* About halfway through the checker
I'm going to merge with master to avoid clashing with the declaration
fix.
* Add undefined to Symbol.valueDeclaration
Also add undefined to a number of utility functions that have always
accepted it, but never added it to their type.
* Fix lint from code review
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
* remove obsoleted fix from inferFromUsage
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
* Add undefined to Symbol.declarations' type
Symbol.declarations now has type `Declaration[] | undefined`.
I made a mistake somewhere in the checker related to JS checking, so
there are quite a few test failures right now.
* undo clever change to getDeclaringConstructor
* Address PR comments
1. More early-returns.
2. More line breaks.
* Add 'data' property to completion entry for better cooperation between completions and completion details
* Add doc comment
* Update API baselines
* Add server test
* Test session’s Full result
* Fix tests
* stableSort to fix server fourslash test
* Explicit verification of data parameter
* No array literal subtype reduction when contextual type is present
* Accept new baselines
* Fast path in relations and filtering of pure discriminated union types
* Create maps for mixed unions, but not for small or primitive only unions
* Create many-to-many mapping with certain limits, also use in CFA
* Use constituent maps in CFA for switch statements, cleanup, add comments
* Revert change to apparent contextual type / better criteria for map eligibility
* Deduplicate array literal element types
* Accept new baselines
* Filter in false case only when discriminant property has unit type
* Only subtype reduce unions with less than 100 distinct types
* Accept new baselines
* Caching and quick discriminant checks in subtype reduction
* Accept new baselines
* Remove deduplication logic now that subtype reduction was optimized
* Only enable special assignability rule on string index signatures to 'any'.
* Accepted baselines.
* Added test.
* Accepted baselines.
* Renamed test files.
* Add non-erroring version of bclas'subClassThisTypeAssignable01.ts'
* Accepted baselines.
Co-authored-by: TypeScript Bot <typescriptbot@microsoft.com>
* Fix: checkAliasSymbol crash when checking for @deprecated
It's possible that we shouldn't be creating symbol with no declarations
from non-homomorphic mapped types, but for 4.2, the right fix is to make
the @deprecated-check in checkAliasSymbol ensure that
target.declarations is defined.
* Add bug number and accept baselines
* When structurally comparing similar types, check if we are already in the middle of a more general comparison of those same types
* Do the same, but with only string manipulations
* Eliminate well-known symbols in the checker: 2021 edition
* Actually update the lib text to say unique symbol, too (this is unneeded with compat code in place, but this makes goto-def make more sense)
* Add test showing mismatched symbol constructor type interop
* Add more test cases for some other related issues this fixes
* Revert computed name change
* Style comments
* When noImplicitAny is set, combine multiple contextual overloads into a single signature, rather than producing `any` and an error
* Amalgamate intersection composite signature return types as intersections, rather than the prior exclusively union behavior
* Add another example from an issue, albeit slightly modified
* Fix newlines, add test from DT
* Interior remodelling
* Improve @template lookup and resilience
1. @template parsing may produce a template tag with a type parameter
whose name is the missing identifier. These tags should be skipped
in the checker because they receive an error in the parser.
2. The fix in #37819 was incorrect; there's no such thing as a type
parameter declared on a variable declaration. Instead, there needs to be a type
parameter declared on a jsdoc comment, because that's the scope for tags
like `@return` and `@typedef`.
There are 3 tests because either fix (1) and (2) fix the first test's
failure, but both are required to fix the last two tests' failures.
* remove containsParseError call
* Specified error message for iterating known array types without --downlevelIteration
* Added extra target info to diagnostic
* NodeList too, a classic
* PR feedback: invert to allowsStrings; required param
Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
* Change variable name AllowQualifedNameInPlaceOfIdentifier to AllowQualifiedNameInPlaceOfIdentifier
* Change deleting AllowQualifedNameInPlaceOfIdentifier to deprecating it instead.
* Fix failing tests
* Replace old value
* No did-you-mean-to-call error on casts
I chose to do the ad-hoc check rather than yet another tree walk.
1. It's faster to run and easier to read.
2. This error came from looking at real code. It happened twice, so I
think the best estimate for other uses that happened zero times is in
fact zero.
3. I couldn't think of other places to put the cast, given the
restrictions on `testedNode` just before the new code.
* Skip parentheses
I chose to do the ad-hoc check rather than yet another tree walk.
1. It's faster to run and easier to read.
2. This error came from looking at real code. It happened twice, so I
think the best estimate for other uses that happened zero times is in
fact zero.
3. I couldn't think of other places to put the cast, given the
restrictions on `testedNode` just before the new code.
e350c357 (#40228) introduced a subtle bug: it switched the flags to an
alias, dropping `SymbolFlags.Property` --- and that makes
`symbolIsValue()` get to the `resolveAlias(symbol)` call, which leads to
`getPropertyOfType()` with`resolved.callSignatures`+`constructSignatures`
being `undefined`. So initialize them in `setStructuredTypeMembers`
before calling `getNamedMembers()`.
Fixes#42350
The original error message on the last line I have added to in
functionParameterArityMismatch.ts was
No overload expects 5 arguments, but overloads do exist that expect
either 4 or Infinity arguments.
even if we do not define a function that takes Infinity arguments.
This PR changes it to this:
Expected 0-6 arguments, but got 5 or more.
I feel it is still a bit strange but much more understandable.
Fixes#42418
Make `tracing` either `undefined` or the same namespace as before.
Switching all calls to `tracing?.___` means that there is no cost for
a call or the arguments when tracing is not used. Comparing two runs
without tracing (27 runs, drop 5+5, avg rest) I get:
master:
42.59s user 1.00s system 165% cpu 26.372 total
changed:
42.01s user 0.982 system 165% cpu 26.039 total
(Makes it all private, so no api changes.)
* Commonjs module:create synthetic exports symbol
Previously, the `module` identifier in commonjs modules got a synthetic
type with a single property `exports`. The exports property reused the
file's symbol, which, for a module file, gives the correct exported
properties.
However, the name of this symbol was still the filename of the file, not
`exports`. This PR creates a synthetic symbol for `exports` by copying
in a similar way to esModuleInterop's `default` symbol in
`resolveESModuleSymbol` (although the intent there is to strip off
signatures from the symbol).
* correct parent of synthetic symbol
* Exclude primitive types from union subtype reduction in most cases
* Accept new baselines
* Minor fixes
* Less aggressive checking of assertion function calls that don't affect control flow
* Accept new baselines
* @typedef: Improve error spans from declaration emit
This is a proof-of-concept fix. I think it could be expanded for all of
jsdoc, but I only set it up for jsdoc type aliases. It could use a lot
of polish too.
* track error node in isSymbolAccessible instead
* Switch to using enclosingDeclaration
Remove trueErrorNode
* add test of @callback and @enum
* Better error + fix @enum error
Since enums don't have a name property, you *have* to call
`getNameOfDeclaration` to go looking through the AST for one.
* Support Top Level "for await of".
* Add test cases for top level "for await of".
* Apply suggestions from code review
* add test cases
* remove redundant variables
* fix test baselines
* Update diagnostic message and tests
Co-authored-by: Ron Buckton <ron.buckton@microsoft.com>
* fixesmicrosoft/TypeScript#41286
* Added period to end of deprecation message
* Search Symbol.declarations for deprecated tag instead of Symbol.valueDeclaration
* renamed arg0 to deprecatedEntity, narrowed param type
* Added different deprecation message if signature is available
* address PR comments
Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
* Add --force to npm install script for user tests
* Migrate prettier to docker
* Fix vscode Dockerfile
* Fix stack space issue in isJSLiteralType
* Use --legacy-peer-deps based on npm version
* Fix xterm.js Dockerfile
* Add tests for "Cannot find name 'global'. Did you mean 'global'?"
* Fix "Cannot find name 'global'. Did you mean 'global'?"
* Add an additional test case for spelling suggestions of "global".
* Name the boolean for suggestions being global scope augmentations.
* chore: failing test for const enums and isolatedModules
* fix: const enums + isolatedModules emit invalid code
In `isolatedModules` mode, the compiler does not inline const enums,
but also decides not to `import` them, leaving invalid code that
throws a `ReferenceError` at runtime.
This code:
```
import { SomeEnum } from './bar';
sink(SomeEnum.VALUE);
```
..should compile to either:
```
var { SomeEnum } = require('./bar');
sink(SomeEnum.VALUE);
```
..or (with const enum inlining):
```
sink(1 /* VALUE */);
```
..but actually compiles to:
```
sink(SomeEnum.VALUE);
```
..with no imports, which throws a ReferenceError at runtime.
---
The compiler has already realised that the symbol is a referenced const
enum, it just doesn't use this information when it comes to deciding
whether to emit an import. This commit additionally checks that
information, if we are compiling in isolatedModules mode.
---
In my opinion, this is not the correct fix, but it is the simplest. In
`isolatedModules` mode, `const enum` should probably be a compile error
(because there are no benefits and the complexity is high, and,
apparently, buggy). If not, the compiler should not be checking whether
something is a const enum, and should just be treating it as a regular
enum, and checking as if it was?
Fixes#40499.
* chore: extra test for type-only
* feat: explicitly ban --isolatedModules --preserveConstEnums false
* feat: isolatedModules implies preserveConstEnum
* Update src/compiler/diagnosticMessages.json
Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
* chore: compiler test for argument incompatibility
* Add and fix test for namespace import of const enum
* Fix additional bug with reexport of const-enum-only module
Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
Co-authored-by: Andrew Branch <andrew@wheream.io>
hasNonBindableDynamicName
1. Has 'non' in the name, and is only ever used negated.
2. Is true for a case that's not reflected correctly in the name -- it's
true for non-dynamic names as well.
I considered hasEarlyOrLateBindableName, but decided to use
hasBindableName for now.
* 'in' should not operate on primitive types
* accept baselines of failing tests
* review
* update error message
* check if constraint of right type is assignable to a non primitive or instantiable non primitive
* do not throw errors where narrowing is impossible
* accept baselines
* fix test case failures
* Add more accurate comment discussion and document failing edge case in test
* Update baselines
Co-authored-by: Jonas Hübotter <jonas.huebotter@gmail.com>
* New aliases for type alias instantiations
* New aliases for conditional, mapped, and anonymous object type instantiations
* Accept new baselines
* Fix issues with re-aliasing
* Accept new baselines
* Create separate types for equivalent aliased unions
* Accept new baselines
* Preserve original types for union types
* Accept new baselines
* Preserve intersection origin for union types
* Accept new baselines
* Accept new baselines
* Preserve aliases during relationship checks
* Accept new baselines
* Preserve aliases for intersection and indexed access types
* Accept new baselines
* Compute intersection-of-unions cross product without recursion
* Accept new baselines
* Use denormalized type objects for origin / support 'keyof' origins
* Accept new baselines
* Fix fourslash test
* Recursively extract named union types
* Accept new baselines
* Map on union origin in mapType to better preserve aliases and origins
* Remove redundant call
* Accept new baselines
* Revert back to declared type when branches produce equivalent union
* Accept new baselines
* Don't include denormal origin types in regular type statistics
* Fix issue with unions not being marked primitive-only
* Allow new alias to be associated with type alias instantiation
* Accept new baselines
* Revert "Accept new baselines"
This reverts commit 4507270cc1.
* Revert "Allow new alias to be associated with type alias instantiation"
This reverts commit 2c2d06dfe1.
* Test case where the wrong path is emitted
* If import is used in the file, prefer that import specifier over calculating new one
Fixes#39117
* Update Baselines and/or Applied Lint Fixes
* When non-relative path is used as user preference, ignore relative paths even if they are from the existing file
* Fix test
* Add comment
Co-authored-by: TypeScript Bot <typescriptbot@microsoft.com>
* Add support for abstract constructor types
* Add backwards-compatible overloads for creating/updating constructor types
* Reverting use of 'abstract' in lib/es5.d.ts due to eslint issues
* Update baseline due to reverting lib
* Add error for failing to mark an mixin class as abstract
* Fix declaration/quick info for abstract construct signatures
* Support starting and middle rest elements in tuples
* Accept new baselines
* Include all rest arguments in error span
* Accept new baselines
* Fix tests
* Add new tests
* Fix lint errors
Previously, the error span was too large on @type errors on functions
when the type was not a function. The span covered the entire tag. This
PR changes the error node just to be the type of the type tag. In other words,
the error span was previously this:
```
@type {IncorrectType}
```
But is now just this:
```
IncorrectType
```
Fixes the first error from #41974, but not the other two.
Co-authored-by: Ashya Manning <ashyamanning@pursuit.org>
Co-authored-by: Nilber Remon <nilberremon@gmail.com>
Co-authored-by: Ashya Manning <ashyamanning@pursuit.org>
Co-authored-by: Nilber Remon <nilberremon@gmail.com>
* fix as suggestion.
* Update moduleSpecifiers.ts
* compare symbol rather than string
* fix typo.
* fix
* fix lint.
* better name and more clear code
* fix comment.
Co-authored-by: Orta Therox <git@orta.io>
* Have signature identity checks look at the base constraint of type parameters, allow identical type parameter lists to merge in union signatures
* Update text in fourslash test
* Add whitespace to fix lint, remove duplicate impl
* Consolidate names
* Remove comparisons of type parameter defaults, add more test cases
* Explore at least 10 levels of constraints before checking for deeply nested types
* Simplify constraint depth limiter logic
* Add regression test
* Accept new baselines
* Infer template literal types for template literal expressions
* Update test
* Update another test
* Accept new baselines
* Minor fixes
* Add tests
* Accept new baselines
* Make new TypeFlags internal
* Accept new API baselines
* Ensure template literals assignable to String, Object, {}, etc.
* Add tests
* Detect comparisons between large unions or intersections
If their multiplied size is greater than 1E6 (chosen based on the repro
in #41517), then we'll expend a large amount of time and memory
comparing them, so record a trace event.
Related to #41517
* Make an exception for primitive union comparisons
* Address PR feedback
* Pick up baseline change from master
* Eliminate diagnostic and only trace
* Don't check reportErrors
* Less aggressive wildcard check, 'keyof any' constraint for 'infer T' in mapped type constraint position
* Accept new baselines
* Add regression tests
* Allow type-only ImportEqualsDeclarations
* Suppress CJS-in-ESM error when type-only
* Add grammar error on import type in import alias
* Update API baselines
* Fix importsNotUsedAsValues with ImportEqualsDeclarations
* Make bad error talk words more good for Daniel. Fixes#41603
* One more error message baseline update
* Update transformer and emitter
Fixes#41586Fixes#41588
1. For binary expressions, if the immediate parent is an IfStatement,
then check the body of the if statement. I didn't walk upward to find an
IfStatement because in my experimentation I found that binary expression
uncalled-function errors are only issued when the expression is on the left of the
top-most binary expression.
2. For property accesses with interspersed calls, I added a
CallExpression case. In fact, any expression could appear here, but I
only want to fix calls for now since that's all we've observed in
Definitely Typed, and we didn't see anything else in the user tests or RWC
tests. I also didn't examine parameters of the intermediate call
expressions, but I don't think it's needed since the intent is to avoid
false positives.
* Remove-all-unused-identifiers skips assigned identifiers
Previously, fixUnusedIdentifier worked the same in fix-all mode as for a
single fix: identifiers with assignments would be deleted:
```ts
function f(a) { }
f(1)
```
becomes
```ts
function f() { }
f()
```
But any kind of argument will be deleted, even one with side effects.
For a single codefix invocation, this is probably OK.
But for fix-all, this could lead to multiple changes
spread throughout a large file.
Now fix-all will only delete parameters and variable declarations with
no assignments:
```ts
function f(a) { }
function g(a) { }
f(1)
g
let x = 1
let y
```
becomes
```
function f(a) { }
function g() { }
f(1)
g
let x = 1
```
* Don't remove assigned parameters for single codefix either
* add optional parameter test case
* Skip initialised params and binding elements
Based on PR feedback from @amcasey
* fixAll removes unused binding patterns completely
* Fixes from comments
Thanks @amcasey for the thorough review
* fix trailing space lint
* correctly remove-all array binding
* Add actual baselines for a problem with global namespace being preferred over config & pragma implicit ones
* Fixed an issue with global React namespace being preferred over config & pragma implicit ones
* Do not try to mark JSX classic runtime symbols as used when automatic runtime is used
* Add tracing support to tsserver
Read the `TSS_TRACE` environment variable to determine which directory
trace files should be written to.
Notable changes from tsc tracing:
1) Drop all tracepoints that depend on type IDs
2) Write output to trace.PID.json
3) New, server-specific events (request/response, cancellation, etc)
* Drop try-finally blocks that aren't strictly necessary
* Fix lint error
* Trace background work (for diagnostics)
* Move try-finally blocks into session so tsc doesn't use them
* Add missing try-finally
* Use consistent capitalization
* Inline canPop call where underlying variable is available
* Clarify comments
* Include PID in build-mode file names
* Introduce more efficient popAll function
* Trace throwIfCancellationRequested rather than isCancellationRequested
* Remove unnecessary try-finally blocks
* Add a command-line argument for consistency with logging
* Fix rebase issues
* Address PR feedback
* Rename completionEvents to eventStack
* Drop assertStackEmpty as hard-to-maintain and marginally valuable
* Rename stepCancellation to stepCanceledEarly
* Rename stepEarlyCancellation to stepCanceled and use flag instead
* Check correct variable on exit
Storing the arguments on the stack will make it possible to forego
try-finally blocks when we start tracing in server scenarios, which have
to handle cancellation.
Fixes resolution of export aliases in the postfix-property-access case
of commonjs require:
```js
const { x } = require('./foo').nested
x
```
This program would previously fail if `x` was an export alias.
Fixes#41422
* Add tests
* Dont look at object or function type when looking for members of `export=` type to be resolved by named imports
Fixes#37165
* Create separate cache when skipping function and object property augmentation
* Lookup in both cache if not skipObjectFunctionPropertyAugment
* Support xml namespace prefix for JSX elements and attributes
Just as with the `-` character, `:` is now also treated specially in JSX
element and attribute names, but is only allowed a single time, and not
at the beginning or end of the name, as is specified in the JSX spec.
All tests in jsxInvalidEsprimaTestSuite still fail, but for slightly
different reasons now. Two lines in jsxEsprimaFbTestSuite were
uncommented as they included elements with namespaces, and they now pass
without error.
* Add case for colons at ends of identifier
* Add case for jsx namepsace intrinsics
* Add cases with upcase idents for jsx namespaces
* Add case for jsx namespaces with react option
* Always consider jsx names with colon to be intrinsics
* Adjust comment about chars valid in jsx names but not js idents
* Fix minor typo in namespace prefix test case variable name
* Remove misleading comments on isUnhyphenatedJsxName
* Use ts.map for stylistic consistency
* Show error only if noImplicitAny is set
* Accept baseline for noImplicitAnyIndexing
* Fix lint error
* Add test cases for indexedAccessWithFreshObjectLiteral
* Don't record Ternary.Maybe results in cache during recursive variance measurement
* Add regression test
* Accept new baselines
* Use Ternary.Unknown to signal variance recursion
* Add comments
* Fix comment
* Fix: `E` events need to have the same information that is on the
corresponding `B` events. (Superseded below.)
* Use `I` (not `i`) for instant events, so they show in devtools
too. (Though they don't go through the flame chart as they do in
`about://tracing`, so they're not nearly as useful.)
* Abstract the code that writes the records in a single `writeEvent`
local function.
* Make `args` optional, and default to `undefined` (which will not add
them) at all.
* Drop the `{ "ts": ... }` wrapper around the `args`, after verifying
that having arguments with names like `begin`, `end`, `pos`, `id`
doesn't interfere with either UIs.
* Add `tracing.push`/`tracing.pop` for complete events, change a few
`.begin`/`.end` to use these. (The caveat is that until there's an exit
handler to dump unterminated events, these won't show in the dump. When
that's done the push/pop variant can be used everywhere.)
* Add meta lines to name the process and the thread, and a line that
avoids the warning when opening in devtools.
* Move anonymous type instantiation cache from AST node to root type
* Use "root" type reference as cache location for deferred type references
* Add test
Co-authored-by: Andrew Branch <andrew@wheream.io>
```js
const x = require('./foo').y
```
was incorrectly using the unmangled require path as the temp name in
emit:
```
import ./foo_1 = require('./foo')
import x = ./foo_1.y
```
It now uses the imported identifier:
```
import x_1 = require('./foo')
import x = x_1.y
```
Discovered while fixing #37832
* Update package-lock.json
* Suggesting a library for a missing property/method
* Added more types and added tests
* Added more tests to cover all the latest features
* Added bigintarrays and dataview methods
* Fixed typo in template
* Transform old error message to use 2nd template slot
* Removed test that has been split up between es2015 and es2016+
* Use empty arrays and remove unnecessary function call
* merge
* Added early bail-out and updated baselines
* Implemented early bail-out (misread)
Co-authored-by: TypeScript Bot <typescriptbot@microsoft.com>
* Fix reference types in @typedef
Previously this code path was broken and untested. Fortunately the fix
is simple.
* add test case from #40234
* update baselines
* Fix noUncheckedIndexedAccess for tuple rest elements
* Defer inclusion of undefined for generic indexed access types
* Create separate IndexedAccessTypes depending on whether --noUncheckedIndexedAccess applies
* Undo accidental export
* Parenthesize for clearer precedence