Commit graph

3853 commits

Author SHA1 Message Date
Alexander T 57f161eaa8 feat(38225): change diagnostic message for remove braces from arrow function body 2020-04-28 10:44:36 +03:00
Alexander T 31b81bafe7
fix(38138): show suggestions for identifier in class property initializer (#38157) 2020-04-24 13:50:34 -07:00
Andrew Branch ce95d9ca6b
Fix values and types merging in JS module exports (#37896)
* Fix values and types merging in JS module exports

* Fix everything

* Share `setValueDeclaration` between binder (local merge) and checker (cross-file merge)

* Revert accidental changes to baselines

* Update baseline from master merge
2020-04-24 13:49:48 -07:00
Andrew Branch 9569e8aaa4
Fix newline issues when adding multiple imports (#38119)
* Add new import declarations in a single TextChanges call

* Refactor
2020-04-23 11:59:38 -07:00
Josh Goldberg ef83109dbf
Prefer a likely literal over anonymous type in --noImplicitAny codefixes (#36015)
* Prefer a likely literal over anonymous type in --noImplicitAny codefixes

Before trying to make an anonymous type for a type's usage, we'll first check if there is exactly one builtin primitive the usage is assignable to, and use it if so. Right now that's only `number` and `string` because `boolean` has no distinguishable members.

A couple of implementation details:
* `tryInsertTypeAnnotation` needed to know to insert a type _after_ a node's `exclamationToken` if it exists
* This code area was written before `??` 😉

* Used unknown/any instead of void when applicable

* Fix little whitespace change in tests/cases/fourslash/codeFixInferFromUsagePropertyAccessJS.ts

* Undid some now-unnecessary unknown additions

* Took advice on restricting void to just call expressions
2020-04-22 11:28:11 -07:00
Alexander T d2016912b5
fix(37825): exclude private fields from completions in subclasses (#37906) 2020-04-22 12:07:36 -04:00
Alexander T 92a63741a2
fix(38080): add outlining spans for TypeLiteral (#38089) 2020-04-22 11:51:36 -04:00
Andrew Branch 7d4fc73331
Fix preserveNewlines printer option when a list child has the same start or end as its parent (#37846)
* Fix preserveNewlines printer option when a list child has the same start or end as its parent

* Fix leading line separator calculation and JSX bug
2020-04-21 15:34:30 -07:00
Alexander T 1e48057b9e
fix(15398): skip adding line breaks when replacing JS checks directives (#38086) 2020-04-21 11:02:56 -07:00
Alexander T 52d32e5597 Add outlining spans for object destructuring elements 2020-04-21 12:57:52 +03:00
Andrew Branch 547fd12c2f
Fix doc comment template on assignment expressions (#38032) 2020-04-20 11:15:12 -07:00
sergeir82 b346f5764e
prefix-unused-parameter-with-_ codefix now works in jsdoc @param (#36152)
* Fix prepending unused TypeScript variables with underscore doesn't rename JSDoc @param.
Fix test for quick fix "Prefix all unused declarations with '_' where possible".
Fixes #33021.

* Replace FindAllReferences.Core.eachSymbolReferenceInFile function call to more ligher call of getJSDocParameterTags when searching for a parameter in jsdoc.

* Remove redundant constant declaration.

* Add test for prefix single unused parameter in jsdoc.
2020-04-17 13:18:05 -07:00
Alexander T a16c44180a
fix(37940): add space after parameter decorator (#37959) 2020-04-15 11:42:29 -07:00
Joe Previte 583e70b3d1
fix(refactor): keep comments after refactor (#35937)
* add two tests: Refactor: Remove braces from arrow function

* refactor: simplify test and add another test

* fix: copyTrailingAsLeadingComments in addOrRemoveBracesToArrowFunction

* test: add additional test

* fix: clean up changes

* fix: add check for newEdit

* fix: add function for semi colon modifier

* feat: grab all comments during refactor

* refactor: update addOrRemoveBraces logic

* fix: remove duplicate function call

* Update src/services/refactors/addOrRemoveBracesToArrowFunction.ts

* remove blank line

remove blank line

Co-authored-by: Jesse Trinity <42591254+jessetrinity@users.noreply.github.com>
2020-04-15 11:06:04 -07:00
Alexander T a8e1ad4e62
fix(37781): import missing argument types for a new method (#37857) 2020-04-13 10:23:12 -07:00
Alexander T aa6be6ee6f
fix(37364): show completions for string literal index on mapped type (#37367) 2020-04-10 12:36:26 -04:00
Neonit d6af9b7cbc Fix indentation preservation in JSDoc (#37717)
This fixes two bugs in the parseJSDocCommentWorker().

1. The initial indent was calculated wrongly. It was set to the
   difference between the index of the last newline or beginning of file
   and the current start marker (position of /**). By calculating it
   this way, the newline character itself is counted as indentation
   character as well. The initial indent is used as margin for the
   whole comment. The margin contains the amount of characters to skip
   before the actual content or payload of a comment line. The algorithm
   does not skip non-whitespace characters at the beginning of the
   content, but it would strip away one whitespace character for
   indented content (which does matter, if there is e.g. a Markdown
   code block with indentation in the comment).

2. When reducing initial whitespace sequences of comment lines by the
   remaining margin the algorithm cut off one character too much. This
   might have been introduced to fix 1. It had a similar effect as 1.
2020-04-10 17:46:08 +02:00
Nathan Shively-Sanders 3030cd8eff refactoring done except for deduping 2020-04-09 16:43:31 -07:00
Nathan Shively-Sanders e287c8321a Codefix invokes generate get-set accessor refactor
1. Add add-all test
2. Add codefix that delegates to get-set accessor refactor.

Needs massive amounts of cleanup and deduplication.
2020-04-09 15:06:45 -07:00
Nathan Shively-Sanders 71b7695113 add fourslash tests for codefix 2020-04-09 11:24:54 -07:00
Andrew Branch 57f9076612
Remove extraneous string escape from convert to template string refactor (#37743)
* Add failing test

* Remove extraneous string escape

* Revert unnecessary change
2020-04-09 09:40:28 -07:00
Alexander T e897eb1b2a
fix(37817): omit comments in name accessor (#37822) 2020-04-07 16:59:54 -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
Zixiang Li 54b0e4acc5
Fix goto implementation does not suggest all subtypes (#33652) 2020-04-02 09:57:48 -07:00
Andrew Branch 3810c2fe6b
Fix rename for type symbols imported as a different name (#37745)
* Add failing test

* Fix getMeaningFromLocation for imports

* Only the name of an ImportEqualsDeclaration counts

* Commit baseline
2020-04-02 09:06:19 -07:00
Alexander T 72a0411776
fix(37431): allow only one space between async keyword and method name (#37504) 2020-04-02 11:30:05 -04: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
Wenlu Wang 5596ed80d7
Add replacement span for string literal (#37490)
* Add replacement span for string literal

* fix change requests

* fix lint

* Avoid flag

* Fix baseline

* ADd misising baseline
2020-04-01 17:58:16 -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
Jesse Trinity ef377d5a66
Don't delete comments when deleting unused declarations (#37467)
* don't delete comment on variable declaration

* add more declaration kinds

* don't copy comment in convertes6 class

* don't copy comments in convertToES6Class

* add tests

* use isAnyImportSyntax

* handle mixed comment types

* update tests
2020-03-31 10:18:06 -07:00
Andrew Branch 0f3a9d4d4b
Support completions for local named exports (#37606)
* Support completions for local named exports

* Add JSDoc

* Use sort text instead of filtering

* Revert new CompletionKind

* Return valid completions even when export declaration is in an invalid place
2020-03-27 10:47:02 -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
Andrew Branch a04225dbec
Don’t suppress completions after yield (#37609) 2020-03-25 15:27:47 -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
Andrew Branch 292d01880f
Add code fix for importsNotUsedAsValues error (#37468) 2020-03-19 13:13:15 -08: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
Alexander T 0aa2e2783c
feat(37409): add fix all quick fix to fixInvalidJsxCharacters (#37436) 2020-03-18 09:54:17 -07:00
Alexander T c8e43d878f
fix(37194): fix crash on go to the definition in variable assignment (#37253) 2020-03-17 16:16:28 -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
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
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
Jesse Trinity 4c160683c3
Add trimTrailingWhitespace Editor Option (#36905)
* add trim trailing whitespace option

* set default trimTrailingWhiteSpace to true

* add fourslash tests

* accept new baselines

* only preserce whitespace when setting is explicitly false

* format whitespace
2020-03-13 13:42:49 -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
Andrew Branch db44231e38
Add outlining spans for case clauses (#37374)
* Add outlining spans for case clauses

* Update old test

* Update other test

* Update yet another of the same test
2020-03-13 10:52:27 -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
Joey Watts 31963d54b8
Add implementation for fixExpectedComma (#33879)
Signed-off-by: Andrew Deniszczyc <adeniszczyc@bloomberg.net>

Cleanup of implementation

Move check node container check

Add test cases for fixExpectedCommaError

Renaming and add test case

Co-authored-by: Andrew Deniszczyc <adeniszczyc@bloomberg.net>
2020-03-12 14:55:02 -07:00
David 4406717f13
add config to insert space for empty braces (#35427) 2020-03-12 16:35:35 -04:00
Alexander T 8d63a7a842
fix(28163): change outdated options (#37268) 2020-03-07 10:23:07 -08:00
Jonathan Share c0c5760d15
Fixes duplicated comment when executing code fix to add missing enum member (#28163)
Resolves issue #28031 by overriding default value of
`useNonAdjustedStartPosition` option to replaceNode. Test case included
that confirms intended behaviour.
2020-03-06 16:53:37 -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
Alexander T 176241cca9
fix(36238): allow aliases in spelling suggestions (#37168) 2020-03-03 10:58:29 -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
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
Ryan Cavanaugh f4e371c731
Harden findAllReferences.ts against symbol.declarations = undefined cases (#37088)
Fixes #37086
2020-02-27 14:55:49 -08: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
Ryan Cavanaugh 35aea8bbfa
Remove crashing diagnostic code that wasn't helping us (#36913) 2020-02-27 12:45:28 -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
Orta 8a797cad2b
Adds floating block comments to the outlining spans response (#36880)
* Adds floating block comments to the outlining spans response

* Only use one route for grabbing outline nodes, which now includes special casing the EOF token
2020-02-25 17:09:16 -05: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
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
Alexander T c8147cb601
fix(33377): use quoteStyle option for string literals completions (#36720) 2020-02-20 08:45:07 -08:00
Alexander T bab0c99584
fix(29565): Add missing super() quickFix errors for constructo… (#36601) 2020-02-18 13:00:31 -08:00
Alexander T bc12123115
fix(29908): Declare static method/property quickfix can add st… (#36854) 2020-02-18 11:27:35 -08:00
Alexander T c59fcae117
fix(30003): formatter deletes comments after trailing comma (#36674) 2020-02-14 14:57:18 -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
Andrew Branch 950b36192a
Fix renaming an ExportSpecifier name when propertyName is present (#36790)
* Fix renaming exportSpecifier name when propertyName is present

* Add baseline test for name without propertyName too
2020-02-13 16:55:52 -08:00
Daniel Rosenwasser 210090b483
No template refactor on plain strings (#36785)
* Add/convert to failing tests.

* Stop offering to convert single string literals to template expressions.

* Ensure we're actually testing for single quotes.
2020-02-13 12:22:53 -08:00
Alexander T e435054b3b
fix(36416): empty import path causes server crash (#36751) 2020-02-12 14:26:51 -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
Andrew Branch ad8c209fc2
Use type-only imports in auto-imports when it would be an error not to, and use auto-imports in “implement interface” fix (#36615)
* Refactor fix-all-missing-imports to be reusable by other codefixes

* Migrate infer-from-usage to use ImportAdder

* Add infer from usage test importing more than one thing in a single fix

* Migrate implement interface / abstract members fixes to use ImportAdder

* Update old tests

* Use type-only imports when it would be an error not to

* Add another test

* Rename stuff
2020-02-10 17:13:35 -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
Nathan Shively-Sanders 2cc585668d
Support property declarations in jsdoc template generation (#36658)
* Support property declarations in jsdoc template generation

* fix lint and add test
2020-02-06 14:38:21 -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
Alexander T 1c42fd4bdf
fix(33600): disallow convertFunctionToEs6Class Quick Fix for IIFE (#36580) 2020-02-03 16:52:08 -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
Ron Buckton 8db1d7bc6d
Do not adjust location for import/export keywords with more than one possible binding (#36560) 2020-01-31 14:58:30 -08:00
Ron Buckton 9a357c19f3
Fix wrong script info used to resolve line/offset for call hierarchy items (#36559) 2020-01-31 14:41:25 -08:00
Ron Buckton 01af3aa483
Support 'find references' on most declaration-related keywords (#36490)
* Allow 'find references' to work on most declaration keywords

* Add support for rename

* Add more keywords, move logic out of checker and into services

* Add additional type and expression keywords
2020-01-31 11:53:57 -08:00
Eli Barzilay ad8feb5f90 Filter out private fields in string literal property completions.
Also some minor simplifications.

Fixes 36082.
2020-01-30 22:42:32 -05:00
Hye Sung Jung 8ed129771f
fix spelling errors (#36523)
* fix spelling errors

* remove changes in lib/*
2020-01-30 13:39:54 -08:00
Alexander T bfff11530f
fix(35069): insert blank line after last new import (#36531) 2020-01-30 11:20:09 -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
Alexander T 9fd0202e9f
fix(36481): allow renaming private fields (#36499) 2020-01-29 09:21:19 -08:00
Sheetal Nandi 869a8211fc
Make javascript require goto def similar to ts import equals (#36487)
Fixes #34996
2020-01-28 16:23:56 -08:00
Ben Lichtman e87b2e3506
Merge pull request #36063 from uniqueiniquity/addWeakCompletionProperty
Add completion property to identify completions from unchecked files
2020-01-28 13:53:47 -08:00
Alexander T 2cc7a5d6bf fix(33362): 'extract to function' for variable that is assigne… (#36455) 2020-01-28 12:10:12 -08:00
Andrew Branch cf33f7bff6
Don’t use 'import =' for auto-import when esModuleInterop is on unless it’s already been done (#36475)
* Revisit esModuleInterop import kind priority yet again

* Test was wholly redundant

* Check for precedent is simpler now
2020-01-28 11:05:04 -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
Orta 3ece65a94c
When looking at outlines for try functions, allow for not finding a child to provide a span when requesting outlines (#36389) 2020-01-27 15:59:49 -05: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
Alexander T c239626f23 fix(36140): handle quotesPreference option in interface implementation (#36398) 2020-01-27 12:25:31 -08:00
Alexander T 30545006df fix(36068): Incorrect quick fix for undeclared private field i… (#36373) 2020-01-24 18:28:42 -08:00
Sheetal Nandi 29895e8906
Handle header comments better by comparing its end line with first node line (#36413)
Fixes #31508
2020-01-24 11:20:41 -08:00
Andrii Dieiev 420b478c65 Add prefix/suffix only to binding element name (#33538) 2020-01-24 10:46:41 -08:00
Nathan Shively-Sanders ef5573b266
Add as completions (#36359) 2020-01-23 08:29:06 -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
Nathan Shively-Sanders c8e2f58ec5
Completions for asserts and declare (#36355)
* Add completions for `asserts`

* Add declare assertions.
2020-01-22 10:43:33 -08:00
Orta 5e59eece34
Adds support for showing default exports in the navtree (#35477)
* Adds support for showing default exports in the navtree - Fixes #34601

* Handle the feedback in #35477

* Navigation items using default export or export = will get noted if they are a const vs function
2020-01-22 08:13:04 -05: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
Alexander T afa11d3c7a fix(34621): show suggestions in class property initializer (#35999) 2020-01-17 14:27:12 -08:00
Alexander T 94e8db7e07 fix(35043): TS Server: references does not mark isDefinition o… (#36051) 2020-01-17 14:26:36 -08:00
Alexander T ce4c4b6183 fix(36023): fix crash in document highlight service (#36233) 2020-01-17 14:24:46 -08:00
Sheon Han 96e8fbc657 Fix for issue #32528: Prevent meta property from appearing twice (#35844)
* fix meta property from appearing twice

* handle case where ImportMeta has props defined

* rename file

* use exclude instead of exact

* undo comment

* this file should have no change

* change file name back

* add more test cases

* remove comment and text validation

* fix formatting
2020-01-17 13:56:50 -08:00
Andrew Branch 797c5362a2
Codefix: Don’t return a fixId if there’s definitely nothing else that can be fixed (#35765)
* Start fixing fixId

* Fix tests

* Add comment

* Fix unit tests, remove fixAllDescription when unavailable

* Add codeFixAllAvailable to fourslash harness
2020-01-16 10:07:37 -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
Andrew Branch 81a942e7b9
Fix completions triggered on existing private identifier property access (#36191) 2020-01-15 13:13:11 -08:00
Jean Pierre 79dcd3dba1 Correctly resolve tags for function overloads (#30253)
* Correctly resolve tags for function overloads. Fixes #30181

* Better fix for #30181. Added more unit tests

* Fix commentsOverloads tests

* Fallback to first signature when doc and tags are empty
2020-01-10 08:54:26 -08:00
Nathan Shively-Sanders 66b5c47854
Fix crash in codefixes re: braces of class body (#36087)
* Fix crash in codefixes re: braces of class body

Previously, the code that finds braces of a class body assumed they were
always there. This is not always the case, so this code checks for
that.

* fix semicolon lint
2020-01-09 08:46:00 -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
Ben Lichtman 509d243ea5 Add test 2020-01-07 13:07:52 -08:00
Alexander T 8ed92dcecd fix(31909): show suggestions for second type argument of generic (#36024) 2020-01-07 11:03:22 +00: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
Alexander T 4585f448a9 fix(35179): formatter incorrectly remove spaces (#35979) 2020-01-03 10:09:56 -08: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 ad0f0064ce Remove refactoring from template expression to string concatenation. 2020-01-02 16:12:44 -08:00
Titian Cernicova-Dragomir 82b0547281 Fixed outlining spans for chained method calls. (#35860) 2020-01-02 15:44:22 -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
Alexander T a39a675696 fix(35474): formatter incorrectly adds space after increment (#35550) 2019-12-23 12:27:54 -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
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
Daniel Rosenwasser 35a3a5fbaf Merge remote-tracking branch 'origin' into convert-to-template 2019-12-20 16:46:37 -08:00
Andrew Branch d96be353cb
Fix JSDoc param type completions when name hasn’t been written yet (#35787) 2019-12-20 15:23:53 -06:00
Andrew Branch 1fd5bd2b4e
Filter out self-fulfilling completions (#35709) 2019-12-19 16:05:23 -06:00
Andrew Branch aef2e0a238
Fix implement interface codefix for synthetic member symbols (#35718) 2019-12-18 07:20:01 -08:00
Andrew Branch c73af610fe
Add ignoreInterpolations util to fourslash for fuzzy diagnostic matching (#35652)
* Add ignoreInterpolations util to fourslash for fuzzy diagnostic matching

* Simplify

* It’s not Swift

* Fix regexp

* Remove unnecessary type assertion
2019-12-16 17:21:21 -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 1fd1b429f0
Handles different references and renames involved with import export and import type node (#34813)
* Test

* Handle import type node when handling the namespace import and reexport
Fixes #33017

* Handle qualifier of the importTypeNode

* Handle export specifier

* Fix rename prefix when search for rename starts at qualifier in import type ndoe

* Fix rename of qualifier with importType node when invoked without provideSuffixAndPrefix option
2019-12-11 15:11:27 -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
Andrew Branch 64a886700f
Fix spelling codefix for optional chain property access (#35583) 2019-12-09 11:31:47 -08:00
Andrew Branch f050750cc6
Don’t auto-import undefined (#35504) 2019-12-05 14:47:51 -08:00
Andrew Branch b39b4e05be
Use namespace import for esnext when esModuleInterop is off (#35475) 2019-12-04 12:07:25 -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 d6bd3ac552 Don't filter away private completions if in the same context
Fixes #34405, which was introduced in PR #16953.
2019-11-27 17:41:58 -06: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
Eli Barzilay 77ec756960 Make getSourceFileToImportFromResolved prefer files in program.getSourceFiles()
Fixes #30550
2019-11-20 18:00:10 -05:00
Andrew Branch 571ca60b08
Add preceding semicolon on await insertion when parentheses are included (#34627)
* Add preceding semicolon on await insertion when parentheses are included

* Just start with precedingToken

* Fix semicolon formatter regression

* Delete test with debatable expected behavior

* Lint after control flow changes
2019-11-19 13:11:42 -08:00
Orta af0d5d33b6
Improve positioning of the implement interface codefix (#34928) 2019-11-19 12:13:50 -05: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
Andrew Branch f2146a627c
Fix isInJsxText after JSXOpeningElement with type arguments (#34958)
* Fix `isInJsxText` after JSXOpeningElement with type arguments

* Do the same thing a different way
2019-11-06 15:02:45 -08:00
Sheetal Nandi 47ec514cf4
Use empty object for invalid package json contents instead of undefined (#34906)
* Use empty object for invalid package json contents instead of undefined
Fixes #34726

* Behave as if package json doesnt exist in case of invalid json in package json
2019-11-04 14:31:45 -08:00
Wenlu Wang 234680851b add template literal spans (#34699) 2019-10-30 23:54:00 -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
Sheetal Nandi cbbbcfa4c5
Fix incorrectly looking for position in call/new expression arguments when looking for indentation of type arguments (#34779)
* Fix incorrectly looking for position in call/new expression arguments when looking for indentation of type arguments
Fixes #32487

* Update src/services/formatting/smartIndenter.ts

Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2019-10-28 14:02:09 -07:00
Andrew Branch 634e0ad52b
Fix extract type on JS function params (#34745) 2019-10-28 10:30:59 -07:00
Andrew Casey 590fd3f2a2 Don't assume that all symbols have declarations
...in Find All References.  For example, global `this` doesn't in
modules.

Part of #34404
2019-10-22 15:00:30 -07:00
Andrew Casey 159b6262ea
Merge pull request #34631 from amcasey/ComputedPropName
Handle undefined from getPropertyNameForPropertyNameNode
2019-10-22 10:17:05 -07:00
Andrew Casey 7862e58354 Handle undefined from getPropertyNameForPropertyNameNode
...which can be returned when the property name is computed.

Part of #34404
2019-10-21 17:41:06 -07:00
Daniel Rosenwasser b845800bdf
Add option to configure automatic optional chain completions (#34552)
Add option to configure automatic optional chain completions
2019-10-18 17:35:59 -07:00
Tim Suchanek 9ff9c41a9a Add completion test for partial generic object (#34559) 2019-10-18 08:59:49 -07:00
Daniel Rosenwasser d2fab65df6 Added test. 2019-10-17 17:04:45 -07:00
Andrew Branch 454a3a0b0f
Fix auto-imports from auto type acquisition definitions (#33766)
* Fix auto-imports from ATA typings

* Compare canonical filenames in isImportablePath
2019-10-17 13:59:09 -07:00
Andrew Branch f41b7b59ce
Fix quick info for methods whose contextual type is a mapped type property (#33930) 2019-10-17 10:54:01 -07:00
Andrew Branch a95a25b9a7
Fix completions of optional properties in generic positions (#33937)
* fixes #30507

* Add test case for generic Partial type

* Fixes #28470

* Simplify contextFlags binary check

* Add string literal completion test

* Fix ContextFlags typings

* Speed up inference expression for completion

* Fix baseline merge

* Make contextFlags internal

* Reapply readonly array changes

* accept baselines

* Fix generic completion tests

* Re-merge ContextFlags

* Don’t change type during inference

* Fix typos and superfluous undefined arguments

* Add test for completions in unconstrained generic object literal
2019-10-17 10:45:40 -07:00
Orta 5d20c573a6
Merge pull request #34524 from orta/fix_32675
Does not add a duplicate completion when offering an export which was re-declared as a global
2019-10-17 13:08:32 -04:00
Orta Therox 85010fa6fe Make sure that global module re-exports are short-cutted to be added to completions 2019-10-17 12:33:01 -04:00
Nathan Shively-Sanders f3a234caac
Dedupe inherited jsdoc comments (#34522)
JSDoc on own properties was already deduped, but inherited jsdoc was
incorrectly not deduped.

Fixes #32708
2019-10-16 15:56:01 -07:00
Orta Therox c40ddb183e Does not add a duplicate completion when offering an export which was re-declared as a global - fixes #32675 2019-10-16 17:02:35 -04:00
Nathan Shively-Sanders 29f9493d87
Fix crash when exporting+aliasing globalThis inside declare global (#34408)
* global module:Fix crash when exporting+aliasing globalThis

* Fix another globalThis crash

find-all-refs assumed that an export inside a `declare x` was always an
ambient module, but it is not -- `declare global` does not allow
`export`, so find-all-refs shouldn't return any refs for this error case.
2019-10-15 14:05:39 -07:00
Andrew Branch e146f0d13d
Allow inferFromUsage to do auto-imports (#33915)
* Add test

* Auto-import instead of using ImportTypeNodes

* Write more tests and fix namespace case

* Remove unused enum memmber

* Update API baselines

* Lint

* Style nits and util consolidation
2019-10-14 10:33:00 -07:00
Andrew Casey 87c905f423 Handle string literals in merge conflict regions
Check for undefined, like the other code paths in the same function.
2019-10-09 14:46:19 -07:00
Wenlu Wang 3d8252c70e avoid space before dot question (#33840) 2019-10-07 17:11:54 -07:00
Andrew Branch 7be7cba050 Fixes binding well known symbol assignment via element access (#33687)
* Fix binding well-known symbols by element access

* Add navigationBar test

* Revert settings.json change

* Accept baselines

* Actually make it bind

* Accept API baselines

* Dont use internal name in API
2019-09-30 16:14:07 -07:00
Wenlu Wang 7c50bccec2 nullish coalescing commit (#32883)
* migrate nullish coalescing commit

* add more test case

* add branch type check test

* add more tests

* fix nullish precedence

* update public api

* add rescan question question token to fix regression

* update public api baseline

* Added tests that emit for nullish coalescing operator conforming with grammar restrictions when assertions are used.

* Fixed emit to hoist temporary variables (they previously went undeclared).
Added tests to ensure calls and property accesses are only called once.

* use not equal to null

* rename factory

* add grammar check

* fix more cases

* Fix handling of nullish coalescing oprator in expando objects.

* Fixed classifier to support ?? operator.

* update baseline

* accept baseline

* fix review

* update emitter and more testcase

* update control flow

* make linter happy

* update libs

* avoid unnecessary assert

* fix typooo

* Fixes for control-flow analysis
2019-09-30 15:33:50 -07:00
Andrew Branch f89de95955
Allow special element access assignments to create declarations (#33537)
* Start enabling element access special assignment

* Treat element access assignment as special assignment in JS

* Make declarations for bindable element access expressions

* Fix navigationBar crash

* Add multi-level test for JS

* Propagate element access expressions to more code paths

* Fix property access on `this`

* Add quick info test

* Uhhh I guess this is fine

* Fix module["exports"] and property access chained off element access

* Add test for this property assignment

* Add test for and fix prototype property assignment

* Fix teeeest???

* Update APIs

* Fix element access declarations on `this`

* Fix go-to-definition

* Add declaration emit to tests

* Reconcile with late-bound symbol element access assignment

* Fix baselines

* Add JS declaration back to tests

* Fix JS declaration emit of non-late-bound string literal property names

* Revert accidental auto-format

* Use `isAccessExpression`

* Add underscore escaping member to test

* Fix and test navBar changes
2019-09-30 15:08:44 -05:00
Ron Buckton fcd9334f57
Add support for Optional Chaining (#33294)
* Add support for Optional Chaining

* Add grammar error for invalid tagged template, more tests

* Prototype

* PR feedback

* Add errors for invalid assignments and a trailing '?.'

* Add additional signature help test, fix lint warnings

* Fix to insert text for completions

* Add initial control-flow analysis for optional chains

* PR Feedback and more tests

* Update to control flow

* Remove mangled smart quotes in comments

* Fix lint, PR feedback

* Updates to control flow

* Switch to FlowCondition for CFA of optional chains

* Fix ?. insertion for completions on type variables

* Accept API baseline change

* Clean up types

* improve control-flow debug output

* Revert Debug.formatControlFlowGraph helper
2019-09-30 12:33:28 -07:00
Wesley Wigham 293816875c
Support some late-bound special property assignments (#33220)
* Support some late-bound special property assignments

* Integrate PR feedback

* PR feedback

* Enable declaration on core tests

* Specialize type of binary expression used for late binding, speculative fix to navigation bar, merge check and type for elem/property accesses

* Add test showing current nav bar behavior (specifically the lack thereof)
2019-09-27 13:54:50 -07:00
Andrew Branch 304fcee09b
Updated: Only auto-import from package.json (#32517)
* Move package.json related utils to utilities

* Add failing test

* Make first test pass

* Don’t filter when there’s no package.json, fix scoped package imports

* Use type acquisition as a heuristic for whether a JS project is using node core

* Make same fix in getCompletionDetails

* Fix re-exporting

* Change JS node core module heuristic to same-file utilization

* Remove unused method

* Remove other unused method

* Remove unused triple-slash ref

* Update comment

* Refactor findAlias to forEachAlias to reduce iterations

* Really fix re-exporting

* Use getModuleSpecifier instead of custom hack

* Fix offering auto imports to paths within node modules

* Rename things and make comments better

* Add another reexport test

* Inline `symbolHasBeenSeen`

* Simplify forEachAlias to findAlias

* Add note that symbols is mutated

* Symbol order doesn’t matter here

* Style nits

* Add test with nested package.jsons

* Fix and add tests for export * re-exports

* Don’t fail when alias isn’t found

* Make some easy optimizations

* Clean up memoization when done

* Remove unnecessary semicolon

* Make getSymbolsFromOtherSourceFileExports pure

* Cache auto imports

* Revert "Cache auto imports"

This reverts commit 8ea4829587.

* Handle merged symbols through cache

* Be safer with symbol declarations, add logging

* Improve cache invalidation for imports and exports

* Check symbol presence first

* Only run cache invalidation logic if there’s something to clear

* Consolidate cache invalidation logic

* Fix reuseProgramStructure test

* Add more logging

* Only clear cache if symbols are different

* Refactor ambient module handling

* Start caching package.json stuff

* Support package.json searching in fourslash

* Move import suggestions cache to Project

* Start making more module specifier work available without having the importing file

* Going to backtrack some from here

* Get rid of dumb cache, fix node core modules stuff

* Start determining changes to a file have invalidated its own auto imports

* Move package.json related utils to utilities

* Add failing test

* Make first test pass

* Don’t filter when there’s no package.json, fix scoped package imports

* Use type acquisition as a heuristic for whether a JS project is using node core

* Make same fix in getCompletionDetails

* Fix re-exporting

* Change JS node core module heuristic to same-file utilization

* Remove unused method

* Remove other unused method

* Remove unused triple-slash ref

* Update comment

* Refactor findAlias to forEachAlias to reduce iterations

* Really fix re-exporting

* Use getModuleSpecifier instead of custom hack

* Fix offering auto imports to paths within node modules

* Rename things and make comments better

* Add another reexport test

* Inline `symbolHasBeenSeen`

* Simplify forEachAlias to findAlias

* Add note that symbols is mutated

* Symbol order doesn’t matter here

* Style nits

* Add test with nested package.jsons

* Fix and add tests for export * re-exports

* Don’t fail when alias isn’t found

* Make some easy optimizations

* Clean up memoization when done

* Remove unnecessary semicolon

* Make getSymbolsFromOtherSourceFileExports pure

* Cache auto imports

* Revert "Cache auto imports"

This reverts commit 8ea4829587.

* Handle merged symbols through cache

* Be safer with symbol declarations, add logging

* Improve cache invalidation for imports and exports

* Check symbol presence first

* Only run cache invalidation logic if there’s something to clear

* Consolidate cache invalidation logic

* Fix reuseProgramStructure test

* Add more logging

* Only clear cache if symbols are different

* Refactor ambient module handling

* Finish(?) sourceFileHasChangedOwnImportSuggestions

* Make package.json info model better

* Fix misplaced paren

* Use file structure cache for package.json detection when possible

* Revert unnecessary changes in moduleSpecifiers

* Revert more unnecessary changes

* Don’t watch package.jsons inside node_modules, fix tests

* Work around declaration emit bug

* Sync submodules?

* Delete unused type

* Add server cache tests

* Fix server fourslash editing

* Fix packageJsonInfo tests

* Add node core modules cache test and fix more fourslash

* Clean up symlink caching

* Improve logging

* Function name doesn’t make any sense anymore

* Move symlinks cache to host

* Fix markFileAsDirty from ScriptInfo

* Mark new Project members internal

* Use Path instead of fileName

* Rename AutoImportSuggestionsCache

* Improve WatchType description

* Remove entries() from packageJsonCache

* Fix path/fileName bug

* Also cache symlinks on Program for benefit of d.ts emit

* Let language service use Program’s symlink cache
2019-09-27 13:38:31 -07:00
Andrii Dieiev a34fdb203e Better template literals support in checker (#32064)
* Support template literals in enum declarations

* Support template literals in const enum access

* Support template literals in swith with typeof narrowing

* Support template literals in element access discriminant

* Support template literals in ambient module declaration

* Unify symbols for template literals in computed properties

* Unify expression position checks for template literals

* Support template literals in rename and find all references

* Mark computed properties with template literals as write access

* Inline startsWithQuote
2019-09-27 12:04:13 -07:00
Wesley Wigham 61cb06ce40
Allow allowJs and declaration to be used together (#32372)
* Allow allowJs and declaration to be used together

This intorduces a new symbol-based declaration emitter - currently this
is only used for JSON and JavaScript, as the output is likely worse than
what the other declaration emitter is capable of. In addition, it is
still incomplete - it does not yet support serializaing namespaces.

* Add tests for various import/export forms, add notes on export as namespace and fix export * from

* Tests & fixes for computed names

* Add test with current @enum tag behavior

* fix declaration emit for jsdoc @enum tags

* Small adjustments to base class serialization to fix bugs in it

* Guard against type/type parameter confusion when using typeParameterToName a bit

* Integrate feedback from PR

* Fix issue with export= declarations visibility calculation and type declaration emit that impacted all forms of declaration emit

* Only make one merged getCommonJsExportEquals symbol for a symbol

* Support preserving type reference directives in js declarations

* Skip declare mdoifiers for namespace members in ambient contexts

* FAKE ALIASES AND NAMESPACES EVERYWHERE

* Dont do namespace sugar when type members contain keyword names

* Fix json source file export modifier under new output

* Such clean nested aliasing, very wow

* Fix lint

* Add visibility errors, reuse type nodes where possible

* Suppoer having correctly named import types in bundled js declaration emit & adjust binding to allow namespaces with aliases to merge when the aliases look to be type-only

* Better support for module.exports = class expression

* Fix discovered crash bug

* Allow export assigned class expressions to be reachable symbols from external declarations

* Add missing semicolon

* Support @enum tag post-merge

* preserve comments on signatures and declarations where possible

* Basic support for js classy functions

* Add example we should do better with

* Prototype assignments make things a bit wonky, but the example from the PR seems OK

* Make a ton of changes to support the new way js classes are bound

* Remove some old comments, fix import and export default names

* Fix bug in object define handling and add tests for object define property declaration emit

* Fix organization nits from PR comments

* Preserve comments from jsdoc declarations on properties and js declaration type aliases

* Merge export declarations with identical specifiers

* Remove completed TODO comment

* Split lint

* Remove now-unused function

* PR feedback

* Add some project references tests, remove some checks from project refs codepaths that are now invalid

* Update project references tests again

* Merge and update project references tests

* Rename case

* Update test to include declaration output

* Remove yet another project refernces redirect extension check

* Update comment

* Add additional import ref to test

* Add shorthand prop to test

* Fix comment text

* Extract var to temp

* Simplify function and add whitespace

* Update project refs test to use incremental edit entry

* Stylistic refactors in the symbol serializer

* Another round of PR feedback, mostly style, small bugfix with constructors, and test showing bug in export assigned class expression name shadowing

* Use x instead of index
2019-09-26 14:27:16 -07:00
Nathan Shively-Sanders 500a0df6f3
Add useDefineForClassFields flag for Set -> Define property declaration (#33509)
* Disallow property/accessor overrides

Unless the base property or accessor is abstract

* Disallow uninitialised property overrides

This causes quite a few test breaks. We'll probably want to revert many
of them by switching to the upcoming `declare x: number` syntax.

* Updates from design review + fix ancient bug

1. Don't error when overriding properties from interfaces.
2. Fix error when overriding methods with other things. This had no
tests so I assume that the code was always dead and never worked.

* Need to add a couple of errors and squash one

Will update after checking out other branch for a minute

* Everything works so far

Need to test properties initialised in constructor

* Check for constructor initialisation

* change error wording

* Improve error wording

* Add codefix to add missing 'declare'

* Always emit accessors in .d.ts files

* Allow 'declare' on any uninitialised property decl

* Undo code moves

* Let sleeping dogs lie

* Correctly set NodeFlags.Ambient

And simplify redundant parts of check.

* Remove more unneeded code

* Update baselines

* Update baselines

* Update baselines

* Ignore this-property assignments

* Fix base-in-interface check

* Do not error when base parent is interface

* Fix base interface check

* Add missed baselines

* Fix check

* Fix new errors in services

* Fix new errors in services

* Fix errors in testRunner

* Add flag and turn off errors when on

* Structure of new emit is correct, fake content

It is 'hi'.

* Basically right emit

* Fix one last unitialised property declaration

* Haha no I missed another one

* Fix whitespace back to CRLF

* Minor fix and code cleanup

* New test case

* Fix bug in isInitializedProperty

* Updates from design meeting.

1. Change flag name to useDefineForClassFields (and flip polarity).
2. Forbid ES3 + useDefineForClassFields (since there is no
defineProperty).
3. Forbid overriding an abstract property-with-initializer with an
accessor.

* Update baselines

* Object.defineProperty for methods too

Using code from Ron from his upcoming refactor of the factory functions.

* Update slow baselines

* Improve error message

* Update src/compiler/transformers/utilities.ts

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

* Add test of computed properties

* Remove done TODO
2019-09-26 13:25:05 -07:00
Andrew Branch 7d9b22eea0
Add semicolon preference to formatter options (#33402)
* Add UserPreferences for semicolons

* Prototype formatter semicolon removal

* Implement semicolon insertion

* Fix existing tests

* Start adding tests

* Fix some edge cases of semicolon deletion

* Fix semicolon removal before comments

* Fix indentation

* Test on checker

* Replace semicolon-omitting writer with formatter preference

* Fix writing new nodes, update protocol

* Rename option

* Really fix formatting synthetic nodes

* Fix refactoring misses

* Un-update submodules gahhhh

* Update APIs

* Update for ESLint

* Revert accidental test change

* De-kludge deduplication of EOF processing

* Omit last element semicolon from single-line object-like types

* Revert "Omit last element semicolon from single-line object-like types"

This reverts commit 5625cb0237.

* Fix straggler test

* Add test for leading semicolon class members

* Rename a lot of stuff for clarity

* Invert some boolean logic
2019-09-26 13:23:29 -07:00
Anders Hejlsberg 27752c642f Merge branch 'master' into recursiveTypeReferences
# Conflicts:
#	src/compiler/checker.ts
2019-09-24 11:52:40 -07:00
Nathan Shively-Sanders f1104806d5
Merge pull request #33263 from microsoft/infer-from-usage/similarity-to-builtins
Infer from usage by similarity to builtin types
2019-09-24 07:44:34 -07:00
Anders Hejlsberg db7c03d868 Merge branch 'master' into recursiveTypeReferences
# Conflicts:
#	src/compiler/checker.ts
#	src/compiler/types.ts
#	tests/baselines/reference/api/tsserverlibrary.d.ts
#	tests/baselines/reference/api/typescript.d.ts
2019-09-21 08:52:14 -07:00
xiaofa 67aa2b22ac fix conflicts 2019-09-17 19:02:44 +08:00
kingwl 93a250b9a6 fix duplicate async modifier codefix 2019-09-14 02:22:59 +08:00
Nathan Shively-Sanders 3c79225f48 Update baselines with any[] inferences 2019-09-12 11:18:47 -07:00
Nathan Shively-Sanders b69f5af08e Merge branch 'master' into infer-from-usage/similarity-to-builtins 2019-09-12 10:50:13 -07:00
Jesse Trinity fd6fbdf7fe
Show more items in the navbar (#33040)
* show more items in navbar

* fixed missing node kind for property assignments

* updated navBarNestedCommonJsExports test

* updated navigationBarMerging_grandchildren test

* updated navigationBarItemsFunctions test

* updated navigationBarAnonymousClassAndFunctionExpressions test

* updated navigationBarFunctionIndirectlyInVariableDeclaration test

* updated navigationBarInitializerSpans test

* updated navigationBarItemsPropertiesDefinedInConstructors test

* updated tests

* change nav icon for properties with function-like initializers

* add test case for binding element with function-like initializer

* add navigationBarNestedObjectLiterals test

* add navigationBarFunctionLikePropertyAssignments test

* made some silly names less silly (?)

* added SpreadAssignments and ShorthandPropertyAssignments

* new wording for primary menu items
2019-09-11 15:54:27 -07:00
Orta e8fc62e1a2
Merge pull request #33300 from JoshuaKGoldberg/too-large-integer-bigint-codefix
Added codefix for numeric literals >= 2 ** 53
2019-09-11 22:53:19 +02:00
Orta fb9b3fe17d
Merge pull request #32345 from dragomirtitian/GH-32325-improve-const-function-extraction
Improved const extraction for function expressions and arrow functions
2019-09-11 21:19:45 +02:00
Josh Goldberg 79e9bb1c8f Added explicit check for scientific notation 2019-09-07 19:41:03 -04:00
Josh Goldberg 99f9719ab3 Added codefix for numeric literals >= 2 ** 53
`Number.MAX_SAFE_INTEGER` is `2 ** 53 - 1`, so anything greater than that is a 'dangerous' integer to store as a traditional number. This adds a codefix to suggest converting them to a `bigint` literal.
2019-09-07 18:43:32 -04:00
Nathan Shively-Sanders 330e51f098 Add test + reshuffle/rename new code 2019-09-06 15:15:19 -07:00
Nathan Shively-Sanders 052a3d9d73 Infer void from expr statement usage, not calls
This makes inferences a lot better.
2019-09-05 16:16:35 -07:00
Sheetal Nandi c26c44d5fc
Merge pull request #32266 from fuafa/properties-priorities
Add properties priority for completion
2019-09-05 11:09:11 -07:00
Andrew Branch b85134b00d
Fix smart selection bug with TemplateTails (#33108) 2019-09-05 09:01:41 -07:00
Nathan Shively-Sanders 17d1a7e052 Merge branch 'master' into infer-from-usage/similarity-to-builtins 2019-09-03 12:59:43 -07:00
Nathan Shively-Sanders 383286ff53 Add type parameter inference
It's a smeary copy of the checker's type parameter, so I feel bad about
duplicating that code. Not sure what the solution is, architecturally.
2019-08-30 13:44:06 -07:00
Mine Starks ad02f47f08
Merge pull request #33148 from minestarks/formatting-object-literals
Fixes #32923
2019-08-30 08:00:00 -07:00
xiaofa 909bc61f01 Add convert const to let 2019-08-30 18:05:07 +08:00
Mine Starks 9781b95bdc Fixes #32923 2019-08-29 15:31:09 -07:00
Armando Aguirre 029f7a3801
Merge pull request #33124 from armanio123/FixGotoMultipleFile
Fixed goto when global declarations are on multiple files
2019-08-29 14:13:32 -07:00
Nathan Shively-Sanders 37150d9cb5 Turn on findBuiltinTypes
Type parameter inference is special-cased, just moved from its previous
place with no improvement.
2019-08-29 12:40:33 -07:00
Titian Cernicova-Dragomir fa9e0fa8e8 Better outlining spans for prototype methods (#32782)
* Changed outlining to better outline ES5 classes (functions assigned to prototype)

* Changed outlining to better outline ES5 classes (properties assigned to functions)

* Fixed some small bugs when merging es5 class nodes. Added tests for new es5 class outline.

* Added support for interlaced ES5 classes (where an ES5 class's members are mixed with other declarations).

* Fixed crash in outline when assigning {} to the prototype.

* Added support for nested es5 declarations.

* Added support for prototype assignment for es5 classes.
2019-08-29 09:19:04 -07:00
Andrew Branch cd371daf77
Fix writing multi-line text without semicolons (#32903)
* Fix semicolon-omitting writer

* Use writeTrailingSemicolon for do statements
2019-08-28 16:28:31 -07:00
Armando Aguirre 09a5b68a85 Fixed goto when declarations are on multiple files 2019-08-28 15:14:19 -07:00
Wenlu Wang af9ca21643 add support for extract as interface (#31644)
* add support for extract as interface

* fix action assert

* Donot provide convert to interface if duplicate member
2019-08-28 11:34:40 -07:00
Nathan Shively-Sanders 13e1ccdd01
goto-def should treat constructor functions as functions (#33109)
* goto-def:special handling for constructor functions

* Just treat constructor functions like functions

* Even simpler fallback
2019-08-27 16:22:22 -07:00
Anders Hejlsberg b18c70f8c0 Fix fourslash test 2019-08-27 07:23:52 -04:00
Wenlu Wang 9942c6052f add completion for promise context (#32101)
* add completion for promise context

* check insert text inside add symbol helper

* fix incorrect branch

* avoid completions with includeCompletionsWithInsertText perferences

* avoid useless parameter
2019-08-26 15:26:25 -07:00
Armando Aguirre 5008c9cc3e
Merge pull request #33064 from armanio123/FixNavbarMultilineUnterminated
Added optional trailing slash to navigation bar regex
2019-08-26 12:06:36 -07:00
Nathan Shively-Sanders 21f192367a
Fix infer from usage prop assignment (#33088)
* Add test case

* Fix infer from usage property assignment

Property assignment and shorthand property assignment were incorrectly
treated differently; both have ObjectLiteralExpression as a parent, but
the code previously assumed that property assignments had
ObjectLiteralExpression as parent.parent.

Also make fourslash directives case insensitive and less whitespace
sensitive.

* Add "incorrect 3-slash" error to fourslash parsing.
2019-08-26 10:42:17 -07:00
Armando Aguirre a0c29fe4e5 Added optional trailing slash regex 2019-08-23 15:42:03 -07:00
Armando Aguirre 25f609b3a2
Merge pull request #32672 from armanio123/FixNavbarMultiline
Fixed issue for navbar when having multi-line string literals
2019-08-23 15:02:25 -07:00
Andrew Casey 00d37268e8 Make triple-slash comment classification more restrictive
It was overly permissive and ended up making a mess of C#-style
comments:

`/// <summary>Text</summary>`

Now it checks the element name.  Attribute names remain unchecked.
2019-08-23 12:55:10 -07:00
Andrew Branch 5d04250ea8
Improve “Add missing await” fix-all (#32922)
* Improve codeFixAll for add missing await

* Improve add missing await for initializers and fix-all

* Fix when only one side of a binary expression can have its initializer fixed
2019-08-20 16:53:28 -07:00
Zixiang Li 24201cfe6e Add support for jsdoc properties with hyphen (#32631) 2019-08-20 14:49:40 -07:00
Nathan Shively-Sanders 6ca9d04b60
Constructor functions as classes (#32944)
* Initial implementation

The original test passes but I haven't run any other tests yet, so I
assume the world is now broken.

* Append constructor function construct sigs

Instead of overwriting them

* Grab bag of improvements.

1. Mark @class-tagged functions with Class too.
2. Only gather local type parameters of constructor functions.
3. Remove getJSClassType calls with getDeclaredTypeOfSymbol.
4. Add a couple more failing tests.

getDeclaredTypeOfClassOrInterface now needs to understand prototype
assignment. That's next, I think.

* Prototype assignments work now

1. Binder marks prototype assignments as Class now.
2. Checker merges prototype assignments using the same merge code as for
functions and their declarations. No more intersections.

Many fewer failing tests now.

* Mark prototype-property assignments as Class

Even if there are no this-property assignments in them. (Then why are
you using a class?).

* Simplify getJSClassType, remove calls to its guts

It's probably not needed because now it's just a conditional call to
getDeclaredTypeOfSymbol, and I think most callers already know whether
they have a JS constructor function beforehand.

* isJSDocConstructor doesn't need to check prototype anymore

Because all the properties are merged during getDeclaredTypeOfSymbol.

* outer type parameter lookup follow prototype assignment

* this-type and -expression support in ctor funcs

Pretty cool!

* Fix remaining tests

* Fix minor lint

* Delete now-unused code

* Add class flag to nested class declarations

Also remove old TODOs
2019-08-19 14:12:53 -07:00
Nathan Shively-Sanders 2b8ccf40ae
jsdoc template tags might be unmatched (#32936)
* jsdoc template tags might be unmatched

* Update fourslash test
2019-08-16 13:39:57 -07:00
Hoang Pham 46b7972885 Add JSX codefix if available (#32281)
* Add JSX codefix if available

* Update react jsx.

* Update diagnostic code.
2019-08-16 12:46:55 -07:00
Wesley Wigham 1747ee7a55
Perfer the non-module name of a symbol when writing the name of a symbol (#32880) 2019-08-14 17:16:17 -07:00
Andrew Branch 2217f0b859
Fix export=global auto import exclusion (#32898) 2019-08-14 15:50:25 -07:00
Daniel Rosenwasser c8d937ecd3
Merge pull request #32726 from fuafa/completion-after-private
Fix completion disappear after a property declaration with a private modifier
2019-08-13 11:09:32 -07:00
Ron Buckton decc3cd671
Elide /index from auto-import when using rootDirs compiler option (#32828) 2019-08-12 16:05:15 -07:00
Orta 2a2866c3a9
Merge pull request #32563 from orta/fix_31298
Handle namepaths inside JSDoc type expressions a bit better
2019-08-09 16:15:50 -07:00
Ron Buckton 98b6db81d9
Allow accessors in ambient class declarations (#32787)
* Allow accessors in ambient class declarations

* Update src/compiler/transformers/declarations.ts

Co-Authored-By: Wesley Wigham <wewigham@microsoft.com>
2019-08-09 16:11:25 -07:00
Wesley Wigham f2719f95b4
Allow functions and ambient classes to merge (#32584) 2019-08-09 16:10:10 -07:00
Sheetal Nandi b7e49d1d1c Ignore unknown files to search from in document highlights 2019-08-09 15:06:51 -07:00
Armando Aguirre 98729b4462 Truncate to 150 chars and added unit tests 2019-08-07 13:50:18 -07:00
Andrew Branch 984956afec
Only add unnecessary-await suggestion on await expressions (#32754) 2019-08-07 11:27:36 -07:00
Orta Therox 77cdca2971 Adds another test around parsing jsdoc 2019-08-06 15:45:28 -04:00
Orta Therox 487e2ffe2a Merge master 2019-08-06 15:34:06 -04:00
Nathan Shively-Sanders 269c3d3a56
Suggestions now use diagnosticCollection (#32740)
Previously they used multiMaps, unlike all the other diagnostics. This
prevents duplicate suggestions, like other kinds diagnostics.

Fixes #28710
2019-08-06 11:15:06 -07:00
xiaofa e1bca8ff2a Fix class member completion disappear after a property declaration with a private modifier 2019-08-06 08:35:34 +08:00
Andrew Branch c1e0db7953
Escape apparent substitution in synthesized NoSubstitutionTemplateLiterals (#32580)
* Add failing test

* Escape apparent substitution in synthesized NoSubstitutionTemplateLiterals
2019-08-05 09:31:59 -07:00
Andrew Branch e82d0af554
Fix readonly occurrences highlighting (#32583)
* Fix readonly occurrences highlighting

* Rename function

* Rename again

* Apply suggestions from code review

Remove unused function
2019-08-02 18:24:46 -07:00
Andrew Branch 62f65a7884
Make auto-imports more likely to be valid for the file (including JS) & project settings (#32684)
* Add failing tests

* Use default import or namespace import for import fixes when compiler options allow

* Don’t do import * for export=, ever

* Only do import default for export equals if nothing else will work

* Never do import/require in a JavaScript file

* Update tests for changes in master

* Add const/require fix for JS and select based on usage heuristic

* Fix JS UMD import
2019-08-02 15:58:10 -07:00
Andrew Branch 725321f08c
Prioritize “property names” over punctuation in smart select (#32687)
* Prioritize “property names” over punctuation in smart select

* Update doc comment
2019-08-02 15:57:44 -07:00
Orta 4a26271b63
Merge pull request #32663 from orta/fix_31195
Ensure that the comma is removed when all named imports are removed via moveToFile
2019-08-02 10:29:51 -04:00
Orta 78e03848a4
Merge pull request #31946 from orta/30246
Don't let the additional property setting on an object show up as a definition to tsserver
2019-08-02 10:29:34 -04:00
Orta Therox c337f046fb Ensure that the comma is removed when all named imports are removed via moveToFile - fixes #31195 2019-08-01 15:01:52 -04:00
Orta Therox 3145656f6a Merge branch 'master' of https://github.com/microsoft/typescript into 30246 2019-07-31 17:08:45 -04:00
Andrew Casey dbe9e3d237
Merge pull request #32565 from amcasey/TripleSlashClassification
Support classification of triple-slash references
2019-07-29 12:27:55 -07:00
Orta Therox 30aad9db8d Support more terminators for parsing jsdoc filepaths 2019-07-29 09:46:42 -04:00
Wesley Wigham 2a4930f4ec
Bind a jsdoc enum as SymbolFlags.TypeAlias and not SymbolFlags.Enum (#32520)
* Bind a jsdoc enum as SymbolFlags.TypeAlias and not SymbolFlags.Enum

* Actually include an @enum tag as a declaration

* Add enum tag refs into a couple more syntax kind lists

* accept symbol baseline update
2019-07-26 13:57:22 -07:00
Orta Therox b902a71e5f Handle namepaths inside JSDoc type expressions a bit better - fixes #31298 2019-07-25 19:38:48 -04:00
Andrew Casey 9647506d8c Support classification of triple-slash references
Note: not restricted to the element and attribute names that actually
bind
2019-07-25 15:59:17 -07:00
Andrew Branch aa12ec440c
Fix smart select on last blank line of file (#32544)
* Fix SmartSelection on last blank line of file

* Add baseline
2019-07-25 09:47:57 -07:00
xiaofa 3d7bda0ad6 prioritize exclude class or right of dot 2019-07-25 11:52:27 +08:00