Commit graph

15144 commits

Author SHA1 Message Date
Nathan Shively-Sanders
7cf4b12d88
Fix crash for private identifier in expando assignments (#37764)
* Fix crash for private identifier in expando assignments

It does this by disallowing private identifiers from expando assignments
entirely. I haven't thought of a scenario where they make sense, but I
haven't thought about it exhaustively either.

Fixes #37356

* Update baselines

I think the new error is probably better. It's certainly different!
2020-04-03 10:29:22 -07:00
Wesley Wigham
6d25c01d09
Cache the regularized form of union types (#37749)
* Cache the regularized form of union types

* Inline function because why not

* Introduce two fastpasths into isRelatedTo
2020-04-02 23:54:24 -07:00
Anders Hejlsberg
349ae45a2c
Reduce intersections with conflicting privates, elaborate on reasons (#37762)
* Elaborate on reasons for 'never' intersections

* Accept new API baselines

* Accept new baselines

* Add tests

* Accept new baselines

* Address CR feedback
2020-04-02 18:00:59 -07:00
Nathan Shively-Sanders
527f467926
Remove error when spreading optional any (#37757)
Previously, spreading an optional any gave a bogus error when the name
conflicted with earlier properties in the object literal. Now the code
checks any types for optionality before issuing the error.

Fixes #37740
2020-04-02 15:04:45 -07:00
Wenlu Wang
afc41f095d
Quick fix for functions lacking return expressions (#26434)
* stash

* add surmise for return type

* add support for more case

* add more test case

* add more testcase and fix all test

* fix changed diagnosis

* fix broken test case

* add more case

* rename quickfix

* fix conflict

* fix fix desc

* fix semi

* Avoid replace brace with paren

* Split fix all action

* Add return work in same line

* fix test cases

* rename baseline

* refactor and handle comment

* Support semi

* make helper internal
2020-04-02 10:06:14 -07:00
Wesley Wigham
78a99241d8
Reuse input type nodes when serializing signature parameter and return types (#37444)
* Accept change

* Accept the huge set of ever so slightly changed baselines

* Update return type logic to only reuse nodes if original nodes share scope with current node, like property types, only reuse nodes if symbols referened are acessible, reuse nodes for property signatures, too

* Only reuse nodes when a context is provided (otherwise identifier printback may fail)

* Only track symbol if symbol is found and no error is recorded

* Fix type parameter reuse lookup

* Forbid cjs module.exports references in retained nodes

* Adjust check for cjs export references to not include bad module type in output

* Add symbol to all identifiers we see in existing nodes for quickinfo

* Accept fourslash baseline updates

* Accept slightly updated baseline post-merge

* Do not copy original nodes for error types, replace empty type references with any
2020-04-01 19:50:21 -07:00
Wesley Wigham
15aff05ff6
Explicitly merge module augmentation members into the exports added by export * declarations (#37691)
* Explicitly merge module augmentation members into the exports added by export * declarations

* Use ?., add namespace merge test

* Add missing merged symbol call to handle enum/ns merges during entity name lookup

* Add test with error case

* Handle missing value declarations in more places, unify duplicate declaration error handling to improve assignment declaration duplicate errors
2020-04-01 16:36:28 -07:00
Alexander T
c546988e50
fix(37456): omit type arguments from JsxSelfClosingElement, JsxOpeningElement nodes (#37739) 2020-04-01 16:27:33 -07:00
Wesley Wigham
326e1c9ff8
Disallow partial matches for discriminant properties when generating error messages (#37589) 2020-04-01 15:39:12 -07:00
Alexander T
697d1042eb
fix(37519): forbid trailing comma in a index signature (#37535) 2020-04-01 15:38:10 -07:00
Nathan Shively-Sanders
95a124f802
Fix crash on bad namespace parse (#37626)
* Fix crash on bad namespace parse

`global` inside a class body is parsed as a module declaration, and in
the following example has no body:

```ts
class C {
  global x
}
```

`x` is parsed as a separate ExpressionStatement. This caused a crash in
emit because the code didn't expect a module declaration with no body.

* inline node.body variable

* fix missed references to body
2020-04-01 15:05:49 -07:00
Sheetal Nandi
0b38a9a2b0
Add support for extraFileExtensions on WatchCompilerHost (#37726)
To support typescript-eslint/typescript-eslint#1813
2020-04-01 11:13:21 -07:00
Wesley Wigham
0e48e68ed1
Fix post-LKG build 2020-04-01 10:53:46 -07:00
Simon Jaeger
9c4cbd64fb
fix #32843 : evaluate right scope when checked if all type parameter are unused for jsdoc @template (#33320)
Co-authored-by: magierjones <simon.jaeger@magierjones.de>
2020-03-31 15:32:15 -07:00
Nathan Shively-Sanders
4dc827e22a
Fix emit of simple module.exports.C.prototype pattern (#37719)
Extends the fix of #36108 so that the simple example gets correct emit;
the complex test case I came up with still doesn't work correctly, but
the actual code froma #35228 is fixed.
2020-03-31 14:59:47 -07:00
pizzacat83
a46e9aea10
support 'in' type guard of intersections (#37106) 2020-03-31 13:37:08 -07:00
Andrew Branch
23b500cadf
Don’t offer this. completions on self, window, global, globalThis. Disambiguate this. completions from others in details requests. (#37652)
* Special-case window, self, global, globalThis methods

* Disambiguate global and this property completions in details requests

* Hide the Map<boolean> implementation

* Update old tests

* Replace SymbolOriginKind stringification with dedicated enum
2020-03-31 12:40:57 -07:00
Anders Hejlsberg
2b0f351005
Fix narrow-by-constructor logic (#37698)
* Fix narrow-by-constructor logic

* Add regression test
2020-03-30 19:31:16 -07:00
Nathan Shively-Sanders
f17174ceb0 Fix build after merging #35862 2020-03-30 15:13:20 -07:00
Titian Cernicova-Dragomir
3433434142
Fixed issue where missing method call went unreported if the call target symbol did no have an id assigned or if the called property was used inside the if block on a different target. (#35862) 2020-03-30 14:45:32 -07:00
Jack Williams
0e15b9f245
Make never rest type top-like (#35438)
* Make never rest type top-like

* Add higher-order test

* properly support types which reduce to never

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-03-30 14:16:07 -07:00
Wesley Wigham
2f0cc51fee
Fix contextual types for maybe-async callbacks (#37205)
* Fix contextual types for maybe-async callbacks

* Remove comment
2020-03-30 14:15:51 -07:00
Neal Burger
9cd4b070ab
Add link to documentation in tsconfig.json template generated by tsc --init (#34686)
* Add Advanced Compile Options to --init command

* removed advanced options and descriptioncolumn

* tests: fix tsconfig.json baselines

* tests: fix failing tests

* feat: adjusted link to specification

* fix: removed duplicate increment flag

* chore: moved position back

* return of the comments

* fix for missalignment

* return of the comment
2020-03-30 14:14:00 -07:00
uhyo
1f56ab02f0
Improve error message for invalid return type of JSX component (#32702)
* New diagnostic message for wrong JSX function component

* Component and Mixed type

* fix existing tests

* add new test for JSX component return type error

* fix tslint error

* update diagnostic message to include component name

* accept baseline

* update tests

* missing semicolon

* accept baseline

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-03-30 13:04:33 -07:00
Jack Williams
4c440e5e5b
Fix #31319 : Narrow unit-unit inequality tests using comparability (#33071)
* Narrow unit-unit inequality tests using comparability

* Accept updated baselines

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-03-30 12:49:53 -07:00
Alexander T
d8170faee1
fix(33054): allow variables starting with an underscore in for/of statement (#36739) 2020-03-30 11:18:18 -07:00
Alexander T
96f01227d4
fix(36909): wrong error message when trying to named-import an export (#36925) 2020-03-28 12:16:50 -07:00
Alexander T
3c130d1317
feat(37092): improve error message about missing default export (#37212) 2020-03-27 14:33:01 -07:00
Sheetal Nandi
7f5994958b
Handle comment directives in incremental parsing (#37632)
* Add test case that shows failure to handle commentDirectives in incremental parsing
Testcase for #37536

* Handle comment directives in incremental parsing
Fixes #37536
2020-03-27 12:00:34 -07:00
Sheetal Nandi
0ae938b718
Report error when cannot read file (#37611)
This also consolidates helper for readFile failure
2020-03-25 21:29:02 -07:00
Ron Buckton
9119fe3797
Fix sys.debugMode when using VSCode's new preview debugger (#37558) 2020-03-25 19:18:36 -07:00
Ron Buckton
4fc4c4e3d6
Revert 'awaited' type (#37610) 2020-03-25 18:39:45 -07:00
Sheetal Nandi
84a3252e76
Handle packages inside another node modules package when auto importing (#37561)
Fixes #37542
2020-03-25 16:27:02 -07:00
Sheetal Nandi
fd9e602fcf
When the global file is deleted mark all files as changed (#37538)
* Add test case when the errors are not refreshed if global file is deleted
Testcase for #36728

* When the global file is deleted mark all files as changed
Fixes #36728

* Update other baselines to fix file info
2020-03-25 16:26:10 -07:00
Ron Buckton
b58a29b808
Fix emit for optional chain with non-null assertion (#36539)
* Fix emit for optional chain with non-null assertion

* Treat '!' differently inside chain vs end of chain

* remove dead code and fix comment
2020-03-25 15:28:13 -07:00
Wesley Wigham
4567fc4f1a
Ensure computed property names are always checked (#37307) 2020-03-25 15:16:54 -07:00
Sheetal Nandi
6c1e8aa0ad
Sort the arrays of fileNames in the build info (#37541)
* Sort the arrays of fileNames in the build info
Earlier we did this in testing to ensure we could baseline now moved to actual build info writing
Fixes #37156

* Sort using compareStringsCaseSensitive
2020-03-25 14:57:46 -07:00
Rustin
8615eecfc1
Enhancement new expression with type arguments without parenthesized argument list error message (#37576)
* Enhancement new expression with type arguments without parenthesized argument list error message

Signed-off-by: Rustin-Liu <rustin.liu@gmail.com>

* add baselines

Signed-off-by: Rustin-Liu <rustin.liu@gmail.com>

* use parseErrorAt

Signed-off-by: Rustin-Liu <rustin.liu@gmail.com>

* refine code

Signed-off-by: Rustin-Liu <rustin.liu@gmail.com>

* Space before paren

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-03-25 12:37:46 -07:00
Andrew Branch
37569d01f6
Convert to async function: handle type arguments to then/catch (#37463)
* Handle type arguments to then/catch

* Keep single-line types on a single line
2020-03-24 09:56:47 -07:00
Sheetal Nandi
11043b0951
Check JSDocPropetyTag (#37544)
Fixes #37040
2020-03-23 17:20:35 -07:00
Jack Works
38e717a244
fix: hyphened name not auto-completed by the ls (#37455)
* fix: hyphened name not auto-completed by the ls

* fix: accept new baseline

* Adds a test to validate the hypened identifiers in JSX

Co-authored-by: Orta Therox <orta.therox@gmail.com>
2020-03-23 17:08:44 -04:00
Anders Hejlsberg
fde9c7f555
Narrowing from truthy unknown to object (#37507)
* For x && typeof x === 'object', narrow x to just type object

* Add tests

* Allow arbitrary nesting / add comments

* Add additional tests
2020-03-20 17:09:24 -07:00
Ron Buckton
e3ec7b18b8
Add the 'awaited' type operator (#35998)
* Add the 'awaited' type operator

* Add script to manually add reviewers to a PR when GH 'Suggested Reviewers' breaks

* Fix lint error in review script

* Only defer generic awaited type for possible thenable

* Add variance-like behavior for awaited

* Switch awaited type params to 'unreliable' variance

* fix typo in inferTypes

* LKG without syntax in lib

* LKG with new syntax in lib

* Add 'strictAwaitedTypes' flag

* Treat strictAwaitedTypes as strict-mode flag

* Rename TAll, remove duplicate definition of 'race'

* Apply suggestions from code review

Co-Authored-By: ExE Boss <3889017+ExE-Boss@users.noreply.github.com>

* Fix inference priority

* Update comment to isGenericAwaitableType

* Add overloads for then/catch to Promise

* Add inference heuristic for T | PromiseLike<T> (for any PromiseLike)

* Remove strictAwaitedTypes flag

Co-authored-by: ExE Boss <3889017+ExE-Boss@users.noreply.github.com>
2020-03-20 16:09:01 -07:00
Sheetal Nandi
8f64d667f2
If emitting declaration file, update the d.ts signature in state to not have to save all files when different file changes without changing its shape (#37483)
* Add test that calling getAffectedFiles on two different files (even if the second one is saved) returns all files

* If emitting declaration file, update the d.ts signature in state to not have to save all files when different file changes without changing its shape
Fixes #30508
2020-03-20 10:16:41 -07:00
Sheetal Nandi
5e9c43607f
Handle auto import scenarios when using project references (#37482)
* Add test for project reference and auto import
Test for #34677

* Add project reference redirect to the possible file name to import if file is source of project reference redirect
Fixes the auto import suggestion when project is built

* Use fileExists that mimics presence of project reference redirect file when trying to get auto import file name
2020-03-19 16:53:44 -07:00
Eli Barzilay
ec95c27b4d
Fix getSignatureOfTypeTag (#37473)
Prevents infinite looping as in #37265.

Fixes #37265
2020-03-19 19:02:39 -04:00
Anders Hejlsberg
e15a9fb3a8
Track tuple type recursion in inferFromObjectTypes (#37479)
* Track recursive tuple types in inferFromObjectTypes

* Add regression test
2020-03-19 14:05:33 -07:00
Sheetal Nandi
7e07a2b5d1
Allow rich response for compile on save (#37462)
Fixes #30739
2020-03-19 14:03:21 -07:00
Wesley Wigham
c513a4adea
Allow nested conditionals to be related via constraints (#37208)
* Allow nested conditionals to be related via constraints

* Delete word in comment
2020-03-19 12:03:50 -07:00
Allan Guwatudde
a83ce339c9
Fix poor error span for unclosed JSX tags in the presence of whitespace/comments (#37419)
* Improve jsx tag error span

* Move solution to parseJsxChild func

* Add tests and update baselines

* Update comment in src/compiler/parser.ts

Co-Authored-By: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>

* Use skipTrivia to check for whitespaces and other trivia

* Import React into  errorSpanForUnclosedJsxTag.tsx

* .

* .

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-03-19 11:40:43 -07:00
Wesley Wigham
e2156a1535
Add huge maximal length for noTruncation mode (#37461) 2020-03-19 10:45:00 -07:00
Andrew Branch
237ea526f9
Preserve newlines from original source when printing nodes from TextChanges (#36688)
* Allow emitter to write multiple newlines in node lists

* Progress

* Progress

* Fix recomputeIndentation

* Add tests, fix leading line terminator count

* Do a bit less work when `preserveNewlines` is off

* Fix accidental find/replace rename

* Restore some monomorphism

* Fix single line writer

* Fix other writers

* Revert "Fix other writers"

This reverts commit 21b0cb8f3b.

* Revert "Fix single line writer"

This reverts commit e535e279f9.

* Revert "Restore some monomorphism"

This reverts commit e3ef42743a.

* Add equal position optimization to getLinesBetweenRangeEndAndRangeStart

* Add one more test

* Actually save the test file

* Rename preserveNewlines to preserveSourceNewlines

* Make ignoreSourceNewlines internal

* Optimize lines-between functions

* Add comment;

* Fix trailing line terminator count bug for function parameters

* Preserve newlines around parenthesized expressions

* Back to speculative microoptimizations, yay

* Don’t call getEffectiveLines during tsc emit at all
2020-03-19 09:46:00 -07:00
Wesley Wigham
667f3b411e
Allow assertion signatures to narrow by discriminant (#37310) 2020-03-18 21:16:55 -07:00
Alexander T
ac3dc0c4d4
fix(37287): check appropriate context with enabled useDefineForClassFields (#37323) 2020-03-18 17:03:07 -07:00
Alexander T
0aa2e2783c
feat(37409): add fix all quick fix to fixInvalidJsxCharacters (#37436) 2020-03-18 09:54:17 -07:00
Anders Hejlsberg
0222211acb
Support for/of variables in assertion checking (#37432)
* Support for/of variables in assertion checking

* Integrate with "dotted name" logic

* Add tests
2020-03-17 19:20:56 -07:00
David Sherret
48e1745d6d
Fix Node#getStart(sourceFile, true) throwing when node has a js doc and no parent (#37439)
* Fix missing source file argument.

* Add test

* fix lint

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-17 16:08:57 -07:00
Alexander T
66aa9e77bf
fix(36247): disallow 'constructor' as a parameter property name (#37285) 2020-03-17 14:48:05 -07:00
Josh Goldberg
878f447798
Clarified file-not-found error for reference paths without extensions (#35956)
* Clarified file-not-found error for reference paths without extensions

* Updated error message to include extensions

* update baselines missed in merge

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-17 14:21:23 -07:00
Sheetal Nandi
e60bbac84f
Fix declaration emit when the packages are included through symlinks (#37438)
* Convert symlink scenarios to virtual FS where its symlinks are correctly maintained
Adds test for #36866

* Fix the casing issue when redirects differ in casing of the file

* Make ModuleSpecifierResolutionHost internal

* Refactoring for ModuleSpecifierResolutionHost

* If any of the file path option is from node_modules folder, consider only paths in node_modules folder

* Update src/services/utilities.ts

Co-Authored-By: Andrew Branch <andrewbranch@users.noreply.github.com>

Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
2020-03-17 13:21:40 -07:00
Alexander T
a510cad873
fix(36936): fix crash caused by resolving non existent export (#37077) 2020-03-17 13:21:20 -07:00
Alexander T
f1eb9898fb
feat(36908): add 'property overwritten by spread' error for jsx attributes. add related span for conflicting declaration in spread (#37329) 2020-03-17 13:13:38 -07:00
Andy Hanson
b0450aed56
Add codefix for --noImplicitThis (#27565)
* Add codefix for --noImplicitThis

* Code review

* Back to building post-merge

* Remove redundant functions + update tests

Infer-from-usage also inserts `this: any` parameters when needed, so I
removed that from fixImplicitThis.

Otherwise, fixImplicitThis has better suggestions than inferFromUsage,
so I moved inferFromUsage later in the suggestion order.

* More redundancy removal

Don't need to add `@this` anymore either since inferFromUsage will do
that.

* More baseline updates

From moving inferFromUsage down in priority I think?

* remove now-redundant ad-hoc jsdoc emit

* fix more bad merge

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-17 13:00:14 -07:00
Anders Hejlsberg
9120497a33
Flatten immediately nested conditional types in the false position (#36583)
* Flatten immediately nested conditional types in the false position

* Add test

* Accept new baselines

* Handle nested distributive types with different checkType

* Allow deeply nested immediately resolving conditionals without any syntactic requirements or implementation contortions

Extract logic into function

Co-authored-by: Wesley Wigham <wewigham@microsoft.com>
2020-03-16 16:40:04 -07:00
Sheetal Nandi
2458c8a016
When the imported module is through node_modules and symlink to folder that isnt node_modules (#37387)
* Add tests that fail because of symlink to non common directory node_modules

* When the imported module is through node_modules and symlink to folder that isnt node_modules
Most of the monorepo like scenarios are like this so looking at symlink to decide if file can be imported is essential
Fixes #28689
2020-03-16 11:15:39 -07:00
Anders Hejlsberg
b8baf48043
Fix assignment of intersections to objects with optional properties (#37195)
* Treat intersections of only objects as a single object in relations

* Exclude intersections containing non-inferrable types

* Accept new baselines

* Update test

* Accept new baselines

* Add tests
2020-03-14 09:45:05 -07:00
Klaus Meinhardt
8b6bd41ce7
getPropertiesOfUnionOrIntersectionType: handle types with index signature (#31979)
* getPropertiesOfUnionOrIntersectionType: handle types with index signature

Fixes: #31565

* fix test

* more testing

* fix typo in checker.ts

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-13 14:30:53 -07:00
Alexander T
fc30095e8b
feat(33792): add new quick fix service to handle missing call in condition (#37152) 2020-03-13 13:38:44 -07:00
Wesley Wigham
47b60ece0b
Make substitution types even if the substitution base isnt a type variable (#37348)
* Make substitution types even if the substitution base isnt a type variable

* Broaden usage of getConditionalFlowTypeOfType to _all_ type lookups

* Align comments
2020-03-13 11:02:11 -07:00
Alexander T
b41eb1bc61
feat(36249): add quick-fix action to declare a property as private which starts from underscore (#36632) 2020-03-13 10:33:56 -07:00
Wesley Wigham
df523b30cf
Filter the type of a binding pattern to not include undefined is the pattern parent has an initializer (#37309) 2020-03-12 17:50:05 -07:00
Donald Pipowitch
e0f6ecd957
improve error message TS2307 (#27054)
* improve error message TS2307

* add updates missed from merge

* update more missed baselines

* remove incorrectly re-added test files

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-12 15:55:54 -07:00
Sheon Han
b014e2b568
Show token hints for missing closing braces (#36317)
* Add error for missing brace in object literal

* Add new baseline test

* Update all affected tests
2020-03-12 15:52:02 -07:00
Ryan Cavanaugh
0426e48828
Fix crash when host.getSourceFile returns undefined (#37373)
Another day, another incorrect non-null assertion

Fixes #37368
2020-03-12 15:45:56 -07:00
M.Yoshimura
f06f809c75
Treat write-only-access to a class member with setter as a reference. (#35922)
* Treat write-only-access to a class member with setter as a reference.

* Add test case for unused private members, special-casing the member with a setter.
2020-03-12 15:41:40 -07:00
Jack Williams
dcc73944f4
Fix 33436 (#35225)
* Fix 33436

* Fix code

* Fix error message after bad merge

* Remove whitespace
2020-03-12 15:40:14 -07:00
Klaus Meinhardt
7bd6209fbc
Don't parse duplicate JSDoc for ExpressionStatement starting with ParenthesizedExpression (#36289)
* don't parse JSDoc on ExpressionStatement if it starts with ParenthesizedExpression

* update test
2020-03-12 14:42:49 -07:00
Sheetal Nandi
a76a16696d
Move useSourceOfProjectReferenceRedirect to program so other hosts can use it too, enabling it for WatchHost (#37370) 2020-03-12 13:11:11 -07:00
Sheetal Nandi
1f710167de
Ensure that we have seenAffectedFiles map when files are added to pending emit because they were present in the old state (#37302)
* Make the systems for baselining default to pretty

* Ensure that we have seenAffectedFiles map when files are added to pending emit because they were present in the old state
This happens in build scenarios since semantic diagnostics are queried before emit and hence files are added to seenAffectedFiles pending emit
Fixes #37269
2020-03-12 10:54:30 -07:00
Anders Hejlsberg
41a80f5d92
No infinite recursion in excess property and weak type checks (#37360)
* New IntersectionState.ExcessCheck flag to ensure no infinite recursion

* Add regression test
2020-03-12 09:40:15 -07:00
Andrew Casey
9e97b00ca1
adds error message for using value as type argument (#37359)
This addresses issue #28975
(https://github.com/microsoft/TypeScript/issues/28975).

When providing a value as a type argument, we can suggest a more specific
error message: "Did you mean to use typeof T?"

adds error message

WIP: Detect error

WIP: progress

updated tests

janky implementation

adds test coverage around literal types being unaffected

refactor out isIdentifierATypeArgument function

adds test case for type alias

adds test case for nested type arguments

fixes linting errors

merge master into branch to overwrite changes

changes value as type error message

This suggests 'typeof T' as a potential alternative when we give an error
about using value T as a type.

remove stale tests from old change

Co-authored-by: John Patterson <john@johnppatterson.com>
2020-03-11 19:18:17 -07:00
Sheetal Nandi
1a9c8197ff
Optimize module resolution cache for watch and editor (#37055)
* Refactor resolveName

* Have resolutions of failed lookups as array and resolved to fileName map
2020-03-11 14:35:26 -07:00
Anders Hejlsberg
6856c012d2
Use objects instead of closures for type mappers (#36576)
* Use objects instead of closures for type mappers

* Flatten combined type mappers

* Single point of creation for type mappers

* More optimizations

* Fix lint error

* Fewer symbol instantiations / discard type mapper after instantiation

* More optimizations

* Simplify mapper layout and cache in composite mappers

* Removing cache as it doesn't seem to matter much

* Get rid of identityMapper
2020-03-11 13:28:49 -07:00
Austin Cummings
ae3d28b5eb
Implement constructor type guard (#32774)
* Implement constructor type guard

* Fix code review issues for constructor type guard.
- Do not limit constructor expression to only identifiers
- Fix `assumeTrue` and operator no-narrow check
- Use better way to check that identifier type is a function
- Loosen restriction on what expr is left of ".constructor"
- Update typeGuardConstructorClassAndNumber test to include else cases

* Fix grammar & spacing in `narrowTypeByConstructor`

* fix bad merge

* switch (back?) to crlf

* update baselines

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-11 13:16:33 -07:00
Anders Hejlsberg
b78ef30cb7
No union subtype reduction during type inference (#37327)
* No union type subtype reduction in getImplicitIndexTypeOfType

* Add regression test
2020-03-11 10:27:51 -07:00
Arpad Borsos
5937ffdf25
Add constructor functions for {Symbol,Node}Links (#36845)
Using a constructor function like this can help node better optimize
object allocation. This improves memory usage when compiling
`src/compiler` from **277M** to **270M**, a nice ~3% win.
2020-03-11 08:40:51 -07:00
Wenlu Wang
20625a964b
add promise.any (#33844)
* add promise.prototype.any

* add AggregateError

* Update src/lib/esnext.promise.d.ts

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>

* update baseline again

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-11 08:36:00 -07:00
Jack Williams
67ca82b375
Add flag to omit default case (#33574) 2020-03-10 15:04:03 -07:00
Anders Hejlsberg
c4da90368f
Infer to erased signatures (#37261)
* Use erased signatures as inference targets

* Add tests
2020-03-10 08:42:36 -07:00
Sheetal Nandi
e68524a8d2
Handle WatchCompilerHost without timeout methods to retrieve correct Program (#37308) 2020-03-09 16:30:52 -07:00
Josh Goldberg
bf15eac16e
Removed unused host variable in createProgramHost (#37278)
As stated in 26417, `host` is only ever written to and never read from. `createProgramHost` is the only place I could find that provides a member for `ProgramHost`'s `onCachedDirectoryStructureHostCreate`, so that's removed as well.
2020-03-09 13:53:49 -07:00
Andrew Branch
bc0e5a241c
Fix longer type-only property access in non-emitting heritage clauses (#37264)
* Fix longer type-only property access in non-emitting heritage clauses

* Rename misnomer function
2020-03-09 12:05:36 -07:00
Sheetal Nandi
8dede43365
Reset hasChangedAutomaticTypeDirectiveNames once new program is created (#37266)
* Allow passing watch to the change as parameter

* Reset hasChangedAutomaticTypeDirectiveNames once new program is created
Also dont invoke afterProgramCreate if the program is not new
2020-03-06 18:21:16 -08:00
Ben Lichtman
631def81d5
Merge pull request #37260 from uniqueiniquity/watchFileExistsFix
Fix fileExists check for a watch program
2020-03-06 13:01:03 -08:00
Ben Lichtman
0ed21e34ed Fix file exists check for watch program 2020-03-06 09:44:16 -08:00
Nathan Shively-Sanders
458977b94b
Reinstate incorrectly removed esnext.bigint (#37233)
* Reinstate incorrectly removed esnext.bigint

From a bad merge I made in #33845

* fix esnext.bigint alias
2020-03-05 10:11:48 -08:00
Orta
ffde92349d
Added @ts-expect-error to @ts-ignore directives (#36014)
* Added @ts-expect-error to @ts-ignore directives

Similar to `// @ts-ignore`, but will itself cause a new error diagnostic if it does not cause an existing diagnostic to be ignored.

Technical summary:
1. The scanner will now keep track of `CommentDirective`s it comes across: both `@ts-expect-error` and `@ts-ignore`
2. During type checking, the program will turn those directives into a map keying them by line number
3. For each diagnostic, if it's preceded by a directive, that directive is marked as "used"
4. All `@ts-expect-error` directives not marked as used generate a new diagnostic error

* Renamed to getDiagnosticsWithPrecedingDirectives per suggestion

* Added JSDoc comment I thought I did already

Co-authored-by: Orta <orta.therox+github@gmail.com>
2020-03-05 10:37:36 -05:00
Nathan Shively-Sanders
0a1af90bb6
add string.prototype.replaceAll (#33845)
* add string.prototype.replaceAll

* accept baseline

* fix bad merge in tests

* update missed baselines

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-04 13:25:17 -08:00
Nathan Shively-Sanders
061338e82b
Don't inferFromIndexTypes() twice (#34501)
* Don't inferFromIndexTypes() twice

* Add tests
2020-03-04 13:19:35 -08:00
Eli Barzilay
5c8def9a06 Fix emitting ?.
Use `emit()` for writing `questionDotToken`, leading to properly calling
the emit hooks (which `emitTokenWithComment` doesn't) and printing the
comments.  This fixes #35372 by calling its hooks to set the `.__pos`
and `.__end` fields.

Also, remove `getDotOrQuestionDotToken` which was used only here --
mainly because it seems likely to encourage misusing the
`questionDotToken` again.

Also, fix a bunch of `visitor` -> `tokenVisiton` calls in
`visitorPublic.ts`.
2020-03-04 14:52:33 -05:00
Ryan Cavanaugh
67930fc163
Don't crash when there's no class type to derive a 'this' type from (#37164)
Fixes #37161
2020-03-04 09:34:28 -08:00
Wesley Wigham
dfc0b58fe7
Preserve arity for preserving js optional parameters (#37173) 2020-03-04 00:48:53 -08:00
Nathan Shively-Sanders
b481dd4d4b
More precise property-overwritten-by-spread errors (#37192)
* More precise property-overwritten-by-spread errors

Trying to do this check in getSpreadType just doesn't have enough
information, so I moved it to checkObjectLiteral, which is a better
place for issuing errors anyway.

Unfortunately, the approach is kind of expensive in that it

1. creates a new map for each property and
2. iterates over all properties of the spread type, even if it's a
union.

I have some ideas to improve (1) that might work out. I'm not sure how
bad (2) is since we're going to iterate over all properties of all
constituents of a union.

Fixes #36779

* another test and rename
2020-03-03 15:10:19 -08:00
Alexander T
3046a54401
fix(36883): accessor allows this parameter but is not checke… (#36889) 2020-03-03 12:26:41 -08:00
Alexander T
176241cca9
fix(36238): allow aliases in spelling suggestions (#37168) 2020-03-03 10:58:29 -08:00
Wesley Wigham
5941c6e1b1
Emit an any for namepath types (#37176) 2020-03-03 10:55:21 -08:00
Alexander T
ab8adc5f95
fix(37135): handle PrivateIdentifiers in isPropertyName (#37184) 2020-03-03 10:51:50 -08:00
Wesley Wigham
b9c0999a2a
Thread host.useCaseSensitiveFileNames through program and node builder into specifier generation (#37170) 2020-03-03 10:50:01 -08:00
Wesley Wigham
67c6cebfc8
Reinterpret a type parameter constrained to any as an upper bound constraint (#29571)
* Reinterpret a type parameter constrained to any as an upper bound constraint

* Use real constraqint in alias in test

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-03 09:51:15 -08:00
Andrew Casey
dd6811fbe3
Stop looking for the default configured project at node_modules (#35011)
* Optionally stop looking for the default configured project at
node_modules

* Make stopping at node_modules non-optional

* Generalize and simplify the change - node_modules files don't have default configured projects
2020-03-02 16:52:03 -08:00
Wesley Wigham
ff0422091f
Update LKG (#37175)
* Update LKG

* Remove unneeded check (handled by top of function)
2020-03-02 15:15:41 -08:00
Wesley Wigham
af4201ff51
Retain reexports in js emit even when they export nothing (#37124) 2020-03-02 14:33:53 -08:00
Wesley Wigham
d209092ccc
Use merged symbol to pick up js-alias-merged members on export assignments (#37162) 2020-03-02 12:57:00 -08:00
Nathan Shively-Sanders
392fd0ac0b
Remove bogus @implements errors (#37114)
* Remove bogus @implements errors

Make the search for the actual host more comprehensive by reusing the
code that previously only searched for functions. I don't know what to
call this function now, since the old name wasn't accurate either.

* undo gratuitous name change

* Improve name and make calling more uniform

It's slightly less efficient but I think worthwhile for readability.
2020-03-02 09:48:53 -08:00
Anders Hejlsberg
a5796cf3b2
Remove ordering restrictions in control flow analysis (#37134)
* Don't reset CFA type for x.y when x is narrowed

* Add tests

* Accept new baselines

* Remove unnecessary type assertion
2020-02-29 12:03:09 -08:00
Anders Hejlsberg
be4b814a4c
Reduce intersections by discriminants (#36696)
* Treat never-like intersections as never

* Accept new baselines

* Fix compiler issues revealed by increased intersection correctness

* Delete fourslash tests that are no longer applicable

* Include isNeverLikeIntersection check in getNormalizedType

* Erase never-like types in several more places

* Check that base types are not never-like

* Add comments

* Revert isNeverLikeType check in getIndexType (keyof shouldn't resolve member types)

* Introduce getReducedType for union and intersection types

* Don't reduce in getApparentType

* Avoid relationship check in resolveMappedTypeMembers

* Accept new baselines

* Don't call getReducedType in getIndexType

* Ensure reduced and unreduced forms of a type can compare identical

* Reduce types before converting them to string representation

* Accept new baselines

* Reduce intersections before obtaining keyof X

* Add tests

* Accept new baselines

* Fix comment in tests

* Don't infer from empty intersection types

* Add tests

* Accept new baselines

* Defer instantiation of mapped type property types

* Accept new baselines

* Include more precise type in diagnostic

* Accept new baselines

* Minor optimization

* Improve error message

* Optional properties in intersections are never discriminants
2020-02-28 17:06:44 -08:00
Wesley Wigham
f31ff2dac0
Revert #36907 (#37122) 2020-02-28 15:53:24 -08:00
Andrew Branch
f9945f5acf
Full support for CommonJS auto-imports in JS (#37027)
* Support add new requires

* Always use destructuring for requiring default exports

* Add more tests

* Update existing fourslash tests

* Use `getExportsAndPropertiesOfModule`

* Add UMD test

* Apply suggestions from code review

Fix typos

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-28 14:34:20 -08:00
Wesley Wigham
c6c2c4c8d5
Hoist initial assignment to exported names in cjs to they are not blocked by bindings made by __exportStar (#37093)
* Hoist initial assignment to exported names in cjs to they are not blocked by bindings made by __exportStar

* Copy hoisted identifiers so they do not create sourcemaps

* Accept updated baselines
2020-02-28 13:25:28 -08:00
Andrew Branch
0a6ee7753d
Grammar error on export type * (#37064)
* Recognize `export type *` syntax, but disallow it

* Add more comments to test

* Revert recognizing invalid forms as type-only

* Revert more
2020-02-27 16:35:15 -08:00
Pathurs
5c85febb0c
Fix Get/Set being enumerable (#32264)
* Fix Get/Set being enumerable

fixes #3610

* fix tests

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-27 14:08:20 -08:00
Wesley Wigham
e7c578a67d
Reapply contextual type when recalculating array literals as tuples (#37071) 2020-02-27 14:02:28 -08:00
Eli Barzilay
e71614a185 Proper treatment of splicing tuples in array literals
Fixes #32465.

After this was done, I continued to extend the implementation to handle
TupleLike types but it'ss broken since JS doesn't allow splicing
TupleLike values into array literals so pulled that out, and instead
keeping it for reference below.  (It Includes tests, which are broken
too.)

modified   src/compiler/checker.ts
@@ -22268,6 +22268,21 @@ namespace ts {
                         else hasNonEndingSpreadElement = true;
                     }
                 }
+                else if (spreadType && isTupleLikeType(spreadType)) {
+                    let i = 0, tupleEltType: Type | undefined;
+                    while (tupleEltType = getTypeOfPropertyOfType(spreadType, "" + i as __String)) {
+                        elementTypes.push(tupleEltType);
+                        i++;
+                    }
+                    const stringIndexInfo = getIndexInfoOfType(spreadType, IndexKind.String);
+                    const numberIndexInfo = getIndexInfoOfType(spreadType, IndexKind.Number);
+                    if (stringIndexInfo || numberIndexInfo) {
+                        if (stringIndexInfo) elementTypes.push(stringIndexInfo.type);
+                        if (numberIndexInfo) elementTypes.push(numberIndexInfo.type);
+                        if (i === elementCount - 1) hasEndingSpreadElement = true;
+                        else hasNonEndingSpreadElement = true;
+                    }
+                }
                 else {
                     if (inDestructuringPattern && spreadType) {
                         // Given the following situation:
new file   tests/cases/compiler/spliceTupleLikesWIntegers.ts
@@ -0,0 +1,23 @@
+declare const sb: { [0]: string, [1]: boolean };
+
+let k1: [number, string, boolean];
+k1 = [1, ...sb];
+
+let k2: [number, string, boolean, number];
+k2 = [1, ...sb, 1];
+
+// declare const sb_: [string, ...boolean[]];
+
+// let k3: [number, string, ...boolean[]];
+// k3 = [1, ...sb_];
+
+// declare const sbb_: [string, boolean, ...boolean[]];
+
+// let k4: [number, string, ...boolean[]];
+// k4 = [1, ...sbb_];
+
+// let k5: [number, string, boolean, ...boolean[]];
+// k5 = [1, ...sbb_];
+
+// let k6: [number, string, boolean, boolean, ...boolean[]];
+// k6 = [1, ...sbb_];
new file   tests/cases/compiler/spliceTupleLikesWStrings.ts
@@ -0,0 +1,23 @@
+declare const sb: { 0: string, 1: boolean };
+
+let k1: [number, string, boolean];
+k1 = [1, ...sb];
+
+let k2: [number, string, boolean, number];
+k2 = [1, ...sb, 1];
+
+declare const sb_: { 0: string, [s: string]: (boolean|string) };
+
+let k3: [number, string, ...(boolean|string)[]];
+k3 = [1, ...sb_];
+
+declare const sbb_: { 0: string, 1: boolean, [s: string]: (boolean|string) };
+
+let k4: [number, string, boolean, ...(boolean|string)[]];
+k4 = [1, ...sbb_];
+
+// let k5: [number, string, boolean, ...(boolean|string)[]];
+// k5 = [1, ...sbb_];
+
+// let k6: [number, string, boolean, boolean, ...(boolean|string)[]];
+// k6 = [1, ...sbb_];
2020-02-27 16:43:29 -05:00
Nathan Shively-Sanders
6c5c48c74c
Exempt ambient [#]private from unused error (#37050)
* Exempt ambient [#]private from unused error

These declarations exist to create nominality so they _must_ be unused.
There should be no error for them.

* Switch to fourslash test

I don't know how to baseline suggestion diagnostics in the compiler
tests.
2020-02-27 13:18:43 -08:00
Sheetal Nandi
188c3b7046
Measure module and type reference directive times (#37054) 2020-02-27 10:22:40 -08:00
Titian Cernicova-Dragomir
f883bf3acb
Adding support for @implements. (#36292)
* Adding support for @implements.

* Fixed code review issues for @implements, added some more tests.

* Fixed declaration emit for @interface

* Improved getImplementsTypes to not cache the results since it is only used once.

* Removed unnecessary checks from getImplementsTypes
2020-02-27 09:27:37 -08:00
Alexander T
baff821594
fix(36989): 'async' modifier cannot be used in an ambient context.ts (#37010)
* fix(36989): omit 'async' modifier for methods in declaration files.

* remove useless condition
2020-02-27 00:11:29 -08:00
Sheetal Nandi
d07761fe39
Allow --composite false or --composite null on the command line (#36997)
* Add tests for specifying composite as command line option

* Allow passing --composite false on commandline

* Add test to verify tsc --composite false from command line

* Handle "undefined" as option value to be set to undefined for that option

* Support "null" as option to be converted to undefined which is normally end result from our config file as well

* Support null as option for any tsconfig only option as well, and dont support undefined

* Fix public api test case

* Validates objects instead of stringify result

* Add composite true to base source
2020-02-26 15:26:26 -08:00
Ryan Cavanaugh
c4e96856ac
Detect circularities when removing 'undefined' from defaulted params (#37023)
Fixes #37008

Note that referencing a variable in its initializer is a TDZ error;
the OP report had OOB logic that prevented this in practice (?)
2020-02-26 14:59:04 -08:00
Andrew Casey
b424f36e9a
Expose call count for instantiateType in extendedDiagnostics (#36797)
* Expose call count for instantiateType in extendedDiagnostics

* Update API baselines
2020-02-26 12:55:28 -08:00
Nathan Shively-Sanders
af901ba911
No error on this exprs in static property inits (#36781)
No error on `this` expressions in static property declaration
initialisers when targetting ESNext and with useDefineForClassFields. In
this case the emit is correct and the types are correct, so the error
should not be issued.
2020-02-26 09:07:45 -08:00
Wesley Wigham
454cdb8279
Retain undefined initializations (#36806)
* Emit an export assignment even when the initializer is elided

* User a void 0; and elide assignments for enum/namespace-sourced exported variables

* HAHA, SIMPLIFY GREATLY
2020-02-26 08:48:18 -08:00
Wesley Wigham
15dd0002ef
Unwrap substitutions both before _and_ after potential simplification (#32116)
* Unwrap substitutions both before _and_ after potential simplification

* Repeatedly unwrap/simplify until no more can be performed

* Use seperate loops for source and target to reduce redundant calls

* Move loop into function

* Inline worker
2020-02-25 17:36:56 -08:00
Wesley Wigham
4d5464e1f9
Revert "Support declaration emit for late bound element accesses assigned to functions in both TS and JS (#36593)" (#37034)
This reverts commit 3e4ce4777d.
2020-02-25 16:40:38 -08:00
Anders Hejlsberg
9ed73ebbbf
Properly handle control flows from returns in try/catch within IIFE (#36901)
* Properly handle control flows from returns in try/catch within IIFE

* Accept new baselines

* Add tests

* Accept new baselines

* When end of finally is unreachable, end of try statement is too

* Add additional test case
2020-02-25 16:14:00 -08:00
Sheetal Nandi
e89df5ce6f
Handle getScriptVersion correctly to ensure program structure is checked correctly (#36808)
* Fix tests when there are project references but has disableSourceOfProjectReferenceRedirect

* Handle getScriptVersion correctly to ensure program structure is checked correctly
Fixes #36748

* Harness's language service host doesnt have getProjectVersion.
This means earlier we were creating fresh program everytime we did LS operation
Now we reuse same program, so quick info depends on order of quickinfo demands

* Because same program is used, it unvails a bug that if `export=` is evaluated before finding references, it cant find all definitions from the merge

* Update src/server/project.ts

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>

* Make clearSourceMapperCache required

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-25 16:11:21 -08:00
Wesley Wigham
e99173a6f9
Ignore data- props when excess property checking (#36952) 2020-02-25 15:52:24 -08:00
Ryan Cavanaugh
43863cafe2
Check for undefined source.symbol (#37021)
Fixes #37014
2020-02-25 13:46:24 -08:00
Wesley Wigham
3e4ce4777d
Support declaration emit for late bound element accesses assigned to functions in both TS and JS (#36593) 2020-02-25 13:45:27 -08:00
Wesley Wigham
7d8dc730b7
Baseline arity checks for jsx sfc tags (#36643)
Finish comment

PR feedback
2020-02-25 13:44:22 -08:00
Wesley Wigham
e536c89872
Add js-equivalent test for the binary expression stress and introduce trampoline into getJSSyntacticDiagnosticsForFile (#36724)
* Add js-equivalent test for the binary expression stress and introduce trampiline into getJSSyntacticDiagnosticsForFile

* Update src/compiler/parser.ts

Comment text update

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>

* Fix lint

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-25 13:29:34 -08:00
Wesley Wigham
01f81dfc00 Add helpers to helper list, per comment on #36806 2020-02-25 11:46:05 -08:00
Wesley Wigham
e54b796301
Declare dependencies between helpers in the declaritive fashion introduced by #35967 (#37001) 2020-02-25 11:29:59 -08:00
Wesley Wigham
e120762390
Remove unneeded branch from getHelperName (#36998) 2020-02-25 11:29:45 -08:00
ExE Boss
5e40f32f66
fix(helpers): Use hasOwnProperty.call 2020-02-25 14:13:58 +01:00
Ron Buckton
177713ef45
Switch Debug.assertX functions to use asserts conditions (#36995)
* Switch Debug.assertX functions to use asserts conditions

* Replace assert functions with ts.noop when assertion level too low
2020-02-24 18:20:58 -08:00
Andrew Casey
b5bd38bcdc
Convert UnionOrIntersectionType.couldContainTypeVariables to ObjectFlags (#36947)
...to save space (and possibly to reduce de-opts, since it appears to be
lazily set).
2020-02-24 18:18:39 -08:00
Andrew Casey
865c1209de
Use couldContainTypeVariables to short-circuit instantiateType (#36951)
This is particularly impactful for large unions of string literals.
2020-02-24 17:50:44 -08:00
Nathan Shively-Sanders
3e3df8702c
Fix crash on aliased,exported @enum tag in jsdoc (#36996)
THe code to bind `@enum` and `@typedef` didn't handle the case that the
`@enum` was on a property assignment to an alias of module.exports.
Specifically, `x` needs to be correctly aliased to the file's symbol in
the example below:

```
var x = module.exports = {};
/** @enum {string} */
x.E = {
  A: "A"
};
```
2020-02-24 16:13:18 -08:00
Wesley Wigham
65e7acce58
Use getters to define live export bindings refresh (#35967)
* use getters to define live export bindings

* fix scoping in export* helper

* Object.defineProperty cannot be used in ES3 target

* Accept changed baselines

* Use function expression, not arrow function

* Update importStarHelper to match export helper in binding-making

* Fix whitespace

* Adjust whitespace in edited helpers

* Use new helper for setting bindings, use unscoped __exportStar helper for exports so helpers get reused more

* Accept updated baselines

* Use __createBinding for individual reexports when target is es3

* Remove unneeded type assertion

* Singeline the helpers

* Add check for createBinding helper, accept updated baselines with shortened helper

Co-authored-by: Michael Rawlings <mirawlings@ebay.com>
2020-02-24 15:36:14 -08:00
Ryan Cavanaugh
2b69b2281a
Properly handle both special export forms when renaming (#36914)
* Properly handle both special export forms when renaming

Fixes #36713

* Lint
2020-02-24 13:17:02 -08:00
Ron Buckton
fd8000dd59
Fix class emit in converted loop body (#36795) 2020-02-24 10:55:13 -08:00
Wesley Wigham
ebca423a6e
Add elaboration & quickfix for async-able arrow function (#36342) 2020-02-21 15:51:02 -08:00
Nathan Shively-Sanders
6b645f582b
Fix find-refs crash on JSDocNamepath (#36941)
JSDocNamepaths span a lot of identifiers that we don't actually care
about, so it's incorrect for createChildren to add its children as
synthetic nodes.
2020-02-21 15:37:11 -08:00
Klaus Meinhardt
24dd93fc2b
Fix access of protected members on generic this-type (#36928)
Fixes: #36926
2020-02-21 09:33:21 -08:00
Andrew Branch
4d1a1b850a
Expose importModuleSpecifierEnding to protocol (#36725)
* Expose importModuleSpecifierEnding to protocol

* Update API baselines

* Add explicit auto setting
2020-02-20 13:59:56 -08:00
Wesley Wigham
7f02927b78
use const instead of let for new class iife assignments (#36907) 2020-02-20 12:48:02 -08:00
Alexander T
bf6be75131
feat(36048): handle uncalled function checks in ternaries (#36402) 2020-02-20 09:29:41 -08:00
Wesley Wigham
4a34294908
Unify padding impls and consistently use them 2020-02-19 17:21:51 -08:00
Wesley Wigham
5144330c98
Fix implicit dependencies on es6 lib exposed by node changes 2020-02-19 16:43:40 -08:00
Andrew Branch
1236a1006c
Fix initialization error when destructuring from object literal that includes a spread assignment (#36865)
* Add test

* Fix superfluous error when destructuring from object that includes spread assignment

* Update baseline to include error case

* Remove redundant check
2020-02-19 08:28:12 -08:00
Charles
7cc4a8df94
Wrap classes with decorators or static properties in an IIFE, even for ES2015+ (#32011)
* Always wrap classes with decorators or static properties in an IIFE

Currently only script targets less than or equal to ES5 will wrap classes.  However, the wrapping is also crucial to file size optimizations for ES2015+ as well.  Without the IIFE wrapper, minification tools do not elide the class.  This is due to references to the class being present within the downlevelled decorator and static property code.
This change represents the full completion of issue #15857

* Accept new baselines
2020-02-14 16:28:55 -08:00
Klaus Meinhardt
9b518c8f53
Exempt ambient private properties from noImplicitAny (#36640) 2020-02-14 15:01:18 -08:00
Josh Goldberg
1aaf314678
Marked internal createAnonymousType type as allowing undefined Symbols (#36016) 2020-02-14 14:52:05 -08:00
Andrew Branch
b1e706d911
Set correct pos for NamespaceExport (#36794)
* Set correct pos for NamespaceExport

* Update tests
2020-02-14 12:45:26 -08:00
Anders Hejlsberg
7a1c5b7a20
Avoid expensive relationship checking in mapped type member resolution (#36754)
* Avoid expensive relationship checking in mapped type member resolution

* Accept new baselines
2020-02-12 15:05:01 -08:00
Wesley Wigham
2b64731a97
Fix getTypeAtLocation for as const to not issue a diagnostic (#36741)
* Fix getTypeAtLocation for `as const` to not issue a diagnostic

* use existing helpers for checks

* Fix lint
2020-02-12 13:43:02 -08:00
Ron Buckton
195f6bb2ab Merge branch 'separate-nodetypes' of https://github.com/Swatinem/TypeScript into Swatinem-separate-nodetypes 2020-02-12 11:52:53 -08:00
Nathan Shively-Sanders
01c86c749d
Fix get candidate for overload failure checking (#36744)
* getCandidateForOverloadFailure:call resolveUntypedCall

This re-adds the missed errors and marks as used missed nodes from the
user and RWC baselines.

* Update baselines and remove new test

It was redundant with the old tests

* Defer resolveUntypedCall on resolution failure to give priority to parameter types fixed by overload signatures

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-02-12 11:42:56 -08:00
Ron Buckton
cf6b641709
Merge branch 'master' into separate-nodetypes 2020-02-12 11:23:51 -08:00
Wesley Wigham
6f079a4ebc Update versionMajorMinor to match package.json 2020-02-11 15:34:17 -08:00
Wesley Wigham
8481bc1d98
Do not report errors when we fail to find a module symbol at an import specifier when invoked via API (#36742) 2020-02-11 14:49:11 -08:00
Nathan Shively-Sanders
a772c26a71
Error when property is specified more than once via a spread (#36727)
* add tests but not baselines or fixes

* Update original change

Still probably wrong; probably doesn't even compile beacuse I'm just
typing on my laptop.

* fix error code ok

* notes to self

* Error: property is specified more than once via spread

* make jsx tests stricter

* update semicolon error message

* use ?. because it is great

* use maybeTypeOfKind in new code

* restore jsx error

* add tests
2020-02-11 10:23:15 -08:00
Brad Zacher
348c4dddc6
Throw syntax error for } and > in JSX text (#36636)
* Throw syntax error for `}` and `>` in JSX text

Fixes #36341

* Add codefix for error
2020-02-11 11:44:17 -05:00
Wesley Wigham
aece8c06b0
Allow intersections (and substitutions) to be checks against discriminable unions (#36663) 2020-02-10 15:26:46 -08:00
Nathan Shively-Sanders
71c1da020f
redo #28564 (#36665) 2020-02-07 09:55:29 -08:00
Nathan Shively-Sanders
1e48cbe2c9
Fix jsdoc comment parsing initial state (#36661)
* Fix jsdoc comment parsing initial state

Jsdoc comment parsing can be invoked in two modes:

1. top-level parsing, for comments not inside a tag.
2. tag parsing, for comment that occur after the semantic parts of a
tag.

Top-level parsing skips an initial * because it assumes that it is starting
at the very beginning of a JSDoc comment. Tag parsing does not.

The two modes are distinguished by an optional second parameter named
`margin`. When `margin` is provided, it provides an initial indent used
for comment alignment.

Previously, the check for `margin` was a truthy check `if (margin)`.
This check incorrectly treats `margin=""` the same as
`margin=undefined`.

This PR changes the check to `if (margin !== undefined)`, which
correctly treats `margin=""` the same as `margin="    "`.

* Fixes for broken tests

1. Use SawAsterisk start state.
2. @template needs to skip asterisk in addition to whitespace while
parsing type parameter names.

* undo code move
2020-02-07 08:35:40 -08:00
Anders Hejlsberg
b8b59489e1
Cache results of isGenericObjectType and isGenericIndexType (#36622) 2020-02-05 16:04:05 -08:00
Anders Hejlsberg
de37c87252
Optimize deferred type references (#36607)
* Improve reasoning about when to create deferred type references

* Accept new baselines

* Fix minor issues

* Handle default type arguments case in isDeferredTypeReferenceNode
2020-02-05 16:03:42 -08:00
Anders Hejlsberg
0a160323df
Faster exit from isTypeRelatedTo with identityRelation (#36590)
* Faster exit from isTypeRelatedTo with identityRelation

* Reorganize a bit
2020-02-05 16:03:09 -08:00
Wenlu Wang
70399e146e
add support for Lift Template Literal Restriction (#23801)
* add support for Lift Template Literal Restriction

* rename file and improve comment and tests

* fix NoSubstitutionTemplateLiteral support

* extract tagged template and add more test

* avoid useless parameter

* fix incorrect return node if cannot transform

* accept baseline

* correctly baseline

* accept baseline

* fix merge break

* fix merge break

* inline rescan template head or no subsititution template

* update scan error

* add comment and fix lint

* refactor and fix lint

* avoid blank

* fix merge conflict

* fix again

* fix again

* use multiple target

* fix space lint

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-05 08:59:51 -08:00
Andrew Branch
20471182fc
Fix crash when trying to import a non-exported type (#36619)
* Fix crash when trying to import a non-exported type

* Add related info on each declaration
2020-02-05 08:27:49 -08:00
hafiz
09441107c1
Expose hasOnlyExpressionInitializer as a public type guard (#33229)
Exposes `hasOnlyExpressionInitializer` as a public function so users of
TypeScript compiler APIs do not have to roll their own
`HasExpressionInitializer` type guards.

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-02-04 16:01:20 -08:00
Andrew Casey
da8d3ef0a8
Drop support for defunct Chakra host (#33797) 2020-02-04 15:53:45 -08:00
Alexander T
8c31700735
Enable @typescript-eslint/space-before-function-paren, @typescript-eslint/no-unused-expressions (#36569)
* use @typescript-eslint/no-unused-expressions instead of no-unused-expressions

* enable @typescript-eslint/space-before-function-paren
2020-02-04 14:43:25 -08:00
Orta
7726464abd
De-duplicate indentations in JSX Texts (#36552)
* WIP on making the JSX text node not include whitespace

* Scans to the last newline for JSX correctly

* Handle JSX closing element wrapping

* Offload all jsx text indentation handling to indentMultilineCommentOrJsxText

* Switch from find node -> find inde in formatting

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-02-03 17:09:50 -05:00
Andrew Branch
ef8eb0c876
Fix contextually typed object literal completions where the object being edited affects its own inference (#36556)
* Conditionally elide a parameter from contextual type signature calculation

* Slightly different approach to forbid inference to specific expressions

* Handle nested literals and mapped types correctly

* Delete unused cache

* Rename ContextFlags.BaseConstraint and related usage

* Add tests from my PR

* Update ContextFlags comment

Co-Authored-By: Wesley Wigham <wwigham@gmail.com>

* Update comments and fourslash triple slash refs

Co-authored-by: Wesley Wigham <wwigham@gmail.com>
2020-01-31 15:37:18 -08:00
Nathan Shively-Sanders
ad249043da
resolvedJSDocType should cache on node, not symbol (#36561) 2020-01-31 15:19:45 -08:00
Andrew Branch
86556d6c03
Fix export * that resolves to something type-only (#36558)
* Fix `export *` that resolves to something type-only

* Add same tests but non-tsserver
2020-01-31 15:09:27 -08:00
Ron Buckton
fcf28506aa
Fix overzealous renaming of emit helpers in es module emit (#36541) 2020-01-31 10:41:47 -08:00
Ron Buckton
24d8f795b2
Fix crash in emitTokenWithComment (#36542) 2020-01-31 10:41:09 -08:00
Sheetal Nandi
80ad0de87e
Fixes to handle file names in module resolution watching and createGetCanonicalFileName (#36106)
* Add test case to verify directory casing preservation when watching

* Fix unicode file name handling when watching failed lookup locations

* Add special file name lower conversion routine and use that instead of toLowerCase
Fixes #31819 and #35559

* Remove unicode from code

* Replace toLocaleLowerCase on filenames with ts.toFileNameLowerCase

* Make the intent of using toFileNameLowerCase more clear and why we make the restriction on turkish I with dot on top of it

* Update baselines for newly added tests in master
2020-01-31 10:40:57 -08:00
Eli Barzilay
75d1ead3fd Improvements based on @sandersn's notes 2020-01-30 22:42:04 -05:00
Eli Barzilay
1a1ed7464d Add a similar test for target.symbol.valueDeclaration
(With the same question still open.)
2020-01-30 22:42:04 -05:00
Eli Barzilay
68a9d4592f Avoid testing isClassDeclaration if there's no valueDeclaration
I'm not sure if this is enough -- perhaps it's better to make the test
dig through the interface/s to the class?

Fixes 36059.
2020-01-30 22:42:04 -05:00
Ron Buckton
f24f36350b
Fixes JSX attribute escaping when parent pointers are missing (#35743)
* Fixes JSX attribute escaping when parent pointers are missing

* Fix whitespace change
2020-01-30 16:52:31 -08:00
Hye Sung Jung
8ed129771f
fix spelling errors (#36523)
* fix spelling errors

* remove changes in lib/*
2020-01-30 13:39:54 -08:00
Sheetal Nandi
4c378c09dc
Report config file parsing diagnostics correctly with tsc --b (#36520)
* Refactor the test

* Add tests for syntax errors in tsconfig not being reported

* Report config file parsing diagnostics correctly
Fixes #36515

* Fix errors in existing tests for unintended tsconfig parse errors

* Fix lint
2020-01-30 11:18:06 -08:00
Nathan Shively-Sanders
c1e45ac8af
Fix use-before-def errors for ESNext property declarations (#36465)
* Fix use-before-def errors for ESNext property declarations

Fixes #36441
Fixes #36442

* Handle property declarations in nested classes
2020-01-30 10:58:07 -08:00
Anders Hejlsberg
8a0b8822b2
Fix contextually typed parameter issues (#36476)
* Fix multiple issues with contextually typed parameters

* Accept new baselines

* Fix lint error

* Add tests

* Address CR feedback

* Add fourslash tests
2020-01-30 10:50:39 -08:00
Andrew Branch
2fac535158
Fix type-only imports in interface 'extends' and import=/export= (#36496)
* Handle when files get checked in different orders

* Fix interface extends clause

* Fix import= something type only from a module

* Revert apparently unnecessary addition

* Revert "Revert apparently unnecessary addition"

This reverts commit 7444b0b72e.

* Disallow `import = a.b.c` on anything with type-only imports

* Safety first

* Add test for TS Server single-file open

* Add big comment

* Extract error reporting function for import aliases

* Delete blank line

* Un-export, comment, and colocate some utils

* Combine 3 type-only marking function calls into one

* Add more export default tests
2020-01-29 15:00:17 -08:00
Wesley Wigham
aec732a898
Actually use the caches resolvedJSDocType (#36516) 2020-01-29 14:58:06 -08:00
Nathan Shively-Sanders
36169b4d13
Class fields w/esnext+[[Define]]:no shadow error (#36405)
* Class fields w/esnext+[[Define]]:no shadow error

With useDefineForClassFields: true and ESNext target, initializer
expressions for property declarations are evaluated in the scope of
the class body and are permitted to reference parameters or local
variables of the constructor. This is different from classic
Typescript behaviour, with useDefineForClassFields: false. There,
initialisers of property declarations are evaluated in the scope of
the constructor body.

Note that when class fields are accepted in the ECMAScript
standard, the target will become that year's ES20xx

* add negative test case

* Add explanatory comment
2020-01-29 14:47:44 -08:00
Nathan Shively-Sanders
1bbcb5553a
@typedef's nested Object syntax disallows type arguments (#36172)
Previously the jsdoc index signature syntax was incorrectly treated the
same as Object:

```js
/** @typedef {Object} AllowsNesting
 * @property ... */
/** @typedef {Object.<string,string>} IncorrectlyAllowsNesting */
```

Fixes #34911
2020-01-29 12:53:00 -08:00
Andrew Casey
566202f55d
Fix commas in JSON (#36497) 2020-01-29 10:50:03 -08:00
Nathan Shively-Sanders
c42ef575be
createPrivateIdentifier: names must start with # (#36506) 2020-01-29 10:11:30 -08:00
Nathan Shively-Sanders
0cf100dcf8
Add constructor functions to aliasable expressions (#36108)
* Add constructor functions to aliasable expressions

Fixes #35228, at least the crash. There are still a couple of errors
that are probably incorrect.

Note that isJSConstructor relies on parent pointers and the ability to
merge symbols, so I had to move isAliasSymbolDeclaration (back?) to the
checker.

* add simple test case

* remove errors in test

* fix bad merge
2020-01-29 09:36:59 -08:00
Brandon Bloom
49282d9fba
Nested this container (#36495)
* Add nestedThisContainer test

* Fix #36492
2020-01-29 09:35:23 -08:00
Ron Buckton
6769313eee
Fix potential leaks in checker (#36491) 2020-01-28 16:48:28 -08:00
Sheetal Nandi
8eee8db192
NoEmit and incremental are allowed with listFilesOnly (#36488)
Fixes #32882
2020-01-28 15:59:09 -08:00
Sheetal Nandi
0e9416c7c8
Disallow incremental with noEmit (#36483)
Fixes #32882
2020-01-28 13:11:45 -08:00
Sheetal Nandi
f91f762ced
Fix js declaration emit for exporting default which looks like namespace merge (#36482)
Fixes #35074
2020-01-28 12:21:36 -08:00
Andrew Branch
1bb6ea038f
Allow type-only namespace imports in implements clauses (#36464)
* Add test

* Allow type-only symbols in implements clauses

* Add more complex test
2020-01-27 16:13:30 -08:00
Sheetal Nandi
a87512d21b
Add # to completion trigger character, (#36462)
Handle private identifiers little better by creating token for private identifier when its just #
Report same error as invalid character but from language service we can now provide completions for this.#

Fixes #36367, #36250
2020-01-27 14:25:20 -08:00
Andrew Branch
e1bce187a8
Type-only auto imports (#36412)
* WIP

* Promote existing type-only imports to regular if needed

* Add completions test adding to type-only import

* Update tests, revert whole-import-clause replacement codefix strategy to preserve import specifier formatting

* Revert unnecessary changes

* Delete unused function

* }
2020-01-27 12:53:32 -08:00
Nathan Shively-Sanders
757e67041e
Fix getExpandoSymbol for already-expando symbols (#36457)
* Fix getExpandoSymbol for already-expando symbols

getExpandoSymbol is intended to get the symbol of the expando in a
declaration like

```js
var C = class {
}
```

However, when this occurs in a `module.exports` assignment, alias
resolution already jumps to the exported symbol -- in this case the
expando symbol:

``js
// @filename: first.js
module.exports = class {
}
// @filename: other.js
/* @type {import("./first")} */
var C
```

`getExpandoSymbol` is then called on `class { }` instead of
`module.exports = class { }`.

Previously, `getExpandoSymbol` would incorrectly treat `class { }` the
same as the export assignment and get the expando ... from the expando
itself. This resulted in merging the expando with itself, which causes
bogus errors and could cause other problems.

Now `getExpandoSymbol` checks that the expando "initializer" is
different from the declaration.

* Better check for getExpandoSymbol of expando

Check the declaration directly instead of the initialiser.
2020-01-27 12:32:56 -08:00
Alexander T
c239626f23 fix(36140): handle quotesPreference option in interface implementation (#36398) 2020-01-27 12:25:31 -08:00
Andrew Branch
20e8eba143
Issue better error for exporting primitive type (#36424)
* Issue better error for exporting primitive type

* Delete nonsense
2020-01-27 08:11:21 -08:00
Alexander T
30545006df fix(36068): Incorrect quick fix for undeclared private field i… (#36373) 2020-01-24 18:28:42 -08:00
Wesley Wigham
18cd79e179
Allow infer type variables to have constraints inferred (#32093)
* Allow `infer` type variables to have constraints infered and allow the breakdown of substitutes in simplifiable source inferences

* Still skip conditional inference when `extends infer Q` so such a pattern still acts as a constraint size breaker
2020-01-24 16:59:20 -08:00
Wesley Wigham
08e6bc20bb
Trampolines for large binary expressions (#36248)
* WIP

* Test no longer crashes, but emit trampoline is incomplete and skips pipeline phases

* Fix lints, use non-generator trampoline in emit (still skips pipeline)

* Final version with emitBinaryExprssion work stack that is only used if possible

* Fix lints

* retarget to es2015 for testing

* Use bespoke state machine trampolines in binder and checker

* Remove now extraneous code in parser

* Adjust fixupParentReferences to use a depth first preorder traversal rather than breadth first

* Reintroduce incremental fast bail in fixupParentReferences

* Revert target to es5

* PR feedback

* Small edit for devops rebuild with updated definition

* Fix comment nits, add internally extraneous check back into transformer
2020-01-24 16:29:55 -08:00
Klaus Meinhardt
8e0b091795 es2018: visit other binding elements when transforming object destructuring with rest (#35872)
* es2018: visit other binding elements when transforming object destructuring with rest

fixes: #35771

* more tests
2020-01-24 15:50:29 -08:00
Wesley Wigham
9ef9bb04f1
Fix crash on erroneous enum member merged with exported type alias (#36429) 2020-01-24 15:00:15 -08:00
Nathan Shively-Sanders
368db997ed
ESNext+[[Define]]: reference to param props illegal (#36425)
* ESNext+[[Define]]: reference to param props illegal

When target: "esnext" and useDefineForClassFields: true, property
declaration initialisers should not be able to reference parameter
properties; class fields are initialised before the constructor runs,
but parameter properties are not:

```ts
class C {
  foo = this.bar
  constructor(public bar: string) { }
}
```

emits code that looks like this:

```js
class C {
  bar
  foo = this.bar
  constructor(bar) {
    this.bar = bar
  }
}
new C('x').foo.length // crashes; foo is undefined
```

This PR adds an error on foo's declaration with ESNext+[[Define]].

* improve test
2020-01-24 14:53:28 -08:00
Nathan Shively-Sanders
43fc19c958
Emit statements before super (#36417)
* Emit statements before super

When statements come before super, Typescript's emit is incorrect,
whether there is an error or not. This change preserves statements that
come before super whether there is an error or not.

Here is the case with no errors:

```ts
class Test extends Array {
  p: number
  constructor() {
    console.log("p is initialised in the constructor below super()")
    super()
    this.p = 1
  }
}
```

Notice that `p` is manually initialised in the constructor after
`super()` instead of at the property declaration.

* Update baselines

Parameter properties in the error case now move below the super call.
This is an improvement because it means the code is more likely to execute
correctly.

* remove outdated comments
2020-01-24 14:52:48 -08:00
Wesley Wigham
6b64c883f1
Fix crash on missing parent pointer in binder when transpiling export as ns (#36387) 2020-01-24 13:36:05 -08:00
Wesley Wigham
9e712dd097
Consider SymbolFlags.Method as function-esque during js declaration emit (#36274) 2020-01-24 10:29:23 -08:00
Klaus Meinhardt
49eb0d7a2b Disallow 'declare' modifier on private named properties (#36381)
Fixes: #36345
2020-01-23 13:18:10 -08:00
Sheetal Nandi
677e45ccb8
Dont add "use strict" prologue in json emit (#36380)
* Add test for strict with isolated modules and resolveJson
Test for #36372

* Dont add "use strict" prologue in json emit
Fixes #36372
2020-01-23 13:01:11 -08:00
Andrew Branch
b05dde747c
Update type-only import semantics to allow type queries (#36092)
* Change type-only semantics to allow type queries

* Don’t error using type-only import in ambient context

* Fix default import

* Fix namespace import

* Update more baselines

* Prevent circular resolution

* Track const enum expression usage

* Update baselines

* Perf tuning 1

* Test commit for perf impact

* Weave type-only alias declaration finding into alias resolution

* Fix namespace import of type-only exported symbols

* type-only exports do not contribute to the module object type

* Update APIs

* Fix enum casing, remove type-only conversion suggestion

* Short circuit type-only checks in resolveEntityName faster

* Fix casing in API

* Remove unused parameter

* Fix error on qualified names in type queries

* Allow type-only imports in computed property names

* Fix computed property names of types and abstract members

* Remove unused util

* Commit missing baselines

* Rename “check” functions so as not to overload the word “check”
2020-01-23 12:53:36 -08:00
Klaus Meinhardt
0276e7f910 noErrorTruncation affects semantic diagnostics (#36306) 2020-01-23 11:10:05 -08:00
Wesley Wigham
75f88eee48
Do not short-circuit module visibility calculation when alias visibility is requested (#36339) 2020-01-22 14:49:29 -08:00
Andrew Branch
eac2180e40
Be more tolerant with private identifier parsing, issue more targeted errors, and support private identifiers in forgotten 'this' codefix (#36188)
* Support private identifiers in forgotten this codefix

* Parse invalid private identifiers as identifiers and issue targeted errors

* Update codefix

* Remove accidentally deleted newline
2020-01-22 13:41:15 -08:00
Andrew Branch
1d5749ef78
Fix local and exported type alias merging (#36237)
* Fix local and exported type alias merging

* Add baselines
2020-01-22 13:16:49 -08:00
Anders Hejlsberg
da61231039
Include super.XXX(...) assertion method calls in CFA (#36293)
* Support super.XXX in assertions

* Add tests
2020-01-22 11:21:11 -08:00
Alexander T
38eccbab2a feat(29624): better errors for non-exported types (#36187) 2020-01-21 13:03:22 -08:00
Klaus Meinhardt
342f4c0b54 forceConsistentCasingInFileNames affects module resolution (#36334) 2020-01-21 12:45:13 -08:00
Klaus Meinhardt
1fbe20fe75 resolveJsonModule affectsModuleResolution (#36290)
* resolveJsonModule affectsModuleResolutionFixes: #36251

* fix lint
2020-01-21 11:49:38 -08:00
Klaus Meinhardt
bc1e7728df experimentalDecorators and emitDecoratorMetadata affect builder state (#36297)
* experimentalDecorators and emitDecoratorMetadata affect builder state

* better test
2020-01-21 11:28:55 -08:00
Klaus Meinhardt
2dd21a08f5 useDefineForClassFields affects emit (#36308)
* useDefineForClassFields affects emit

* fix lint
2020-01-21 11:28:04 -08:00
Yacine Hmito
4445e1147c Fix isProgramUpToDate when changing rootFileNames (#36011) 2020-01-21 11:26:17 -08:00
Orta
f588c78aab
Remove the compiler diag 1360 after it got missed in #35751 (#36332) 2020-01-21 11:54:48 -05:00
Wenlu Wang
d2c5d54242 remove duplicate message (#36125) 2020-01-18 14:00:53 -08:00
Alexander T
0dd4c9cebe feat(36231): Improve message for "Remove declaration for: ..." (#36283) 2020-01-18 13:28:19 -08:00
Ron Buckton
50adabe32d
Improve diagnostics and add code fixes for top-level await (#36173) 2020-01-18 12:24:08 -08:00
Anders Hejlsberg
1a10e712e6
Improve variance measurement (#36261)
* No covariance default for recursive references in variance measurement

* Add tests

* Accept new baselines
2020-01-17 11:50:38 -08:00
Sheetal Nandi
57925d4e35
Instead of checking if file exists before file read, handle exceptions from file read (#36244)
Fixes #36236
2020-01-16 17:24:03 -08:00
Anders Hejlsberg
8517df6fa2
Fix erroneous optional chain narrowing (#36145)
* Not all optional chains are narrowable references

* Add regression test
2020-01-16 16:49:51 -08:00
Alexander T
eeff036519 fix(35954): Change spelling for private field incorrectly fixes to a string property (#36079)
* fix(35954): code fix incorrectly fixes private properties spelling issues

* remove duplicate function calls
2020-01-16 09:01:21 -08:00
Alexander T
dbd55b3928 fix(35944): show spell checking quick fix for non-existent private named property access (#36195) 2020-01-15 16:56:40 -08:00
Klaus Meinhardt
f220e62ce7 importsNotUsedAsValue affects semantic diagnostics (#36001)
* importsNotUsedAsValue affects semantic diagnostics

* add tests
2020-01-15 15:08:16 -08:00
Anders Kaseorg
64704a160d sys: Use readdir withFileTypes option to skip lots of stat syscalls (#35286)
This makes walking large directory trees much more efficient on Node
10.10 or later.

See:
https://lwn.net/Articles/606995/
https://www.python.org/dev/peps/pep-0471/
https://github.com/nodejs/node/pull/22020
https://nodejs.org/en/blog/release/v10.10.0/

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2020-01-15 12:42:38 -08:00
Orta
1dafd09a06
Revert "Add related diagnostic to "used before defined" if type is a function that returns a union with undefined (#33171)" (#35751)
This reverts commit be960fa356.
2020-01-15 12:50:52 -05:00
Klaus Meinhardt
6e3ab1529f remove private named properties from rest and spread types (#35950)
* remove private named properties from rest and spread types

Fixes: #35943

* code review
2020-01-14 14:47:39 -08:00
Alexander T
daf786ecd0 throw an error when no default export present (#35815) 2020-01-14 11:38:48 -08:00
Wesley Wigham
08014bca05
Fix lints 2020-01-13 12:50:20 -08:00
Wesley Wigham
69ab1d5ecd
Handle Identifier declarations in getDeclarationSpaces (#36136) 2020-01-13 10:29:37 -08:00
Sheetal Nandi
76ee0214f9
Use watch invoked with node_modules/.staging as watch for refreshing complete node_modules, so that npm install is reflected correctly (#36039)
* Add test that demonstrates npm install watch behaviour some times

* Use watch invoked with `node_modules/.staging` as watch for refreshing complete node_modules, so that npm install is reflected correctly
Fixes #35966
2020-01-10 14:58:01 -08:00
Sheetal Nandi
0c3019e3b3
Handle invalid package.json typings fields when generating specifiers (#36137)
Fixes #35437
2020-01-10 14:51:23 -08:00
Nathan Shively-Sanders
13cddae3f7
Allow references to uninitialized ambient properties (#36112)
Previously these were incorrectly treated just like normal properties:

```ts
class Parent {
    a: any;
    constructor(arg: any) {
        this.a = arg;
    }
}
class Child extends Parent {
    declare a: number;
    constructor(arg: number) {
        super(arg);
        console.log(this.a);  // Property 'a' is used before being assigned. (2565)
    }
}
```

Fixes #35327
2020-01-10 10:50:05 -08:00
Anders Hejlsberg
357f715382
Check combined intersection properties against target index signatures (#35143)
* Check combined intersection properties against target index signatures

* Add tests

* Accept new baselines

* Less aggressive check for index signatures

* Track intersection membership state for both source and target

* Minor fixes
2020-01-10 10:46:10 -08:00
Nathan Shively-Sanders
517d6eea28
Get jsdoc host from chained assignment (#36111)
* Get jsdoc host from chained assignment

getSourceOfAssignment previously only checked one level of binary
expression instead of following binary expressions all the way to the
right. This meant that binding of `@constructor` would fail in the
following example:

```js
/** @constructor */
a = b = function () { }
```

* cleanup lint

* use existing utility
2020-01-10 10:09:39 -08:00
Anders Hejlsberg
94271aa753
Remove CFA discriminant check restrictions (#36114)
* Remove unnecessary containsMatchingReferenceDiscriminant logic

* Accept new baselines
2020-01-10 09:41:16 -08:00
M.Yoshimura
5fc917be2e Fixes broken emit with useDefineForClassFields + private field (#35898)
* Fixes broken emit with useDefineForClassFields + private field

* use simpler function for condition
2020-01-09 10:21:49 -08:00
Anders Hejlsberg
0aab63b7ff
Fix narrowing of optional chains (#36089)
* Check for definitely not undefined instead of maybe not undefined

* Fix comment

* Add tests
2020-01-08 15:37:27 -08:00
Titian Cernicova-Dragomir
3e4578c9f4 Fixed unreported strict property initialization violations. (#35891) 2020-01-08 15:15:20 -08:00
Klaus Meinhardt
38b53790af Allow destructuring the same property multiple times
Fixes: #35939
2020-01-08 14:21:28 -05:00
Sheetal Nandi
9889c74939
Disable declaration emit for json files (#36066) 2020-01-08 09:54:32 -08:00
Daniel Rosenwasser
78748c0a35
More actionable "must have annotation" message (#35839)
* Give an actionable elaboration.

* Accepted baselines.

* Less words.

* Accepted baselines.
2020-01-07 16:46:14 -08:00
Joey Watts
f84b2d20a9 Parse error on private identifier optional chain (#35987)
Previously, this error was reported in the checker, so JS files with
checkJs: false were not erroring on this invalid syntax.
2020-01-07 16:00:15 -08:00
Eli Barzilay
9fbcdb1edb Resurrect SuppressAnyReturnType, but make it used only at the toplevel 2020-01-07 17:12:43 -05:00
Eli Barzilay
724f426468 Remove SuppressAnyReturnType
Following a discussion with Ryan, it seems best to leave any `any`s in
the generated code.
2020-01-07 17:12:43 -05:00
Eli Barzilay
0c467d095f Fix signatureToSignatureDeclarationHelper
Even if `SuppressAnyReturnType` is on, don't supress it if it's a function.

Fixes #35508.
2020-01-07 17:12:43 -05:00
Wesley Wigham
88677de380
Do not omit the anyFunctionType from intersections (#35658)
* Do not omit the anyFunctionType from intersections

* Move check into isEmptyResolvedType
2020-01-07 00:39:28 -08:00
Daniel Rosenwasser
d044e0680a
Renamed references to 'configurePrerelease'. (#35997) 2020-01-06 16:38:46 -08:00
Daniel Rosenwasser
f807b57356
Add s to importsNotUsedAsValue (#36037)
* Pluralize end of 'importsNotUsedAsValue'.

* Updated baselines.
2020-01-06 13:23:47 -08:00
Anders Hejlsberg
f8bfc6f5d6
Contextually typed binding element initializers (#35855)
* Binding element initializers contextually typed by parent initializers

* Accept new baselines

* Literal type widening should be last step in inference

* Accept new baselines

* Add tests
2020-01-06 12:53:23 -08:00
Eli Barzilay
d6c05a1358 Fix getEffectiveTypeAnnotationNode
Prevent it from using the (return) type of a function.  Could also check
the condition before calling the function, but there are two places that
need the check, and OTOH, all calls check the result so returning
`undefined` should work.

(This problem was introduced in PR#32553.)

Fixes #33741.
2020-01-03 22:47:17 -05:00
Andrew Branch
3b396e6124 Type-only imports and exports (#35200)
* Add type-only support for export declarations

* Use a synthetic type alias instead of binding type-only exports as a type alias

* Works for re-exports!

* isolatedModules works fine

* Diagnostic for type-only exporting a value

* Start isolated modules codefix

* Update for LKG control flow changes

* Type-only import clause parsing

* Type-only default import checking

* Type-only named imports

* Fix isolated modules error

* Filter namespaces down to type-only

* Fix class references

* Test nested namespaces

* Test circular type-only imports/exports

* Fix getTypeAtLocation for type-only import/export specifiers

* Fix type-only generic imports

* Update public APIs

* Remove unused WIP comment

* Type-only namespace imports

* Fix factory update calls

* Add grammar errors for JS usage and mixing default and named bindings

* Update updateExportDeclaration API baseline

* Fix grammar checking import clauses

* Enums, sort of

* Dedicated error for type-only enum

* Skip past type-only alias symbols in quick info

* Update error code in baseline

* WIP: convertToTypeOnlyExport

* isolatedModules codefix (single export declaration)

* isolatedModules code fix (all)

* Stop eliding non-type-only imports by default, add compiler flag

* Update to match updated diagnostic messages

* Update more baselines

* Update more tests

* Auto-import as type-only

* Add codefix for splitting type-only import with default and named bindings

* Add more services tests

* Add targeted error message for "export type T;" when T exists

* Add targeted error for "import type T = require(...)"

* Flip emit flag

* Add test for preserveUnusedImports option

* Fix flag flip on import =

* Make compiler option string-valued

* Fix merge conflicts

* Add --importsNotUsedAsValue=error

* Phrasing of messages.

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-01-03 14:39:32 -08:00
Sheetal Nandi
18269c0fc8
Add assumeChangesOnlyAffectDirectDependencies as a option to skip checking and generating .d.ts files for files indirectly importing affected file (#35711)
* Baselining tsc --watch output

* Add noIndirectImports as a option to skip checking and generating .d.ts files for files indirectly importing affected file
Fixes #33329

* Rename option to assumeChangesOnlyAffectDirectDependencies

* Description change as per feedback
2020-01-03 13:02:45 -08:00
ExE Boss
5a342742d0 feat(lib/es2020): Add Promise.allSettled(…) (#34065)
* feat(lib/es2020): Add `Promise.allSettled(…)`

* test(lib): Update tests to account for `es2020.promise`

* fix(lib/es2020): `Promise.allSettled(…)` takes `Iterable` argument

* refactor(lib/es2020): Rename `Promise.allSettled(…)` return type

* feat(lib/es2020): Simplify `Promise.allSettled(…)` type declaration

* refactor(lib/es2020): Improve naming of `Promise.allSettled(…)` types
2020-01-03 12:58:02 -08:00
Anders Hejlsberg
a8944e6844
Fix type parameter leak (#35949)
* Fix cloneSignature to include unionSignatures property

* Add regression test
2020-01-03 07:54:38 -10:00
Daniel Rosenwasser
024b8c1e5f
Merge pull request #30565 from D0nGiovanni/m-template-literal-2
add refactoring: string concatenation to template literals
2020-01-02 17:08:29 -08:00
Titian Cernicova-Dragomir
ded072e8af Fixed find all references for private identifiers. (#35887) 2020-01-02 17:06:25 -08:00
Daniel Rosenwasser
ff4fa1feb9 Cleaned up refactoring names, descriptions. 2020-01-02 16:32:06 -08:00
Daniel Rosenwasser
75ca64120f
Fix error on interfaces in .js files (#35969)
* Use the correct error message.

* Accepted baselines.
2020-01-02 16:30:46 -08:00
Daniel Rosenwasser
ad0f0064ce Remove refactoring from template expression to string concatenation. 2020-01-02 16:12:44 -08:00
Eli Barzilay
4942fd2b84 Make checkPropertyNotUsedBeforeDeclaration ignore properties of properties
Use `isAccessExpression` to cover both `PropertyAccess` and
`ElementAccess`.  Also use it in a few other places that used both
explicitly.  (And also fix a random weird formatting.)

Fixes #32721.
2020-01-02 16:38:54 -05:00
Wesley Wigham
291ab63a9b
Reuse "getBestMatchingType" logic during elaboration to allow for more specific elaborations (#35278)
* Filter target union during elaboration to allow for more specific elaborations

* Reuse best match logic instead

* Update user baselines (#48)

Co-authored-by: TypeScript Bot <ts_bot@rcavanaugh.com>
2020-01-02 13:14:08 -08:00
Max Heiber
36c87aca8a Private named instance fields (#30829)
* Fix display of private names in language server

Signed-off-by: Joseph Watts <jwatts43@bloomberg.net>
Signed-off-by: Max Heiber <max.heiber@gmail.com>

* Parse private names

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* update parser error recovery tests to use ¬ not #

The intent of the tests seemed to be to
regiment the behavior of the parser
when a weird symbol is encountered.

The `#` is now taken by private identifiers,
so `¬` seems like a good new choice for
keeping the diff small, since it also fits in
16 bits (wide emojis would be treated
as multiple characters, since the scanner
uses ++).

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* Private Name Support in the Checker (#5)

- [x] treat private names as unique:
    - case 1: cannot say that a variable is of a class type unless the variable points to an instance of the class
        - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesUnique.ts)
    - case 2: private names in class hierarchies do not conflict
        - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoConflictWhenInheriting.ts)
- [x] `#constructor` is reserved
    - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNameConstructorReserved.ts)
    - check in `bindWorker`, where every node is visited
- [x] Accessibility modifiers can't be used with private names
    - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoAccessibilityModifiers.ts)
    - implemented in `checkAccessibilityModifiers`, using `ModifierFlags.AccessibilityModifier`
- [x] `delete #foo` not allowed
- [x] Private name accesses not allowed outside of the defining class
    - see test: https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNameNotAccessibleOutsideDefiningClass.ts
    - see [test](https://github.com/mheiber/TypeScript/tree/checker/tests/cases/conformance/classes/members/privateNames/privateNamesNoDelete.ts)
    - implemented in `checkDeleteExpression`
- [x] Do [the right thing](https://gist.github.com/mheiber/b6fc7adb426c2e1cdaceb5d7786fc630) for nested classes

mv private name tests together

more checker tests for private names

update naming and cleanup for check private names

for private name support in the checker:
- make names more consistent
- remove unnecessary checks
- add utility function to public API
- other small cleanup

Move getPropertyNameForUniqueESSymbol to utility

for consistency with other calculation of
special property names (starting with __),
move the calculation of property names for
unique es symbols to `utilities.ts`.

private name tests strict+es6

Update private name tests to use 'strict'
type checking and to target es6 instead of
default. Makes the js output easier to read
and tests more surface area with other
checker features.

error message for private names in obj literals

Disallow decorating private-named properties
because the spec is still in flux.

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* Add private instance field transformation, pr feedback

Implements private instance fields on top of the class properties refactor.

This commit also includes incorporation of PR feedback on the
checker, parser, and transformer in order to make the rebase
manageable.

Co-Authored-By: Max Heiber <max.heiber@gmail.com>
Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com>

Signed-off-by: Joey Watts <jwatts43@bloomberg.net>
Signed-off-by: Max Heiber <max.heiber@gmail.com>

Incorporate PR feedback

Fix checker crash with new block scoped bindings

Add classExpressionInLoop test

Update baselines for private name errors

Apply suggestions from code review

Fix privateNameFieldCallExpression test

Remove unnecessary comment

Fix PropertyAccessEntityNameExpression type

Remove PrivateName from PropertyNameLiteral

Add createPrivateName

Remove PrivateName type from textSourceNode

Add Debug asserts for invalid syntax kinds

Don't output private name syntax when undeclared

Make PrivateName extend Node

Update baselines for public API

Fix completions in language server

Fix fourslash test crash

intern private name descriptions

undo expensive node.name.parent assignment

Back the way things were on `master`: only
assign node.name.parent when we need to

Add tests for private names and JSDoc

Patch hoverOverPrivateName fourslash test

Fix goToDefinition for private-named fields

remove Debug.fail for private name outside class

Remove Debug.fail in binder.ts::`getDeclarationName`.
It turns out this code path *does* get hit (intentionally).

For best error messages, return `undefined` and rely
on the parser generating a good error message

"Private names are not allowed outside class bodies"

Add rbuckton test cases for private names

These test cases specifically exercise where
we needed to use name-mangling. They are
cases where private names have the same
description.

- private names no conflict when inheriting
- private names distinct even when
the two classes have the same name

check dup instance+static private identifiers

class A {
    #foo;
    static #foo;
}

not allowed because static and private names
share the same lexical scope
https://tc39.es/proposal-class-fields/#prod-ClassBody

refactor getPropertyForPrivateName, rel spans

refactor getPropertyForPrivateName so
it is easier to read (use findAncestor instead
of loop).

Fix bugs in getPropertyForPrivateName:
- make it work with deeply-nested classes with
and without shadowing
- make it catch shadowing when the conflict is
between static and instance
private name descriptions (these can actually
clash)

And add related spans to diagnostics
for getPropertyForPrivateName

catch conflicts between static and instance
private identifiers:
- cannot have an instance and static private identifier
  with the same spelling, as there is only one namespace
  for private names

rename 'PrivateName' to 'PrivateIdentifier'

to match the change of wording in the spec
prposal:

https://tc39.es/proposal-class-fields/#sec-syntax

The rename in the spec was to avoid confusion
between the AST Node PrivateIdentifier
and the internal spec type PrivateName.

So one uses the [[Description]] of a
PrivateIdentifier to look up the PrivateName
for a given scope.

This corresponds closely to our implementation
in the binder and checker:
- we mangle PrivateIdentifier.escapedText to
get a `key` which we use to get the symbol
for a property

f

getLiteralTypeFromProperty-check privateIdentifier

rename and simplify privateNameAndAny test case

make it clearer that all this test is showing is
that we allow accessing arbitrary private identifiers
on `any`.

Note: we could have something more sound here by
checking that there is a private-named field declaration
in a class scope above the property access.

Discussion:
https://github.com/microsoft/TypeScript/pull/30829/files#r302760015

Fix typo in checker

s/identifer/identifier

remove accidental change

patch fourslash test broken by isPrivateIdentifier

just needed to add a check to see if the symbol
.name is defined

extract reportUnmatchedProperty

per @nsandersn feedback

propertiesRelatedTo was getting to long

pull out the unmatchedProperty reporting into
a seprate function

fix typo in private names test

Fix type soundness with private names

Remove PrivateIdentifier from emit with Expr hint

Fixup helpers and set function name for privates

remove accidentally-committed baselines

These baselines somehow ended up in this pr,
though they have nothing to do with the changes

Revert "getLiteralTypeFromProperty-check privateIdentifier"

This reverts commit bd1155c300bc3517a0543580f4790268f86e473f.

reason: the check for isIdentifier in
getLiteralTypeFromProperty is superfluous because
we do this check in getLiteralTypeFromPropertyName

Update comment in private name uniqueness test 3

I think the comments were not accurate and that we
export the error on `this.#x = child.#x` because:
- private names are lexically scoped: the code in question is not in a
lexical scope under the definition of Child's #x.
- private names are private to their containing class: never inherited

This expected behavior matches that of Chrome Canary and
my understanding of the spec

test private names use before def, circular ref

test private names use before def, circular ref

update diagnosticMessages s/delete/'delete'

per @DanielRosenwasser and @sandersn guidance,
use this style in diagnostic messages:

"operand of a 'delete' operator" (single quotes)

rather than old style:

"operand of a delete operator" (single quotes)

This is for consistency, as we use the new
style in the privateIdentifiers error messages
and it is consistent with our messages about
other operators

incorporate private names early exit feedback

and code style change to use a ternary
instead of if so we can 'const'

require private-named fields to be declared in JS

All fields must be declared in TS files.

In JS files, we typically do not have this requirement.

So special-case private fields, which must always
be declared (even in JS files, per spec)

update debug failure for es2015 private identifier

Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com>

fix checker handling of private name in subclasse

update checker and tests to account for the
following ts features:

- private names do not participate in
the prototype chain, but *are* assigned
in the parent class' constructor. So
parent can access its *own* private fields
on instances of the subclass

Add more tests for private-named fields in JS

add test to hit symbolToExpression w private names

symbolToExpression knows about private names
add a test to exercise this code path

ban private-named static methods (not supported yet)

ban private-named methods (not supported yet)

ban private-named accessors (not supported yet)

fix privateIdentifier fourslash test

change assertion throw to return

Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com>

Update comment in checker.ts re reserved members

Remove case for privateIdentifier in EntityNameExpr

Remove case for privateIdentifier in
EntityNameExpr. That code path is never hit,
and privateIdnetifiers cannot be entity names.

remove unnecessary parentheses

Ban private identifier in enum

As the new test, 'privateNameEnumNoEmit',
shows, the checker now correctly makes
a diagnostic for private identifiers in enums.

However, when noEmit is false we
hit this assertion in the transformer.

This assertion will have to be removed
so that we have a diagnostic here instead
of an assertion error.

When the assertion is removed,
the 'privateNameEnum' baseline
will have to be updated

Fix destructuring assignment, use createCallBinding, remove unneeded helper

Add class private field helpers to external helpers

Remove private identifier enum assertion, use missing identifiers

Fix hash map inefficiency by only using get

Update baselines with empty identifier change

Add privateNameEnum test baselines

Fix private identifier destructuring (array assignment defaults, unique names)

Use createPrivateIdentifierAssignment in destructuring transform

Fix lint error

Separate destructuring target visitor from regular visitor

Fix destructuring assignment with this bindings

Fix destructuring assignment with this bindings

Fix syntax error with destructuring assignment output

Disallow private identifiers in property signatures

remove duplicate test baselines

Add tests for undeclarated private identifiers

remove unnecessary cast

Nicer error message for mis-placed hashbang

Workaround v8 bug with destructured assignments

Optimize private identifier stack lookup

Avoid the cost of performing an array lookup to look at the top of the
private identifier environment stack.

Change function name to be more specific

Changes "getOperatorForCompoundAssignment" to
"getNonAssignmentOperatorForCompoundAssignment" now that this
function is accessible to the entire compiler.

Improve test case for private name assignment

Adds a compound assignment test case for a class with private names
being declared on the left-hand-side of the assignment expression.

Remove extra non-private-field test

Remove isPrivateIdentifierAssignmentExpression helper

Don't transform private names in ESNext target

Preserve private fields initialized to functions

Move function expressions to outer scope for efficiency

Add WeakMap collision check

Modify potential WeakMap collision condition

Fix this property assignment binding with private names

Add correct error message for WeakMap collision

Add error for statements before super with private identifiers

Refactor getPropertyForPrivateIdentifier

Add test for private identifier fields initialized to class exprs

Fix shebang errors

Fix private errors on index signatures

Add codefix for missing private property

Update error messages for unsupported private features

Fix inheritance-related errors

Fixes inheritance-related errors with private identifiers by resolving
properties from base classes. Private identifiers do not show up as
properties on a union type, so those do not type-check.

Add test for interface extending class with private access

Remove debugging log

Remove name assignment from private named functions

Rename to getPrivateIdentifierPropertyOfType

Fix index signature test comment

Fix test target syntax error

Change error messages

patch private identifiers outside class bodies

Add test for private identifier with ooo super

Add test for a class with a private identifier
with a non-preambly (for example, not a comment)
statement before 'super':

should error, saying 'super' must come first

Fix nits

incorporate PR feedback

Incorporate checker feedback

- reorganize if statements in checkFunctionOrConstructorSymbol
- remove overload for getPrivateIdentifierPropertyOfType

reorganize if statements in checkFunctionOrConstructorSymbol

test for private names with JSX

use getPropertyOftype in getPropertyForPrivateIdentifier

getPrivateIdentifierPropertyOfType error on synthetic

make getPrivateIdentifierPropertyOfType  error
if given a node that is not from the parse tree

Simplify checkPrivateIdentifierPropertyAccess

use getPropertiesOfType instead of
rehashing that logic

test for private identifiers w decl merging

fix test target for privateNameDeclarationMerging

update baselines

Fix private identifier ++/-- numeric coercion

Remove 'downleveled' from super error

Fix bad comments in helper call emit

Error on private identifiers in JSX tag names

Add more private identifier tests

Add es2015 target for private name destructured binding test

Add privateNameConstructorSignature test

Add test for navigation bar w private identifier

Remove spurious line from test

// in js file
class A {
    exports.#foo = 3; // should error
}

The above line failed to produce an error
when run using the test harness.

When using tsc or the language server,
we got the expected error message.

Removing the troublesome line, as it
seems to say more about the test runner
than about the code it is testing.

Fix inefficient constructor generation

dts: don't emit type for private-identified field

Do not emit types for private-identified fields
when generating declaration files.

// example.ts
export class A {
    #foo: number;
}

// example.d.ts

export declare class A {
    #foo;
}

**This is not ideal!**

The following would be better:

// example.d.ts

export declare unique class A {
    #foo;
}

See discussion:

https://github.com/microsoft/TypeScript/pull/33038#issuecomment-530321165

notice when private-identified field unused

Notice when private-identified fields are unused,
and implement the same behavior as for unused
private-modified fields.

This is used in the language server to make things
grayed out.

This case generates an error when --noUnusedLocals
flag is passed to tsc:
    - "<name> is declared but never used"

accept baselines

Revert "dts: don't emit type for private-identified field"

This reverts commit e50305df5fb88121486291abad14478f5339a455.

Instead of just excluding the type from private identifier
emit, only emit a single private identifier
per class.

This accomplishes nominality while
hiding implementation detail that
is irrelevant to .d.ts consumers

only emit a single private identifier in dts

In dts emit, emit at most one private identifier,
and rename it to `#private`.

refactor getPrivateIdentifierPropertyOfType

- safer check for wehther is parse tree node
- return undefined when not found (instead of
a Debug.fail)

Incorporate PR feedback

Don't rely on parent pointers in transform

Passes context about whether the postfix unary expression value is
discarded down the tree into the visitPostfixUnaryExpression function.

Remove orphaned test baseline files

remove unreachable if

Check `any`-typed private identified fields

Update private identifier incompatible modifier checks

- disallow 'abstract' with private identifiers
- s/private-named-property/private identifier

Add additional call expression test cases

Fix disallow 'abstract' with private identifier

Static private identifiers not inherited

Including this in the PR for private
instance fields even though static
private identifiers are banned.

Reason: this change
improves quality of error messages,
see test case.

Thanks Ron!

Simplifiy private identifier 'any' type handling

Error on private identifier declarations for ES5/ES3

Bind `this` for private identifier property tagged template literals

Fix target for jsdocPrivateName1 test

Update getPrivateIdentifierPropertyOfType API

Make it easier to use by accepting a string
and location, rather than a PrivateIdentifier.

Thanks Ron!

remove orphaned tests

rename test

remove duplicate tests

Remove unrelated error from test

update diagnostic message 'private identifier'

The nodes for hash private fields are now
called 'private identifier'. Update one last
diagnostic message to use the new terminology.

refine solution for static private identifier fields

- use `continue` instead of `filter` for perf
- better naming
- make it clear the current solution will
need to be altered when we lift the ban on
static private identifier fields, including
a test case that should change in the future

Fix display of private identifiers in lang server

Fix bug where private identifiers in completion
tooltips in the playground were showing up
as the symbol table entries (with underscores and such).

https://github.com/microsoft/TypeScript/pull/30829#issuecomment-534157560
Signed-off-by: Max Heiber <max.heiber@gmail.com>

* fix privateIdentifier w !useDefineForClassFields

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* Disallow PrivateIdentifier in Optional Chains

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* restrict privateIdentifier completions correctly

Don't autocomplete privateIdentifiers in
places where they are not allowed.

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* make PrivateIdentifier not a PropertyNameLiteral

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* Added test.

* Accepted baselines.

* Update symbol serializer to understand private fields in JS `.d.ts` emit.

* Accepted baselines.

* fix for private field no initializer esnext

Signed-off-by: Max Heiber <max.heiber@gmail.com>

* fix private fields .d.ts emit for JS w expando

fix bug where the following in a JS file
would lead to a `#private` in the .d.ts:

```js
class C {
    constructor () {
        this.a = 3
    }
}
```

Co-authored-by: Joey Watts <joey.watts.96@gmail.com>
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2019-12-27 13:07:35 -08:00
Kagami Sascha Rosylight
0f5ddd2ea0 Add es2020 transformation (#35518)
* Add es2020 transformation

* Add missing comma

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2019-12-23 16:45:17 -08:00
Alexander T
320adf5ce0 show an error if --showConfig is enabled and tsconfig.json does not exist (#35723) 2019-12-23 12:30:21 -08:00
Kagami Sascha Rosylight
05a2f1b110 Support bigints in ES2020 (#33874) 2019-12-23 12:18:52 -08:00
Andrew Branch
bed7c89354
Add base constraint completions for JSX attributes (#35803)
* Add base constraint completions for JSX attributes

* Add test for class components
2019-12-23 14:06:46 -06:00
Kagami Sascha Rosylight
d66e959a74 Add ES2020 to diagnostic messages (#35814) 2019-12-23 11:40:41 -08:00
Ron Buckton
6c413e0bbb
Add support for Call Hierarchies in language server (#35176)
* Add support for Call Hierarchies in language server

* Use baselines for callHierarchy tests

* Clean up commented code

* Support multiple hierarchy items when an implementation can't be found

* Use optional chaining in a few places

* Use getFileAndProject
2019-12-22 13:25:09 -08:00
Ron Buckton
114dad7f56
Add top-level await for esnext and system modules (#35813) 2019-12-22 13:24:31 -08:00
Daniel Rosenwasser
35a3a5fbaf Merge remote-tracking branch 'origin' into convert-to-template 2019-12-20 16:46:37 -08:00
Kagami Sascha Rosylight
deb5288e31 Add module: es2020 (#33893) 2019-12-20 16:29:49 -08:00
Wenlu Wang
4c7844be74 Implement export as namespace from (#34903)
* init export start as decl

* fix some broken

* fix more case

* fix more and more case

* make it work

* make lint happy and accept baseline

* add more tests

* fix system module

* add more case

* delete useless assert

* accept baseline

* make lint happy

* fix missing utils

* update api

* make lint happy

* add missing semi

* fix minor issue

* fix locally bound

* avoid useless check

* update public api

* add more case

* fix some case

* Use multi-module selection in test runner to cut down on duplication.

* Accepted baselines.

* remove superfluous tests.

* Remove baseline.

* Downlevel `export * as ns` in es2015.

* Accepted baselines.

* Update names of things.

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2019-12-20 16:00:20 -08:00
Anders Hejlsberg
2f0d07c29a
Increase selectivity of subtype relationship for signatures (#35659)
* Increase selectivity of subtype relationship for signatures

* Add regression test

* Accept new baselines

* Use strictSubtypeRelation for union subtype reduction

* (x: number | undefined) -> void is subtype of (x?: number | undefined) => void

* Accept new baselines

* Add tests

* Accept new baselines

* Address CR feedback

* Fix parameter list length check

* Accept API baseline changes
2019-12-20 14:52:22 -08:00
Nathan Shively-Sanders
3d2b92ce69
Readonly support for jsdoc (#35790)
* Add @readonly

The rule for @readonly on this-assignments in the constructor is wrong.
See failing tests.

* In-progress

Add ctor function test
Add some notes and rename variable

* Done except for cleanup and fix 1 bug

* Fix last test and clean up
2019-12-20 13:47:20 -08:00
Nathan Shively-Sanders
3b7de1a976
remove JSDOC object->any rewrite for noImplicitAny (#35661)
* remove JSDOC object->any rewrite

* reinstate object->any rewrite when noImplicitAny: false

* flip boolean right way round
2019-12-20 09:23:15 -08:00
Nathan Shively-Sanders
2cc1340a7b
Ignore @private/@protected on constructor functions (#35782)
* Ignore @private on constructor functions

This was incorrect in the best of circumstances and caused a crash when
the parent of the function had no symbol, because the accessibility
check assumed it was operating on a constructor and that the parent was
always the containing class.

* Non-constructors are always accessible

Previously, all function-like kinds were accessible, which includes
constructors. This was wrong.
2019-12-20 08:41:52 -08:00
Sheetal Nandi
9445657184
Correctly set filesByName map when reusing program to ensure it is same as old (#35784)
It was previously not populated correctly if preserveSymlinks with useSourceOfProjectReference was true,
in that case if module was resolved to symlink and we deduced it refers to source of project reference we want to set "resolvedFileName" correctly
otherwise it results in incorrect module not found errors.
2019-12-20 07:44:35 -08:00
Sheetal Nandi
ec84392f2e
Use resolvedPath consistently in the builder (#35757)
* Add baseline for #35468

* Use resolvedPath consistently in the builder
Fixes #35468
2019-12-19 10:10:17 -08:00
Nathan Shively-Sanders
3c5ecc2a60
Add jsdoc support for @public/@private/@protected (#35731)
* Add @private/@protected/@public test

* Fix @declaration

* draft abstraction + one usage

* Fill in necessary parsing etc

* make general getEffectiveModifierFlags

move to utilities, make the right things call it

* reorder public/private/protected

* JS declaration emit works with @public/@private/@protected

* revert unneeded/incorrect changes

* Update baselines and skip @public/etc when parsing

1. Update the API baselines with the new functions.
2. Do not check for @public/etc during parsing, because parent pointers
aren't set, so non-local tags will be missed; this wrong answer will
then be cached.

* Parser: don't call hasModifier(s) anymore.

Then move jsdoc modifier tag checks into getModifierFlagsNoCache where
they should be. The jsdoc checks are skipped when the parent is
undefined. There are 3 cases when this can happen:

1. The code is in the parser (or a few places in the binder, notably
declareSymbol of module.exports assignments).
2. The node is a source file.
3. The node is synthetic, which I assume to be from the transforms.

It is fine to call getModifierFlags in cases (2) and (3). It is not fine
for (1), so I removed these calls and replaced them with simple
iteration over the modifiers. Worth noting: Ron's uniform node construction
PR removes these calls anyway; this PR just does it early.

* Fix constructor emit

1. Emit protected for protected, which I missed earlier.
2. Emit a constructor, not a property named "constructor".
3. Split declaration emit tests out so that errors are properly reported
there.
2019-12-18 12:58:12 -08:00
Sheetal Nandi
853507642a
Do not list output files that just change their modified time when using --listEmittedFiles (#35714)
* Baseline incremental scenarios for listEmittedFiles

* Do not list output file that just changes modified time stamp as emitted file
Fixes #35605
2019-12-18 10:24:59 -08:00
Sheetal Nandi
8c1900c74b
Baselining tsc --watch output just like tsc baselines for easier updates (#35710)
* Baselining tsc --watch output

* Fix lint errors
2019-12-18 10:23:58 -08:00
Ron Buckton
2eb60c2cb2
Fix decoding of HTML entities in TSX/JSX (#35739) 2019-12-17 17:32:48 -08:00
Anders Hejlsberg
cafa175501
Properly reflect CFA effects of return in try or catch blocks (#35730)
* Properly reflect CFA effects of return in try or catch blocks

* Add tests

* Accept new baselines
2019-12-17 16:46:34 -08:00
Sheetal Nandi
f90cde4706
Fix completions when the ts installation and project are on two different windows drive (#35733)
* Fix completions when the ts installation and project are on two different windows drive
Fixes #35512

* Fix typo
2019-12-17 14:19:52 -08:00
Andrew Branch
53c8b958d7
Fix formatting scanner on multiline JSX attribute strings (#35705)
* Fix formatting scanner on multiline JSX attribute strings

* Update API
2019-12-16 12:36:40 -08:00
Andrew Branch
8a88c1c84c
Don’t offer import fix for members of arrays or classes (#35635)
* Write failing test

* Don’t offer import fix for members of arrays or classes
2019-12-13 14:20:54 -08:00
Sheetal Nandi
c3b2aea9f9
Do not write files directly from builder when noEmitOnError is true (#34832)
* Add tests for noEmitOnError

* Do not write files directly from builder when noEmitOnError is true
Fixes #34823

* make linter happy

* Instead of generating output in memory, check errors before doing the emit in case of noEmitOnError
2019-12-12 19:51:18 -08:00
Anders Hejlsberg
71a91763f4
Fix33448 (#35513)
* Filter out discriminants of type 'never'.

* Add tests

* Accept new baselines

* Remove unnecessary '!' assertion
2019-12-12 06:45:46 -08:00
Nathan Shively-Sanders
b98cb0645d
Fix binding of this-assignments w/computed properties (#35639)
Top-level this-assignments do not support computed properties. But the
binder forgets to check for computed properties and tries to bind them
normally. This hits a helpful assert.

This change stop binding this-properties with computed properties at the
top-level.  There's nothing sensible we could do with them; we're unable
to late-bind entries to the global scope or to modules.
2019-12-11 15:55:08 -08:00
Sheetal Nandi
236012e47b
Add watchOptions to tsconfig and allow supplying them on command line as well (#35615)
* Create different watch options in compiler options

* Thread through the new watch options

* Actually use the options passed through for watch strategy

* Support delay on updating child directory watches

* Make watchOptions separate from compilerOptions

* Support passing watch options from command line

* Handle displaying of watchOptions
2019-12-11 13:26:44 -08:00
Sheetal Nandi
4212484ae1
Open bigger set of configured projects when opening composite project for operations that operate over multiple projects like rename (#33287)
* Add isInferredProject, isConfiguredProject and isExternalProject

* Skip refreshing configured project on change of config file if its not loaded

* Open a tree of projects when doing findAllRefs or rename operations

* Fix addToSeen project key

* Refactor combineProjectsOutputWorker

* if the definition is local, no need to load and look in other projects

* Add disableSearchSolution as option to disable looking for solution

* Rename the option to disableSolutionSearching
2019-12-11 12:28:18 -08:00
Andrew Branch
f1f874699c
Improve some completions on generic object literals (#34855)
* Weird fix

* Slightly better I guess

* Update APIs

* Make `hasTypeArguments` do what it says on the tin

* Fix merge mistake
2019-12-11 11:21:28 -08:00
Sheetal Nandi
07364595e4
Handle consistent file name during editor and tsc --watch scenarios (#34622)
* Add isInferredProject, isConfiguredProject and isExternalProject

* Add test for rename on file with case change that fails
Test for #25460

* Dont store fileName on text storage

* Store root file names in the root file map to reflect their name

* Delay open file triggering watches

* Correct the name of source file as we query it (eg. it could be same source file returned in old program with different casing on case insensitive file name)

* More tests

* Refactoring

* Cache bind And check diagnostics and always get program diagnostics from the program

* Another test

* Try to report conflicting file error on file instead of global diagnostics

* Create better tests for module resolution diagnostics check

* Fix lint errors
2019-12-10 18:25:10 -08:00
Toxyxer
f8cacf97e1 Issue/34870 (#35586)
* Add new error message when missing brace

* Add test for missing close brace

* Update other tests which were affected
2019-12-09 16:31:23 -08:00
Wesley Wigham
a78342a160
Move most harness globals into namespaces (#35530)
* Move most harness globals into namespaces

* Remove forward declaration from `createMapShim` and move all `Map` declarations into one file

* A small pile of more changes to get the harness transforming
2019-12-06 15:20:49 -08:00
Wesley Wigham
27616dd523
Move codefix types into services/types.ts (#35506)
* Move codefix types into services/types.ts

* Also split apart refactorProvider

* Move all meanings of DocumentHighlights into one file

* Use setter for object allocator

* Remove unneeded namespace reference

* Remove some shorthand references to nonlocal namespace variables

* Convert WatchType string enum to a structure that can be merged across modules

* Rename harness to harnessIO

* Move accidental globals into namespace

* Remove unused globals

* Suppress lints - these qualifiers are needed for the migration to go smoothly

* Hide global declaration
2019-12-05 10:51:31 -08:00
Anders Hejlsberg
09271f107d
Make no inferences from binding patterns with no defaults (#35454)
* Use nonInferrableAnyType in types inferred from binding patterns

* Add regression tests

* Accept new baselines
2019-12-05 07:09:45 -08:00
Nathan Shively-Sanders
a816162923
Remove unneeded Array and Promise JS rewrites (#35482)
Type-argument defaulting is handled elsewhere in the compiler.
This is a small drive-by improvement, so I didn't change the handling of
'array' or 'promise'; they still manually create `any[]` and
`Promise<any>`, respectively.
2019-12-04 09:06:42 -08:00
Wesley Wigham
7bfffa745f
Remove redundant checker functions and use patterns more friendly to modules (#35399)
* Remove redundant checker functions, use patterns more friendly to modules

* Also use a helper for localizedDiagnosticMessages

* Move types into same file as consts

* Accept slightly changed api baseline

* Whitespace!
2019-12-02 13:44:25 -08:00
Wesley Wigham
85ec9bf175
Remove duplicate definition of Push (#35397)
It's also defined in `corePublic.ts` - there's no errors because they're (almost) identical and merge (creating a redundant overload for `push`). Ironically, while this definition was internal, the other is public (and more complete).
2019-12-02 11:47:42 -08:00
Andrew Branch
97aba45d6f
Emit unused identifier suggestion diagnostics in declaration files and ambient nodes (#35119) 2019-12-02 09:52:40 -08:00
Eli Barzilay
d6740cf410 Fix getTypeFromJSDocValueReference
When using `{import('./b').FOO}` which is defined as a string literal,
`valueType` doesn't have a `symbol`.  Leave it for the fallback value
for now.

This was exposed in 8223c0752.

Fixes #34869.
2019-11-27 17:53:11 -06:00
Sheetal Nandi
d02531f650
Fix compileOnSaveEmit when using source of project reference redirect with --out (#35335)
* Fix compileOnSaveEmit when using source of project reference redirect with --out
Fixes #35226

* Fix typo
2019-11-27 13:47:19 -08:00
Wesley Wigham
c447ebc59c
Refactor: No more than 1 namespace declaration per file (#35373)
* Refactor: No more than 1 namespace declaration per file

* Simplify refs where possible
2019-11-27 13:44:31 -08:00
Anders Hejlsberg
1320c36165
Fix control flow analysis for break/continue with label (#35377)
* Use existing 'continue' target labels for labeled statements

* Use linked list for active labels

* Add regression test

* Accept new baselines
2019-11-27 12:28:06 -08:00
Anders Hejlsberg
ea4e6b31ba
Improve control flow type caching (#35332)
* Cache getTypeOfExpression results when CFA was invoked

* Add tests

* Accept new baselines
2019-11-25 15:10:09 -08:00
Anders Hejlsberg
0c2c58c42f
Create returnOnlySignature only when inferences will possibly be made (#35173)
* Create returnOnlySignature only when inferences will possibly be made

* Add regression test

* Accept new baselines
2019-11-25 15:05:53 -08:00
Alexander T
0c17476d09 assign error to method definition node if a return type is empty (#35309) 2019-11-24 20:18:04 -08:00
Wesley Wigham
b9689228b5
When calculating spreads, merge empty object into nonempty object to … (#34853)
* When calculating spreads, merge empty object into nonempty object to produce partial object to reduce complexity

* Actually accept remainder of baselines

* Limit simplification to single prop or partial types
2019-11-22 17:19:17 -08:00
Anders Hejlsberg
58a05f3e87
Normalize type references before relating them (#35266)
* Normalize type references before relating them in isRelatedTo

* Add comments

* Accept new baselines

* Add regression tests

* Accept new baselines

* Use aliases when available in error reporting

* Accept new baselines
2019-11-22 15:40:18 -08:00
Nathan Shively-Sanders
369900bb07
Emit defineProperty calls before param prop assignments (#34987)
* Emit defineProperty calls before param prop assignments

Note that I restricted this to --useDefineForClassFields is true.
Nothing changes when it's off. I think this is the correct fix for a
patch release.

However, in principal there's nothing wrong with moving parameter
property initialisation after property declaration initialisation. It
would be Extremely Bad and Wrong to rely on this working:

```ts
class C {
  p = this.q // what is q?
  constructor(public q: number) { }
}
```

But today it does, and probably somebody relies on it without knowing.

* Put parameter property initialiser into defineProperty's value

* Combine ES5/ESNext into one test
2019-11-22 15:37:24 -08:00
Nathan Shively-Sanders
2075f74fef useDefineForClassFields skips emit of ambient properties (#35058)
* useDefineForClassFields skips emit of ambient properties

Previously:

```ts
class C {
  declare p
}
```

would incorrectly emit

```js
class C {
    constructor() {
        Object.defineProperty(this, "p", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: void 0
        });
    }
}
```

when useDefineForClassFields was turned on (for targets <ESNext).

* Fix bug for ESNext as well

This moves the check earlier in the pipeline.

* update baselines
2019-11-22 14:52:29 -08:00
Daniel Rosenwasser
3da85df511
Clean up error messages for using TypeScript syntax in JavaScr… (#35254)
* Fix up quotation marks in error messages in JavaScript files.

* Accepted baselines.

* Typescript -> TypeScript

* Accepted baselines.

* Migrate syntactic diagnostics tests to baselining tests.

* Accepted baselines.

* Update diagnosticMessages.json

* Removed markers.

* Add ability to baseline both semantic and syntactic diagnostics.

* Fix up broken diagnostics when using a server LS.

* Accepted baselines.

* Lints.

* Fake up sourcefile objects in the tsserver session client instead.

* Fewer allocations.
2019-11-22 14:51:22 -08:00
Wesley Wigham
3e329469c1
Actually use the moer complete update function in visitEachChild (#35301) 2019-11-22 14:36:22 -08:00
Eli Barzilay
f017fa04c4 Scan types of yield expressions in classes too
Also, drop the other cases where they were ignored, since they're
forbidden in enums, and the others are fine wrt the comment that was
there.

Fixes #34892
2019-11-22 08:51:00 -05:00
Eli Barzilay
20b246c83a Fix getIntrinsicAttributesTypeFromJsxOpeningLikeElement
Use `getIndexTypeOfType`+`getDeclaredTypeOfSymbol` instead of `getIndexInfoOfSymbol`.

Fixes #34730.
2019-11-22 08:43:24 -05:00
Wesley Wigham
663a42be94
Allow references to globalThis to be made in declaration emit (#35279) 2019-11-21 15:21:35 -08:00
Wesley Wigham
cfa367d7f9
Have definite assignment assertions on property signatures mark them as typescript (#35270) 2019-11-21 13:13:46 -08:00
Anders Hejlsberg
94d4023043
Add inference priority level for conditional types in contravariant positions (#35199)
* Add inference priority level for conditional types in contravariant positions

* Accept new API baselines

* Add regression tests

* Accept new baselines
2019-11-21 13:05:44 -08:00
Wesley Wigham
614a07c7d5
Fix printing and emit for definite assignment assertions (#35095)
* Fix printing and emit for definite assignment assertions

* Make factories that handle definite assertions internal
2019-11-21 11:20:57 -08:00
Wesley Wigham
a6d44aa52e
Map stale empty object type in union into fresh empty object type after spread is complete (#34839)
* Map stale empty object type in union into fresh empty object type after spread is complete

* Accept minor baseline diff
2019-11-21 10:57:55 -08:00
Sheetal Nandi
0e736a7438
Fix the usage of pattern matching in module resolution for check of hasZeroOrOneAsteriskCharacter (#35209)
* Fix the usage of pattern matching for check of hasZeroOrOneAsteriskCharacter
Fixes #35171

* Fix error message
2019-11-20 10:55:40 -08:00
Kārlis Gaņģis
17f5469a2c Fix crash with Object.defineProperty for imported alias (--allowJs) (#35198)
Fixes #35196
2019-11-20 10:50:47 -08:00
Daniel Rosenwasser
b50b9e0fd2
Fix check for get/set recommendation (#34885)
* Added more tests.

* Accepted baselines.

* Work better with any parameter type.

* Accepted baselines.

* Use the actual indexed expression.

* Add tests that exhibit bad stringification.

* Accepted baselines.

* Short-circuit stringification on 'undefined'.

* Accepted baselines.

* Remove space.

* Accepted baselines.
2019-11-19 13:00:24 -08:00
Klaus Meinhardt
fce728e07f fix emit for delete on optional chain (#35090)
* fix emit for delete on optional chain

* Apply suggestions from code review

Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com>
2019-11-18 16:34:47 -08:00
Anders Hejlsberg
8b83703632
Properly strip readonly from rest argument types (#35169)
* Properly strip readonlyness from rest argument types

* Add tests

* Accept new baselines
2019-11-18 13:11:36 -08:00
Anders Hejlsberg
196c0aa078
Fix excess property checking for unions with index signatures (#34927)
* Fix excess property checking for union targets with index signatures

* Accept new baselines

* Remove unused code

* Add tests

* Accept new baselines
2019-11-15 10:59:58 -08:00
Jack Williams
3bcea0dbba Fix #35060 (#35065)
* Fix 35060

* Refactor and check ro-array to tuple case

* Lint
2019-11-15 10:13:10 -08:00
Klaus Meinhardt
5321dcb09f disallow 'await' and 'yield' in property and enum member initializer (#34892)
* disallow 'await' and 'yield' in property and enum member initializer

* accept baseline changes

* Add a test for #34887

Ensures that this fixes #34887
2019-11-14 17:44:48 -08:00
Klaus Meinhardt
8f40ac06cc optimize transform of optional chaining and nullish coalescing (#34951)
* optimize transform of optional chaining and nullish coalescing

* remove unnecessary condition

* typo

* fix lint

* prevent capturing of super

* swap branches again

* accept new baselines

* avoid temporary objects
2019-11-14 17:34:13 -08:00
Orta
ef0cca7d12
Adds 'did you mean' to the CLI args parser (#35063)
* Adds did you mean to the CLI args parser

* Adds test coverage for the did you mean on CLI args

* Adds did you mean to convertOptionsFromJson

* Ensure tsconfig compiler flags also get 'did you mean?'
2019-11-13 20:16:48 -05:00
Anders Hejlsberg
38db7ae59e
Properly analyze switch statement bypass control flow (#35087)
* Properly analyze switch statement bypass control flow

* Add regression test

* Accept new baselines
2019-11-13 09:22:18 -08:00
Wesley Wigham
aa39080ac7
Do not allow freshness to move errors out of the current file, ensure json documents are deeply unfreshened and fully widened (#35048) 2019-11-12 13:30:27 -08:00
Nathan Shively-Sanders
f3344767dd
Fix import type resolution in jsdoc, mark 2 (#35057)
Fake alias resolution only applies when the import type is followed by a
qualified name. Otherwise the alias is sufficiently resolved already.
2019-11-12 12:44:30 -08:00
Klaus Meinhardt
94f85901d7 strip QuestionToken from MethodDeclaration and PropertyDeclaration emit (#34954)
* strip QuestionToken from MethodDeclartion emit

Fixes: #34953

* test property emit
2019-11-12 10:30:46 -08:00
Anders Hejlsberg
3a5230ab3d
Defer switch exhaustiveness checks (#35000)
* Defer switch exhaustiveness checks until they're actually needed

* Add regression test

* Accept new baselines
2019-11-09 07:52:39 -08:00
Andrew Branch
53d2b7ed60
Don’t assume importing some JSON means you want everything imported with .js extensions (#34961) 2019-11-07 14:55:54 -08:00
Andrew Branch
4cbace7110
Add "auto" to importModuleSpecifierPreference (#34981)
* Add "auto" to importModuleSpecifierPreference

* Update APIs
2019-11-07 14:55:13 -08:00
Anders Hejlsberg
1c42c1aaa8
Fix control flow analysis in try-catch-finally (#34880)
* Revise creation of control flow graph for try-catch-finally statements

* Add tests

* Accept new baselines
2019-11-05 12:06:25 -08:00
Anders Hejlsberg
95be956320
Fix switch statement exhaustiveness checking (#34840)
* Don't optimize away CFA nodes representing missing default clauses

* Add regression test

* Accept new baselines
2019-11-05 12:05:41 -08:00
Anders Hejlsberg
966d9864d0
Properly instantiate object types created from rest parameters (#34826)
* Anonymous types of rest variable declarations need instantiation

* Add regression test

* Accept new baselines

* Accept new API baselines
2019-11-05 12:04:45 -08:00
Alexander T
56cad36678 (34894): Wrong information in error message for overridden acc… (#34901) 2019-11-05 00:07:03 -05:00
Ozair Patel
be960fa356 Add related diagnostic to "used before defined" if type is a function that returns a union with undefined (#33171)
* Add "use before defined" diagnostic

* Make "use before defined" diagnostic as related information to TS2454

* Add baseline tests for "use before defined"

* Add test for type alias union with undefined for "use before defined" diagnostic

* Update baselines
2019-11-04 17:53:31 -05:00
Luka Hartwig
9a3ec5f229 Improve error message when compiling a .js file (#34861)
* Improve error message when compiling a .js file

* Add dedicated error message for .json and .js files

* Update missing baseline tests

* Remove error hint for .json files
2019-11-04 14:59:06 -05:00
Ron Buckton
ba5e86f140
Propagate 'undefined' instead of the optional type marker at an optional chain boundary (#34588)
* Propagate 'undefined' instead of the optional type marker at an optional chain boundary

* Update src/compiler/types.ts

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2019-11-01 11:36:22 -07:00
Anders Hejlsberg
9ff378aab3
Exclude types originating in literals from recursion depth limiter check (#34742)
* Exclude types originating in literals from recursion depth limiter check

* Add tests

* Accept new baselines

* Remove superfluous test
2019-10-31 06:14:43 -07:00
Wesley Wigham
7b02c635b6
Report generic rest parameters as unreliable variance positions (#33020)
* Report generic rest parameters as unreliable variance positions

* Add example from discussion on #30301
2019-10-30 13:54:39 -07:00
Wesley Wigham
5e0fbc677a
Add circularity checking during deferred type argument creation (#34791) 2019-10-30 13:36:43 -07:00
Wesley Wigham
8b7664ae15
Generate more correct property name nodes in declaration emit (#34741)
* Generate more correct property name nodes in declaration emit

* Silly only-on-CI lint rule T.T
2019-10-30 12:40:59 -07:00
Wesley Wigham
d28672d97f
Fix alias naming and structure bugs in js declarations (#34786)
* Fix alias naming and structure bugs in js declarations

* Add another test case and change condition for ns merge to require signature or export content

* Fix typo in comment
2019-10-30 12:40:06 -07:00
Ron Buckton
87cc8c4af8
Evaluate RHS of binding/assignment pattern first (#34806) 2019-10-29 17:42:30 -07:00
Nathan Shively-Sanders
00dd1f0609
Add isIntersectionConstituent to relation key (#34789)
* Add isIntersectionConstituent to relation key

isIntersectionConstituent controls whether relation checking performs
excess property and common property checks. It is possible to fail a
relation check with excess property checks turned on, cache the result,
and then skip a relation check with excess property checks that would
have succeeded. #33133 provides an example of such a program.

Fixes #33133 the right way, so I reverted the fix at #33213
Fixes #34762 (by reverting #33213)
Fixes #33944 -- I added the test from #34646

* Update comments in test
2019-10-29 15:08:59 -07:00
Nathan Shively-Sanders
7635884224
JSDoc type reference understands require with entity name (#34804)
* resolve require with entity name postfix

For example, `require("x").c`. This is the value equivalent of
`import("x").a.b.c`, but the syntax tree is not as nicely designed for
this purpose.

Fixes #34802

* Add bug number to test

* Add optional chain test
2019-10-29 14:56:33 -07:00
Sheetal Nandi
dbef230eb8
This handles when packages are symbol links in mono repo like scenarios to use source files instead of output d.ts from project reference (#34743)
* Fix incorrect outDir usage instead of out

* Handle symlinks of packages in mono repo like packages
Fixes #34723

* Added clarified comment
2019-10-29 10:49:14 -07:00
Ron Buckton
554bd24734
Fix checker handling for empty type argument lists (#34790) 2019-10-29 08:56:11 -07:00
Martin Probst
ff590b622e Fix a crash when transforming functions in modules. (#34513)
When transforming a module declaration and block, parse tree nodes
contained in the module block have their parent pointers reset due to
`shouldEmitModuleDeclaration` calling into `isInstantiatedModule`, which
needs to set parent pointers to operate.

That causes a crash when later transforming any nodes within the module,
as retrieving their source file in `getSourceFileOfNode` (via
`getOrCreateEmitNode`) fails, due to their new synthesized parent nodes
not being in a source file.

This change avoids the issue by using the parse tree node in `ts.ts` to
decide whether a module declaration should be emitted (i.e. whether the
module contains values).

This means transformers cannot add values to modules that previously did
not contain any.

Fixes #34644.
2019-10-29 08:40:49 -07:00
Nathan Shively-Sanders
080e41dc90
Fix type reference to merged prototype property assignment (#34764)
The constructor function code path in the return type checking of
signatures needs to pass the *merged* symbol of the declaration to
getDeclaredTypeOfClassOrInterface. Other callers of
getDeclaredTypeOfClassOrInterface do this, or used an already-merged
symbol.

Fixes #33993
2019-10-28 10:14:04 -07:00
Eli Barzilay
eb0208c589
make globalThis have an empty declarations (#34561)
Fixes #33860 by making it an error.  This is an improvement, but sounds
like it would be better to make it work later.
2019-10-25 22:49:31 -04:00
Andrew Branch
d8840f8a18
Show all matching enum flags in debug flag formatter (#34689)
* Show all matching enum flags in debug formatter

* Revert "Show all matching enum flags in debug formatter"

This reverts commit 073099722a.

* Same thing but simpler

* Lint
2019-10-25 16:27:24 -07:00
Evan Cahill
88f3593742 Fix error when exporting const enums (#33060) (#34721)
* Allow export declaration to reference const enums

* Update baselines

* Add test to verify reexported const enums are elided
2019-10-25 16:04:44 -07:00
Anders Hejlsberg
c404c08fde
Fix reachability analysis for ?? operator (#34702)
* Exclude ?? operator from true/false literal check in createFlowCondition

* Accept new API baselines

* Add tests

* Accept new baselines

* Address CR feedback

* Accept new API baselines
2019-10-24 15:57:14 -07:00
Martin Probst
a03227d60e Avoid a crash with @typedef in a script file. (#33847)
* Avoid a crash with `@typedef` in a script file.

Scripts (as opposed to modules) do not have a symbol object. If a script
contains a `@typdef` defined on a namespace called `exports`, TypeScript
crashes because it attempts to create an exported symbol on the
(non-existent) symbol of the SourceFile.

This change avoids the crash by explicitly checking if the source file
has a symbol object, i.e. whether it is a module.

* Add usage of exports.SomeName typedef.

* Fix bug at bind site rather than in declare func
2019-10-24 14:04:42 -07:00
Wesley Wigham
7cfa1dfb8a
Fix regression in mixin emit by removing unneeded line of code (#34715)
* Fix regression in mixin emit by removing unneeded line of code

* Double the test, double the fun
2019-10-24 14:02:37 -07:00
Nathan Shively-Sanders
d892fd408f
Fix expando handling in getTypeReferenceType (#34712)
* Fix expando handling in getTypeReferenceType

getExpandoSymbol looks for the initialiser of a symbol when it is an
expando value (IIFEs, function exprs, class exprs and empty object
literals) and returns the symbol.

Previously, however, it returned the symbol of the initialiser without
merging with the declaration symbol itself. This missed, in particular,
the prototype assignment in the following pattern:

```js
var x = function x() {
  this.y = 1
}
x.prototype = {
  z() { }
}

/** @type {x} */
var xx;
xx.z // missed!
```

getJSDocValueReference had weird try-again code that relied on calling
getTypeOfSymbol, which *does* correctly merge the symbols. This PR
re-removes that code and instead makes getExpandoSymbol call
mergeJSSymbols itself.

* Remove extra newline
2019-10-24 13:12:44 -07:00
Nathan Shively-Sanders
969634b97c
Restore delayed merge check to getTypeFromJSDocValueReference (#34706)
* Restore delayed merge check to getTypeFromJSDocValueReference

This is needed when a function merges with a prototype assignment. The
resulting *merged* symbol is a constructor function marked with
SymbolFlags.Class. However, the merge doesn't happen until
getTypeOfFuncClassEnumModule is called, which, in the
getTypeReferenceType code path, doesn't happen until
getTypeFromJSDocValueReference. That means the check for
SymbolFlags.Class is missed.

Previously, getTypeFromJSDocValueReference had a weird check
`symbol !== getTypeOfSymbol(symbol).symbol`, which, if true, ran
getTypeReferenceType again on `getTypeOfSymbol(symbol).symbol`. For
JS "aliases", this had the effect of dereferencing the alias, and for
function-prototype merges, this had the effect of ... just trying again
after the merge had happened.

This is a confusing way to run things. getTypeReferenceType should
instead detect a function-prototype merge, cause it to happen, and
*then* run the rest of its code instead of relying on try-again logic at
the very end. However, for the RC, I want to fix this code by restoring
the old check, with an additional check to make sure that #33106 doesn't
break again:

```ts
const valueType = getTypeOfSymbol(symbol)
symbol !== valueType.symbol && getMergedSymbol(symbol) === valueType.symbol
```

I'll work on the real fix afterwards and put it into 3.8.

* Add bug number
2019-10-24 09:24:58 -07:00
Wesley Wigham
07d3a2ec7e
Do not consider element accesses which are neither statically bindable nor late bound as special assignments (#34679) 2019-10-23 16:01:25 -07:00
Nathan Shively-Sanders
8223c07527
getTypeFromJSDocValueReference: handle import types (#34683)
Previously it only handled types whose declaration was from `require`,
but now it handles types whose reference is an import type as well.
2019-10-23 15:53:38 -07:00
Kārlis Gaņģis
479d30646f Fix crash in assigning function with this ref to alias (#34650) 2019-10-22 14:33:45 -07:00
Nathan Shively-Sanders
1cbbe288ac
Treat any mix of element/prop access as declaration in JS (#34649)
Fixes #34642 but, notably, doesn't actually make the assignment into a
working declaration. It just fixes the crash.
2019-10-22 11:28:28 -07:00
Andrew Casey
8cf13249ea
Merge pull request #34521 from amcasey/LazyDirectoryCreation
Stop pre-emptively creating directories
2019-10-21 17:41:54 -07:00
Andrew Casey
af2f46e899 Use longer lambda parameter names 2019-10-21 16:22:10 -07:00
Daniel Rosenwasser
1b0fca5df5 Update version to 3.8. 2019-10-21 14:51:21 -07:00