Commit graph

175 commits

Author SHA1 Message Date
Wesley Wigham da86332120
Limit export= js declaration emit to only json source files (#40882) 2020-10-01 14:55:24 -07:00
Wesley Wigham ad2a07440c
Fix crash on js declaration emit of export assigned default augmented function (#40596)
* Fix crash on js declaration emit of export assigned default augmented function

* {sp}
2020-09-23 00:50:12 -07:00
Nathan Shively-Sanders e350c357d2
Alias for module.exports.x = x (#40228)
* Alias for `module.exports.x = x`

This fixes #40155 in a surprisingly small amount of code.

* Treat any aliasable expression as an alias

* test internal references to exported class
2020-09-10 11:23:48 -07:00
Wesley Wigham 683979246f
Fix JS declaration emit for acessors in a class/interface merge (#40456) 2020-09-10 10:39:41 -07:00
Wenlu Wang ee5f51bc0f
Add see tag support (#39760)
* Add see tag parser

* add baseline

* fix symbol resolve

* add more case

* fix unittests

* improve tests and parser

* accept baseline

* Adopt package-lock.json and npm ci

* Add a workflow to update package-lock.json daily

* Git ignore package-lock.json and forcibly update in workflow

* Update bot email address

* Delete extra npm update

* Update package-lock.json

* Add compactDisplay and signDisplay to NumberFormatOptions (#40039)

* Fix typo in (Readonly)Set.keys comment (fixes #40164) (#40176)

* fix(26325): use a unique name for reserved words in 'constructor like' function name (#39684)

* fix(25770): add diagnostic message for the possible mapped type used as an index (#39973)

* fix(31046): add new diagnostic message for incompatible constructor signature (#40073)

* Update package-lock.json

* Update package-lock.json

* Add rename support

* Accpet baseline

* wip

* fix anders

* Revert "fix anders"

This reverts commit b3178d4618.

* Fix call hierarchy item serialization and server tests (#40348)

* Avoid error

* accept baseline

* Add more tests

* Add signature name resolve

Co-authored-by: Andrew Casey <andrew.casey@microsoft.com>
Co-authored-by: TypeScript Bot <typescriptbot@microsoft.com>
Co-authored-by: Neil Kistner <neil.kistner@gmail.com>
Co-authored-by: cherryblossom000 <31467609+cherryblossom000@users.noreply.github.com>
Co-authored-by: Alexander T <alexander.tarasyuk@outlook.com>
Co-authored-by: Erich Gamma <egamma@microsoft.com>
Co-authored-by: Andrew Branch <andrewbranch@users.noreply.github.com>
2020-09-09 10:45:09 -07:00
Wesley Wigham 155610e114
Better support class instances assigned to the module object for JS declarations (#40037)
* Better support class instances assigned to the module object for JS declarations

* Extract constant
2020-09-05 02:23:12 -07:00
Nathan Shively-Sanders c3d41bbb73
Alias for commonjs require in JS (#39770)
* First attempt at aliases for require

* test+initial support for const x=require

* 1st round of baseline improvements

* 2nd round of baseline updates

* support property access after require

* check @type tag on require

* forbid expando missing namespaces on aliases

taken from #39558 as soon as it was created

* accept error baselines that are good, actually

* Scribbling on d.ts emit code

* use getSpecifierForModuleSymbol

* hideous hack for module.exports of aliases

* Fix module.exports.x --> export list emit

* fix isLocalImport predicate

* require only creates aliases in JS

* re-handle json imports

* update fourslash baseline

* Cleanup in the checker

1. Simplify alias resolution.
2. Simplify variable-like checking.
3. Make binding skip require calls with type tags -- they fall back to
the old require-call code and then check from there.

I haven't started on the declaration emit code since I don't know what
is going on there nearly as well.

* Function for getting module name from require call

* First round of cleanup plus a new test

Found one missing feature, not sure it's worth adding.

* more small cleanup

* more cleanup, including lint

* use trackSymbol, not serializeTypeForDeclaration

* Code review comments, plus remove unneeded code

Ad-hoc type reference resolution for `require` isn't needed anymore.

* find all refs works

* remove old ad-hoc code

* make it clear that old behaviour is not that correct

* update api baselines

* remove outdated comment

* PR feedback

1. Fix indentation
2. Add comment for exported JSON emit
3. Add test case for nested-namespace exports.

* add a fail-case test (which passes!)
2020-08-17 14:00:37 -07:00
Eli Barzilay 620e260576 Avoid the double-symbol trick for enums
Nameless jsdoc typedefs have their exportedness controlled by the
exportedness of the location they pull their name from.

Fixes #33575.
2020-08-12 18:40:57 -04:00
Wesley Wigham 94989789df
In JS declaration emit, move imports painted in nested contexts to the root private context (#39818)
* In JS declaration emit, move imports painted in nested contexts to the root private context

* Add test for nathan
2020-07-31 18:25:37 -07:00
Nathan Shively-Sanders 9b2d487392
Fix this-parameter emit for JSDocFunction types (#39814)
* Fix this parameter emit for JSDocFunction types

Previously, parameters with names that were not `new` were treated like
rest parameters. This is incorrect: parameters with the name `this`
should emit a `this` parameter.

Fixes #38550

* ❤️ quote style
2020-07-29 14:11:59 -07:00
Nathan Shively-Sanders 3b107fec3b
Fix @param type parameter lookup (#39532)
Previously, getObjectTypeInstantiation had special-case code to look up
type parameters for `@param` as if they were in the parameter location.

This should occur in the main lookup loop of `getOuterTypeParameters`,
however. The current code only runs once, which is not sufficient, and
it also jumps to the parameter for any type contained in a `@param`,
which skips type parameters that occur in the tag itself.
2020-07-10 08:42:25 -07:00
Wesley Wigham dd2b2447d0
Add regression test for #38834 (#39479) 2020-07-08 13:32:15 -07:00
Nathan Shively-Sanders 53a756ea63
Type this in more constructor functions (#39447)
* Type `this` in more constructor functions

Previously,  `this: this` in constructor functions only when there was
an explicit `@constructor` tag on the function. Now, `this: this` for
any function that's known to be a constructor function.

This improves completions inside constructor functions; also note that
previously the compiler *did* type `this: this` inside methods of constructor
functions, so this fix makes us more consistent. This is reflected in
the large number of baselines that improve.

The fix is a simple switch to `isJSConstructor`, which is the standard
way to detect constructor functions. I'm not sure why the original PR
didn't use this method.

I remember discussing this limitation in the original bug, #25979, and
I guess I decided that it made sense. But I was heavily primed by the bug's
framing of the problem in terms of `noImplicitThis`, which *should*
require an explicit `@constructor` tag.

With better typing comes better detection of `@readonly` assignment; I
had to fix the readonly detection code to use `isJSConstructor` as well.

* Remove `Add @class tag` fix for noImplicitThis.

The new rules mean that it never applies. It's possible that it should
apply to functions like

```js
function f() {
  this.init()
}
```

In which `init` is never defined, but I think this program is incomplete
enough that not offering the fix is fine.

* Fix precedence of `@this`

Previously, both `@class` and `@this` in a jsdoc would cause the `@this`
annotation to be ignored. This became a worse problem with this PR,
because `this` is correctly typed even without the annotation.

This commit makes sure that `@this` is checked first and used if
present.
2020-07-08 08:44:17 -07:00
Anders Hejlsberg 8c6b85835f
Properly handle rest parameters in function declarations with @type annotations (#39473)
* Properly handle rest parameters in function declarations with @type annotations

* Add tests
2020-07-07 16:35:37 -07:00
Wesley Wigham d2b32b422f
Ensure type/namespaceish statics are included in the list of namespace merge members (#38920)
* Ensure type/namespaceish statics are included in the list of namespace merge members

* Simplit into two lines

* Update baseline post-merge
2020-07-07 16:28:09 -07:00
Nathan Shively-Sanders 9a65658b28
Parse *= separately in types (#39457)
* Parse *= separately in types

Previously, when the scanner produced `*=` as a single token, the type
parser ran special-case code to produce an "optional all type", which
only makes sense when the `=` really should be attached to the `*`. This
is often not the case.

The correct solution, which I missed when I first wrote this code, is to
have the scanner go back and produce a separate `=` token, which is what
this PR does.

* add test from #38551

* we ❤️ semicolons
2020-07-07 08:30:42 -07:00
Nathan Shively-Sanders c3c6be6618
In JSDoc, parse postfix-? below conditional types/tuple types (#39123)
Outside of JSDoc comments, postfix-? is parsed at lower precedence than
the `?` of conditional types, and a postfix-? inside a tuple type
results in the type being marked optional.

This PR changes JSDoc parsing to behave the same way, which means that

1. Conditional types are allowed in JSDoc. Fixes #37166.
2. Tuple types' postfix-? syntax is interpreted correctly in JSDoc.
Fixes #38747.

The breaking change is that a postfix-? type followed by another postfix type,
like `[]` or `!`, is parsed as a conditional type. [Postfix-? is not
common](https://github.com/microsoft/TypeScript/issues/37166#issuecomment-612274456),
so this is an acceptable breaking change.

A postfix-? type `T?` is still parsed everywhere else and treated as `T | null`.
2020-06-17 14:06:39 -07:00
Nathan Shively-Sanders 9f872c01e1 Merge branch 'master' into fix-implements-tag-emit 2020-06-11 16:05:21 -07:00
Wesley Wigham 08cb0b23e8
Serialize (noncontextual) keyword named namespace members with export declarations in both declaration emitters (#38982)
* fix(38750): create unique names for keywords and re-export them with original names

* Serialize (noncontextual) keyword named namespace members with export declarations in both declaration emitters

* Add exhaustive keyword emit test for js declaration emitter and fix it up

Co-authored-by: Alexander T <alexander.tarasyuk@outlook.com>
2020-06-10 14:42:49 -07:00
Wesley Wigham 2287dbc7e2
Handle missing return type nodes and nested type references missing type arguments in existing jsdoc node serialization (#39011)
* Handle missing return type nodes and nested type references missing type arguments in existing jsdoc node serialization

* Accept updated baselines
2020-06-10 12:42:38 -07:00
Nathan Shively-Sanders c5f66716cf Fix @implements emit for namespaced base types
Fixes #38640
2020-05-20 10:29:39 -07:00
Ron Buckton 1cbe7ef000
Fix crash in JS declaration emit (#38508)
* Fix crash in JS decl emit

* Emit as class with private ctor
2020-05-15 14:00:59 -07:00
Ron Buckton d07e866a28
Fix for jsdoc modifiers on constructor params (#38403)
* Fix for jsdoc modifiers on constructor params

* Update Public API baseline and fix unique symbol grammar check for js
2020-05-11 15:07:43 -07:00
Wenqi 1b7b3eb0f7
report error for duplicate @type declaration (#38340) 2020-05-11 12:47:49 -07:00
Wesley Wigham 7b03835b77
Fix js missing type arguments on existing nodes and jsdoc object literal declaration emit (#38368)
* Fix js missing type arguments on existing nodes and jsdoc object literal declaration emit

* Add special lookups test case, rename helper

* Accept slightly modified baselines
2020-05-08 10:46:28 -07:00
Alexander T c219fdae08
fix(37703): forbid required parameter after optional (#38155) 2020-05-05 10:29:17 -07:00
Wesley Wigham 815dc90dc5
Issue an error on cross-file merges we cant emit (#38148) 2020-04-23 19:01:16 -07:00
Wesley Wigham 136f728bb0
Fix js declaration emit for inherited and this-typed inherited fields (#37970) 2020-04-21 13:13:50 -07:00
Alexander T a2628c9088 fix(37242): add reference to return type for JSDocFunctionType 2020-04-17 09:05:23 +03:00
Wesley Wigham b4838c8b62
Use comments from host variable declaration when exporting a signature in js declarations (#37594) 2020-04-08 13:32:17 -07:00
Nathan Shively-Sanders 7ca6334dbd
Look for outer type parameters on VariableStatements (#37819)
This only applies in JS, where `@template` tags can apply to
initialisers of variable declarations:

```js
/**
 * @template T
 * @returns {(b: T) => T}
 */
const seq = a => b => b
```

Fixes #36201
2020-04-07 08:04:33 -07:00
Nathan Shively-Sanders eac073894b
Fix serialisation of static class members in JS (#37780)
* Fix serialisation of static class members in JS

Previously static class members would be treated the same way as expando
namespace assignments to a class:

```ts
class C {
  static get x() { return 1 }
}
C.y = 12
```

This PR adds a syntactic check to the static/namespace filter that
treats symbols whose valueDeclaration.parent is a class as statics.

Fixes #37289

* fix messed-up indent

* Extract function
2020-04-03 20:06:05 -07:00
Wesley Wigham 78a99241d8
Reuse input type nodes when serializing signature parameter and return types (#37444)
* Accept change

* Accept the huge set of ever so slightly changed baselines

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

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

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

* Fix type parameter reuse lookup

* Forbid cjs module.exports references in retained nodes

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

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

* Accept fourslash baseline updates

* Accept slightly updated baseline post-merge

* Do not copy original nodes for error types, replace empty type references with any
2020-04-01 19:50:21 -07:00
Wesley Wigham dfc0b58fe7
Preserve arity for preserving js optional parameters (#37173) 2020-03-04 00:48:53 -08:00
Wesley Wigham 5941c6e1b1
Emit an any for namepath types (#37176) 2020-03-03 10:55:21 -08:00
Wesley Wigham d209092ccc
Use merged symbol to pick up js-alias-merged members on export assignments (#37162) 2020-03-02 12:57:00 -08:00
Nathan Shively-Sanders 392fd0ac0b
Remove bogus @implements errors (#37114)
* Remove bogus @implements errors

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

* undo gratuitous name change

* Improve name and make calling more uniform

It's slightly less efficient but I think worthwhile for readability.
2020-03-02 09:48:53 -08:00
Titian Cernicova-Dragomir f883bf3acb
Adding support for @implements. (#36292)
* Adding support for @implements.

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

* Fixed declaration emit for @interface

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

* Removed unnecessary checks from getImplementsTypes
2020-02-27 09:27:37 -08:00
Nathan Shively-Sanders 3e3df8702c
Fix crash on aliased,exported @enum tag in jsdoc (#36996)
THe code to bind `@enum` and `@typedef` didn't handle the case that the
`@enum` was on a property assignment to an alias of module.exports.
Specifically, `x` needs to be correctly aliased to the file's symbol in
the example below:

```
var x = module.exports = {};
/** @enum {string} */
x.E = {
  A: "A"
};
```
2020-02-24 16:13:18 -08:00
Nathan Shively-Sanders 1bbcb5553a
@typedef's nested Object syntax disallows type arguments (#36172)
Previously the jsdoc index signature syntax was incorrectly treated the
same as Object:

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

Fixes #34911
2020-01-29 12:53:00 -08:00
Nathan Shively-Sanders 0cf100dcf8
Add constructor functions to aliasable expressions (#36108)
* Add constructor functions to aliasable expressions

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

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

* add simple test case

* remove errors in test

* fix bad merge
2020-01-29 09:36:59 -08:00
Nathan Shively-Sanders 757e67041e
Fix getExpandoSymbol for already-expando symbols (#36457)
* Fix getExpandoSymbol for already-expando symbols

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

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

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

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

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

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

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

* Better check for getExpandoSymbol of expando

Check the declaration directly instead of the initialiser.
2020-01-27 12:32:56 -08:00
Wesley Wigham 9e712dd097
Consider SymbolFlags.Method as function-esque during js declaration emit (#36274) 2020-01-24 10:29:23 -08:00
Nathan Shively-Sanders 517d6eea28
Get jsdoc host from chained assignment (#36111)
* Get jsdoc host from chained assignment

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

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

* cleanup lint

* use existing utility
2020-01-10 10:09:39 -08:00
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
Nathan Shively-Sanders 3d2b92ce69
Readonly support for jsdoc (#35790)
* Add @readonly

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

* In-progress

Add ctor function test
Add some notes and rename variable

* Done except for cleanup and fix 1 bug

* Fix last test and clean up
2019-12-20 13:47:20 -08:00
Nathan Shively-Sanders 3c5ecc2a60
Add jsdoc support for @public/@private/@protected (#35731)
* Add @private/@protected/@public test

* Fix @declaration

* draft abstraction + one usage

* Fill in necessary parsing etc

* make general getEffectiveModifierFlags

move to utilities, make the right things call it

* reorder public/private/protected

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

* revert unneeded/incorrect changes

* Update baselines and skip @public/etc when parsing

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

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

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

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

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

* Fix constructor emit

1. Emit protected for protected, which I missed earlier.
2. Emit a constructor, not a property named "constructor".
3. Split declaration emit tests out so that errors are properly reported
there.
2019-12-18 12:58:12 -08:00
Eli Barzilay d6740cf410 Fix getTypeFromJSDocValueReference
When using `{import('./b').FOO}` which is defined as a string literal,
`valueType` doesn't have a `symbol`.  Leave it for the fallback value
for now.

This was exposed in 8223c0752.

Fixes #34869.
2019-11-27 17:53:11 -06:00
Nathan Shively-Sanders f3344767dd
Fix import type resolution in jsdoc, mark 2 (#35057)
Fake alias resolution only applies when the import type is followed by a
qualified name. Otherwise the alias is sufficiently resolved already.
2019-11-12 12:44:30 -08:00
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