Commit graph

263 commits

Author SHA1 Message Date
Andrew Branch 9dfbf07d8a
Find references of a module by filename (#41805)
* Naive implementation enough to build and write a test

* Add simple test

* Add project references test

* Add deduplication test, accept baselines

* Add test for referencing a script (doesn’t do anything)

* Update API baselines

* Use refFileMap for non-module references

* Fix find-all-refs on module specifier

* Remove unused util

* Don’t store text range on ts.RefFile

* Ensure string literal could itself be a file reference

* Remove unused utilities

* Improve baseline format

* Preserve old behavior of falling back to string literal references

* Update baselines from master

* Fix old RefFileMap code after merge

* Add test for additional response info

* Undo test change
2020-12-11 12:37:02 -08:00
Andrew Branch 266d8de64a
Proposal: importModuleSpecifierPreference: project-relative (#40637)
* Add new importModuleSpecifierPreference value

* Add second test

* Update API baselines

* Clean up and add some comments

* Rename option value
2020-11-11 11:48:32 -08:00
Orta Therox db5368dc1d
Import the semantic highlighter from typescript-vscode-sh-plugin (#39119)
* Initial import of the vscode semantic highlight code

* Adds the ability to test modern semantic classification via strings instead of numbers

* Adds existing tests

* Port over the semantic classification tests

* Update baselines

* Update src/harness/fourslashImpl.ts

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

* Handle feedback from #39119

* Consistent formatting in the 2020 classifier

* Update baselines

* Apply suggestions from code review

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>

* Update src/harness/fourslashImpl.ts

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>

* Reafactor after comments

* Use 2020 everywhere

* Handle feedback

* WIP - don't provide a breaking change

* Fix all build errors

* Update baselines

* Update src/services/classifier2020.ts

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>

* Addresses Ron's feedback

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>
2020-09-11 15:10:55 -04:00
Andrew Branch f6f2d36ee3
Add optionalReplacementSpan to completions response (#40347)
* Add optionalReplacementRange to completions response

* Get the name right

* Fix unit tests

* Fix comment typo

* Fix comment typo

* Baseline
2020-09-04 13:09:52 -07:00
Sheetal Nandi 03d946d145
Revert to including only open files in partial semantic server mode (#40026) 2020-08-12 20:45:59 -07:00
Sheetal Nandi da5ff57608
Renames in servermode per feedback (#39883)
* Server mode renames as per feedback

* More renames
2020-08-05 12:19:15 -07:00
Sheetal Nandi aee78acedb
Add separate flag serverMode for server mode (#39735)
* Add separate flag serverMode for server mode to allow back compatibility

* Addressed code review feedback.

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-08-02 18:18:26 -07:00
Andrew Branch 86a87c493c
Limit auto import provider project size (#39855)
* Limit auto import provider project size

* Add test

* Make option configurable

* Fix test

* Only bail when setting is auto

* Fix other test

* Update API baseline
2020-08-02 17:47:49 -07:00
Andrew Branch ec33814616
Make AutoImportProviderProject work with symlinked monorepos (#39679)
* Hack everything together

* Add test

* Remove realpath from program

* Ensure symlinked directories are directories

* Revert unnecessary change

* Update baselines

* Use host program realpath on AutoImportProviderProject files before program creation

* Which fixes hasRoots() too

* Apply suggestions from code review

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>

* Lint

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>
2020-07-22 13:53:30 -07:00
Sheetal Nandi 667ba74c93
Resolve only relative references in open files on syntax server (#39476)
* Resolve only relative references in open files on syntax server

* Support resolving tripleslash references only in the open file

* Apply suggestions from code review

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-07-16 14:31:24 -07:00
Armando Aguirre ef81a0d0ee Merge remote-tracking branch 'upstream/master' into AddToggleCommentFeature 2020-07-09 21:55:36 -07:00
Armando Aguirre b81f240e96 PR comments 2020-07-09 18:35:54 -07:00
Ron Buckton 7b942b4fa8
Revert the type change to ts.Map (#39366) 2020-07-01 17:00:26 -07:00
Ron Buckton eb2f4e2337
Switch to ES Map/Set internally (#33771)
* Add full implemention of Map and Set to shims

* Update default Map interface

* Remove WeakMap/WeakSet

* Add tests for set shim

* Update most usages of Map<K, true> to Set

* PR Feedback

* Fix lint issues

* Change key in fsWatchCallback

* Simpler shim, more tests

* Fix typo in collection shim
2020-06-26 10:12:47 -07:00
Ron Buckton cc7cb9eadb
Upgrade typescript-eslint version (#39242)
* Upgrade typescript-eslint version

* Update TS version used by typescript-eslint
2020-06-24 16:43:03 -07:00
Andrew Branch 086e00de91
Expand auto-import to all package.json dependencies (#38923)
* Start experiment

* Add logging

* Go back to a single program

* Fix forEachExternalModuleToImportFrom

* Move auxiliary program to language service

* Add logging

* Don’t use resolution cache

* Fix(?) containingProjects for ScriptInfo in auxiliary program

* Fix ScriptInfo project inclusion

* Add test for default project of auto-importable ScriptInfo

* Add fourslash server test

* Don’t create auto import provider inside node_modules

* Add monorepo-like test

* WIP

* Naively ensure autoImportProvider is up to date after package.json change

* Start limiting when auto update provider gets updated

* Respond to changes in node_modules

* Don’t create auto-import provider until a file is open that would use it

e.g., don’t create them during cross-project find-all-refs

* Clean up naming, @internal marking, and fix empty project creation bug

* Drop devDependencies, include peerDependencies

* Add additional compiler options

* Fix interaction with importSuggestionsCache

* Move option to UserPreferences, allow inclusion of devDependencies

* Don’t filter out peerDependencies

* Watch unparseable package.jsons

* But don’t filter packages out due to an invalid package.json

* Update test

* Don’t use autoImportProvider in codefixes where it can never be used (or any refactors)

* Add CompletionEntry property for telemetry

* Add assertion for isPackageJsonImport to fourslash

* Fix missing pushSymbol argument

* Add isPackageJsonImport to tests and API baselines

* Fix unit test

* Host auto import provider in new Project kind

* Fix InferredProject attaching on AutoImportProvider-included files, load eagerly

* Update Public APIs

* Simplify PackageJsonCache host

* Remove unneeded markAsDirty

* Defer project finished event until after AutoImportProvider is created

* Make AutoImportProviderProject always report isOrphan = true

* Close and remove AutoImportProviderProject when host project closes

* Don’t set pendingEnsureProjectForOpenFiles

* Use hasAddedOrRemovedFiles instead of hasNewProgram

* Use host-wide watchOptions for package.json watching

* Add to `printProjects`

* Clean up

* Get autoImportProvider directly from LanguageServiceHost

* Clean up

* Clean up

* Close auto import provider on disableLanguageService

* Move AutoImportProvider preload to project updateGraph

* Clear auto import suggestion cache when provider program changes

* Fix tests

* Revert yet-unneeded change

* Use projectService host for module resolution host

* Don’t re-resolve type directives if nothing has changed

* Update src/server/project.ts

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>

* Use ts.emptyArray

Co-authored-by: Sheetal Nandi <shkamat@microsoft.com>
2020-06-22 16:34:27 -07:00
Pranav Senthilnathan 2f793892f1
Add reason for a disabled code action (#37871)
* add reason for a disabled code action

* add addOrRemoveBracesToArrowFunction

* use user preferences

* add error reason

* accept baseline changes

* fix lint rules

* move messages to diagnosticMessages.json

* rename 'error' to 'notApplicableReason'

* accept baseline change

* address comments
2020-06-22 08:16:47 -07:00
Wenlu Wang 59ad375234
Add deprecated related feature (#38523)
* Add deprecated related feature

* Add more support

* fix navtree

* Add identifier check

* Add more deprecated

* fix crash

* fix more crash

* fix crash

* improve diagnostic

* avoid new tag

* avoid tags

* accept baseline

* Check deprecated in binder

* fix baseline

* fix jsdoc cache

* fix incorrect fix

* Avoid useless changes

* Accept baseline

* Add tests

* fix perf

* fix public api

* Adjust deprecated mark on qualifed name

* Revolve alias symbol

* Use modifier flags insted of symbol props

* Fix modifier flag resolve

* Make lint happy

* Fix crash

* fix crash

* Add cached utils function

* Accept baseline

* Add more tests

* try pinning octokit again

* Avoid tests

* Use utils some

* Deprecated perf test (#3)

* check valueDeclaration only

* check without modifierFlags

* donot check alias

* use cached tag

* remove call to jsdoc

* use deprecated tag

* revert changes

* Revert mission changes

* use node flags

* cache result

* cache

* avoid modifier flags

* Opts

* fix jsdoc include modifier

* fix tests

* fix again

* use symbol flag

* set @octokit/rest back to latest

* fix trailing spacel int

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-06-18 17:41:26 -07:00
Andrew Branch 852e7a0b60
Add containerName to CallHierarchyItem (#38997)
* Add containerName to CallHierarchyItem

* Update public APIs

* Update test to demonstrate nested namespace working
2020-06-10 11:56:03 -07:00
Sheetal Nandi a72ed0a2f5
Schedule failed lookup updates (#38560)
* Schedule failed lookup updates

* Tests
2020-06-09 12:00:37 -07:00
Jesse Trinity f3751fbdf3 change type of RefactorTriggerReason 2020-05-29 12:54:59 -07:00
Jesse Trinity 23f4dc9bd9 use enum for RefactorTriggerReason 2020-05-29 12:49:41 -07:00
Jesse Trinity 602ee995d0 fix lint errors 2020-05-29 12:45:54 -07:00
Jesse Trinity bac046573f add trigger reason to protocol 2020-05-29 12:41:06 -07:00
Armando Aguirre ee37d8e8d3 Added comment and uncomment selection 2020-05-22 16:56:57 -07:00
Armando Aguirre 381dd8427a Removed TextRange and added FileRangeRequestArgs 2020-05-22 16:47:34 -07:00
Armando Aguirre 33333e86eb Added toggleLineComment, toggleMultilineComment with jsx and tests 2020-05-22 16:46:31 -07:00
Andrew Branch 707e977056
Ensure formatter can always get a newline character (#38579)
* Ensure formatter can always get a newline character

* Make FormatContext.host optional since it’s not necessary if format options are all applied

* Make FormattingHost required again
2020-05-19 13:14:32 -07:00
Wenlu Wang 8d78984558
Add support of contextual quick info (#37451)
* Add support of contextual quick info

* Avoid document comment map

* Make lint happy

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

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

* Make ModuleSpecifierResolutionHost internal

* Refactoring for ModuleSpecifierResolutionHost

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

* Update src/services/utilities.ts

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

Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
2020-03-17 13:21:40 -07:00
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
Orta f1cc8e4e4e
[minor] Adds some docs to the LSP interface (#36740)
* Adds some docs to the LSP dts

* Ensure that getProgramDiagnostic is included everywhere that getCompilerOptionsDiagnostic is

* Update baselines

* Apply suggestions from code review

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

* Remove the getCompilerOptionsDiagnostics -> getProgramDiagnostics change

Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
2020-03-13 13:26:39 -04:00
David 4406717f13
add config to insert space for empty braces (#35427) 2020-03-12 16:35:35 -04:00
Sheetal Nandi a76a16696d
Move useSourceOfProjectReferenceRedirect to program so other hosts can use it too, enabling it for WatchHost (#37370) 2020-03-12 13:11:11 -07:00
Sheetal Nandi 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
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
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
Ben Lichtman 49f7f2532c Rename new property 2020-01-07 13:02:21 -08:00
Ben Lichtman 1bc387938a Add property for unchecked completions 2020-01-07 10:59:19 -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
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
Sheetal Nandi 4212484ae1
Open bigger set of configured projects when opening composite project for operations that operate over multiple projects like rename (#33287)
* Add isInferredProject, isConfiguredProject and isExternalProject

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

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

* Fix addToSeen project key

* Refactor combineProjectsOutputWorker

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

* Add disableSearchSolution as option to disable looking for solution

* Rename the option to disableSolutionSearching
2019-12-11 12:28:18 -08:00
Wesley Wigham 27616dd523
Move codefix types into services/types.ts (#35506)
* Move codefix types into services/types.ts

* Also split apart refactorProvider

* Move all meanings of DocumentHighlights into one file

* Use setter for object allocator

* Remove unneeded namespace reference

* Remove some shorthand references to nonlocal namespace variables

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

* Rename harness to harnessIO

* Move accidental globals into namespace

* Remove unused globals

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

* Hide global declaration
2019-12-05 10:51:31 -08:00
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
Sheetal Nandi 850d16e45f Add forceDtsEmit flag to getEmitOutput
Fixes #33936
2019-10-15 10:07:19 -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
Wesley Wigham a8bea77d1e
Backfill TypeReference.typeArguments in the API (#33714) 2019-10-02 14:50:12 -07: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
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
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