Commit graph

131 commits

Author SHA1 Message Date
Wenlu Wang 41dc625b0a
Add static index signature (#37797)
* Add static index

* fix lint

* make lint happy

* adjust test cases

* add more cases

* fix changes

* Add more case

* accept baseline

* fix error if extends others

* Update vfsUtil.ts

* use equal to empty array

* static signature of interface is an error

* Accept baseline

* Check index constraints for static signature

* Accpet baseline

* Fix crash

* fix crash

* Accept baseline

* Fix regression

* Fix crash

* always return new array
2021-03-26 15:30:09 -07:00
Titian Cernicova-Dragomir e638af7560
ES private class elements (#42458)
* Added support for private identifier methods.

* Added tests for private methods.

* Added check to only not allow private name method signatures in anything except classes.
Changes objects literal checking to not bail on first private name found in object literal.

* Added private accessors tests

* Transform private methods

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Rename shouldTransformPrivateFields

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Accept baseline

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Use a single WeakSet for brand-check

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Accept baseline

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Add a test for using private methods in static field initializers

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Add breaking checker test

Private methods inside class expressions should not error.

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Add to instances once per-instance

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Accept baseline

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: evaluate receiver and rhs expressions before throwing on readonly assignment

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Add a test for evaluating rhs before readonly assignment

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Transpile private accessors

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Accept baseline

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: handle readonly/writeonly accessors

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* accept baseline

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add a test for private setter without a getter

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: getAllUnscopedEmitHelpers

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: better handling of duplicate names

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Fixed wrong error message for private methods in class expressions.

* change error message

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add a test for async private methods with a higher target

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: setter assignment returns rhs value

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add a test for setter assignment return value

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: handle duplicate accessors

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add tests for duplicate accessors

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* docs: add missing parameter docs

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Fixed failing test.

* baseline-accept: ordering changes

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* fix: attach weakSetName to property declaration

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add a test for nested private methods

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* add a test with any

Signed-off-by: Kubilay Kahveci <kahvecikubilay@gmail.com>

* Added support for static private fields accessors and methods.

* Added error message for private identifiers used with static decorators. There is no spec to go with this behavior as of yet.

* Fixed emit static bug that used private names outside of classes for initialization in esnext. Fixed issue where nested privates produce incorrect brand check.

* Added tests for private static fields methods and accessors.

* Fixed error messages and tests after merge.

* Accept new baseline.

* Improved duplicate identifier checks for static private class elements.

* Added error when using initializers with private static fields when useDefineForClassFields is not specified and target is esnext.

* Fixed code review issues.

* Removed semantically wrong emit on `useDefineForClassFields:true` with `target:esnext`

* Changed emit for uninitialized private static fields.

* Added runtime error in helper if a static private field is accessed before it was declared.

* Fixed code review comments for private identifier static class elements.

* add debug.assertNever for unknown node type (#53)

* Fixed code review issues.

* Fixed code review issues for private class elements.

* Fixes class shadowing when checking access to a private static class element.

* fix private methods/accessors in class expr inside a loop

* collapse switch case

* fix class name

* simplify getPrivateMethodsAndAccessors

* remove findPreviousAccessorInfo

* lazily create weakSetName identifier

* do not allocate a node if not needed in visitMehodDeclaration (#55)

* Removed all the emit helpers for private identifier methods accessors and modified the existing helpers for get and set fields to do the same job.

* Simplified emit for private identifier class elements.

* do not clone the receiver (#57)

* leave bad code in for #constructor and duplicate private names (#58)

* Added check for WeakSet collision.

* Added error for using a set only accessor.

* update keyof tests and ?? (#62)

* replace ?? with ||

* update keyof tests

* fix emit helpers comments

* produce an error if private field helpers are not up to date

* add tests

* fix setter-only compound assignment

* fix tests

* fix duplicated trailing comments (#64)

* clear receiver pos and setTextRange on helper calls

Co-authored-by: Kubilay Kahveci <kahvecikubilay@gmail.com>
2021-03-24 18:15:50 -07:00
Nathan Shively-Sanders b2d1f537f1
Bloomberg computed property name fix (#43197)
* Fix property name bindings for class expr in loops

* Fix block-scope capturing with prop initializers

Co-authored-by: Joey Watts <joey.watts.96@gmail.com>
2021-03-11 10:32:42 -08:00
Titian Cernicova-Dragomir a2ed469022
Fix for crash when using ca call expression on private identifier coming from an any typed variable. (GH #42860) (#42861) 2021-02-18 13:54:10 -08:00
Song Gao 3e28e29c51
fix 38503. (#39716)
* fix 38503.

* trigger test.

* trigger test.

* Move isCallChain

Co-authored-by: Ron Buckton <ron.buckton@microsoft.com>
2021-02-01 18:34:46 -08:00
Oleksandr T 1ecf22884f
fix(42166): allow assertion signature for private identifiers (#42176) 2021-01-11 09:25:51 -08:00
Ron Buckton 0d284e6c26
Add support for abstract constructor types (#36392)
* Add support for abstract constructor types

* Add backwards-compatible overloads for creating/updating constructor types

* Reverting use of 'abstract' in lib/es5.d.ts due to eslint issues

* Update baseline due to reverting lib

* Add error for failing to mark an mixin class as abstract

* Fix declaration/quick info for abstract construct signatures
2021-01-07 17:11:14 -08:00
Oleksandr T b405fdd2ab
fix(41420): forbid optional chain in extends/implements (#41481) 2021-01-04 15:38:54 -08:00
Oleksandr T 841b1a5bc7
fix(37791): fix incorrect private field access in a computed property name (#38135) 2021-01-04 14:01:54 -08:00
Oleksandr T 45b698b3f6
fix(40632): skip emitting abstract members (#40699) 2020-11-04 16:02:17 -08:00
Alexander T 09d68efae1
fix(28516): forbid using async modifier with the abstract modifier (#39963) 2020-09-04 14:59:53 -07:00
Song 8a05707559
Fix 31995: make cached key more precise to avoid returning wrong cached value. (#39670)
* fix 31995

* revert useless change only for debug.

* add test
2020-07-22 12:26:17 -04:00
Ron Buckton a7d6825e25
Fix temp vars referenced in parameter (#38130)
* Fix temp vars referenced in parameter

* Update error message
2020-04-23 20:45:39 -07:00
Nathan Shively-Sanders 6ea291a142
Remove superCallShouldBeFirst error (#37947)
* Remove superCallShouldBeFirst error

It seems redundant since TS gives an error on any use of `this` before
super, and non-`this` uses before `super` should be fine.

Fixes #37371

* Revert "Remove superCallShouldBeFirst error"

This reverts commit 3c09153c8a.

* error except for target:"esnext" && useDefineForClassFields
2020-04-21 12:58:37 -07:00
Nathan Shively-Sanders 63ff6572ae
Fix use-before-def with methods on esnext+useDefineForClassFields (#38033)
* Fix use-before-def with methods on esnext+useDefineForClassFields

It was incorrectly flagging methods as used before their definition, but
this is allowed under any emit.

* Add instance function test case
2020-04-21 08:09:25 -07:00
Klaus Meinhardt 9b518c8f53
Exempt ambient private properties from noImplicitAny (#36640) 2020-02-14 15:01:18 -08:00
Eli Barzilay 1a1ed7464d Add a similar test for target.symbol.valueDeclaration
(With the same question still open.)
2020-01-30 22:42:04 -05:00
Eli Barzilay 68a9d4592f Avoid testing isClassDeclaration if there's no valueDeclaration
I'm not sure if this is enough -- perhaps it's better to make the test
dig through the interface/s to the class?

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

* remove changes in lib/*
2020-01-30 13:39:54 -08:00
Nathan Shively-Sanders c1e45ac8af
Fix use-before-def errors for ESNext property declarations (#36465)
* Fix use-before-def errors for ESNext property declarations

Fixes #36441
Fixes #36442

* Handle property declarations in nested classes
2020-01-30 10:58:07 -08:00
Nathan Shively-Sanders 36169b4d13
Class fields w/esnext+[[Define]]:no shadow error (#36405)
* Class fields w/esnext+[[Define]]:no shadow error

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

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

* add negative test case

* Add explanatory comment
2020-01-29 14:47:44 -08:00
Nathan Shively-Sanders 368db997ed
ESNext+[[Define]]: reference to param props illegal (#36425)
* ESNext+[[Define]]: reference to param props illegal

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

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

emits code that looks like this:

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

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

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

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

Here is the case with no errors:

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

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

* Update baselines

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

* remove outdated comments
2020-01-24 14:52:48 -08:00
Klaus Meinhardt 49eb0d7a2b Disallow 'declare' modifier on private named properties (#36381)
Fixes: #36345
2020-01-23 13:18:10 -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
Klaus Meinhardt 6e3ab1529f remove private named properties from rest and spread types (#35950)
* remove private named properties from rest and spread types

Fixes: #35943

* code review
2020-01-14 14:47:39 -08:00
Nathan Shively-Sanders 13cddae3f7
Allow references to uninitialized ambient properties (#36112)
Previously these were incorrectly treated just like normal properties:

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

Fixes #35327
2020-01-10 10:50:05 -08:00
M.Yoshimura 5fc917be2e Fixes broken emit with useDefineForClassFields + private field (#35898)
* Fixes broken emit with useDefineForClassFields + private field

* use simpler function for condition
2020-01-09 10:21:49 -08:00
Titian Cernicova-Dragomir 3e4578c9f4 Fixed unreported strict property initialization violations. (#35891) 2020-01-08 15:15:20 -08:00
Joey Watts f84b2d20a9 Parse error on private identifier optional chain (#35987)
Previously, this error was reported in the checker, so JS files with
checkJs: false were not erroring on this invalid syntax.
2020-01-07 16:00:15 -08:00
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 369900bb07
Emit defineProperty calls before param prop assignments (#34987)
* Emit defineProperty calls before param prop assignments

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

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

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

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

* Put parameter property initialiser into defineProperty's value

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

Previously:

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

would incorrectly emit

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

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

* Fix bug for ESNext as well

This moves the check earlier in the pipeline.

* update baselines
2019-11-22 14:52:29 -08:00
Ron Buckton 6c59dc34ac
More tests for super.method call chain, improve vary-by (#35013) 2019-11-18 18:03:37 -08:00
Klaus Meinhardt 5321dcb09f disallow 'await' and 'yield' in property and enum member initializer (#34892)
* disallow 'await' and 'yield' in property and enum member initializer

* accept baseline changes

* Add a test for #34887

Ensures that this fixes #34887
2019-11-14 17:44:48 -08:00
Klaus Meinhardt 94f85901d7 strip QuestionToken from MethodDeclaration and PropertyDeclaration emit (#34954)
* strip QuestionToken from MethodDeclartion emit

Fixes: #34953

* test property emit
2019-11-12 10:30:46 -08:00
Nathan Shively-Sanders 1d5add528d
Emit computed property temps even w/o init w/useDefineForClassFields (#34406)
Fixes #33857
2019-10-18 13:23:38 -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
Ron Buckton 3b96729e01
Fix visitLexicalEnvironment to properly merge hoisted declarations (#33219) 2019-09-03 15:29:41 -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
Andrew Branch 4f3412153a
Parse quoted constructors as constructors, not methods (#31949)
* Parse quoted constructors as constructors, not methods

* Update baselines

* Fix disambiguation between quoted constructor and property named constructor

* Clean up parsing a bit

* Support escapes in constructor name

* Update baselines
2019-07-12 14:01:57 -07:00
Ron Buckton 179381301e
Move class property transform (#31848)
* Revert "Revert "Move class property transformation into new transformer. (#30467)""

This reverts commit 53467ae4a4.

* Fix emit issues
2019-06-17 14:26:42 -07:00
Ron Buckton 7611c5b931
Fix for computed properties in instance initializers (#31517) 2019-05-22 11:17:54 -07:00
Andrew Branch e81fa2198d
Emit error on class fields named "constructor" 2019-04-25 17:30:41 -07:00
Andrew Branch c5e6913ede
Add grammar error on quoted constructors for TS 3.5 2019-04-25 15:44:23 -07:00
Andrew Branch 72f30a8308
Add test for quoted constructors 2019-04-25 11:35:10 -07:00
Anders Hejlsberg 2d44a40202 Add regression test 2019-02-05 13:08:18 -08:00
Andrey Roenko bea7ed1aa7 Merge branch 'master' into fix-generic-types-intersections 2018-11-20 20:31:02 +03:00
Andy e0dca0bd95
Error when destructuring private property in a parameter (#28562) 2018-11-16 12:47:05 -08:00
Andrey Roenko 15b4af63dd #27716: fix protected methods for intersection fo generic classes 2018-10-12 18:23:07 +03:00