* 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
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
* 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
* 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.
* 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
* 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
* Change type-only semantics to allow type queries
* Don’t error using type-only import in ambient context
* Fix default import
* Fix namespace import
* Update more baselines
* Prevent circular resolution
* Track const enum expression usage
* Update baselines
* Perf tuning 1
* Test commit for perf impact
* Weave type-only alias declaration finding into alias resolution
* Fix namespace import of type-only exported symbols
* type-only exports do not contribute to the module object type
* Update APIs
* Fix enum casing, remove type-only conversion suggestion
* Short circuit type-only checks in resolveEntityName faster
* Fix casing in API
* Remove unused parameter
* Fix error on qualified names in type queries
* Allow type-only imports in computed property names
* Fix computed property names of types and abstract members
* Remove unused util
* Commit missing baselines
* Rename “check” functions so as not to overload the word “check”
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
* Check combined intersection properties against target index signatures
* Add tests
* Accept new baselines
* Less aggressive check for index signatures
* Track intersection membership state for both source and target
* Minor fixes
* 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
* Binding element initializers contextually typed by parent initializers
* Accept new baselines
* Literal type widening should be last step in inference
* Accept new baselines
* Add tests
Prevent it from using the (return) type of a function. Could also check
the condition before calling the function, but there are two places that
need the check, and OTOH, all calls check the result so returning
`undefined` should work.
(This problem was introduced in PR#32553.)
Fixes#33741.
* Add type-only support for export declarations
* Use a synthetic type alias instead of binding type-only exports as a type alias
* Works for re-exports!
* isolatedModules works fine
* Diagnostic for type-only exporting a value
* Start isolated modules codefix
* Update for LKG control flow changes
* Type-only import clause parsing
* Type-only default import checking
* Type-only named imports
* Fix isolated modules error
* Filter namespaces down to type-only
* Fix class references
* Test nested namespaces
* Test circular type-only imports/exports
* Fix getTypeAtLocation for type-only import/export specifiers
* Fix type-only generic imports
* Update public APIs
* Remove unused WIP comment
* Type-only namespace imports
* Fix factory update calls
* Add grammar errors for JS usage and mixing default and named bindings
* Update updateExportDeclaration API baseline
* Fix grammar checking import clauses
* Enums, sort of
* Dedicated error for type-only enum
* Skip past type-only alias symbols in quick info
* Update error code in baseline
* WIP: convertToTypeOnlyExport
* isolatedModules codefix (single export declaration)
* isolatedModules code fix (all)
* Stop eliding non-type-only imports by default, add compiler flag
* Update to match updated diagnostic messages
* Update more baselines
* Update more tests
* Auto-import as type-only
* Add codefix for splitting type-only import with default and named bindings
* Add more services tests
* Add targeted error message for "export type T;" when T exists
* Add targeted error for "import type T = require(...)"
* Flip emit flag
* Add test for preserveUnusedImports option
* Fix flag flip on import =
* Make compiler option string-valued
* Fix merge conflicts
* Add --importsNotUsedAsValue=error
* Phrasing of messages.
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
* 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>
* init export start as decl
* fix some broken
* fix more case
* fix more and more case
* make it work
* make lint happy and accept baseline
* add more tests
* fix system module
* add more case
* delete useless assert
* accept baseline
* make lint happy
* fix missing utils
* update api
* make lint happy
* add missing semi
* fix minor issue
* fix locally bound
* avoid useless check
* update public api
* add more case
* fix some case
* Use multi-module selection in test runner to cut down on duplication.
* Accepted baselines.
* remove superfluous tests.
* Remove baseline.
* Downlevel `export * as ns` in es2015.
* Accepted baselines.
* Update names of things.
Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
* Increase selectivity of subtype relationship for signatures
* Add regression test
* Accept new baselines
* Use strictSubtypeRelation for union subtype reduction
* (x: number | undefined) -> void is subtype of (x?: number | undefined) => void
* Accept new baselines
* Add tests
* Accept new baselines
* Address CR feedback
* Fix parameter list length check
* Accept API baseline changes
* 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
* Ignore @private on constructor functions
This was incorrect in the best of circumstances and caused a crash when
the parent of the function had no symbol, because the accessibility
check assumed it was operating on a constructor and that the parent was
always the containing class.
* Non-constructors are always accessible
Previously, all function-like kinds were accessible, which includes
constructors. This was wrong.
* 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.
Top-level this-assignments do not support computed properties. But the
binder forgets to check for computed properties and tries to bind them
normally. This hits a helpful assert.
This change stop binding this-properties with computed properties at the
top-level. There's nothing sensible we could do with them; we're unable
to late-bind entries to the global scope or to modules.
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.
* When calculating spreads, merge empty object into nonempty object to produce partial object to reduce complexity
* Actually accept remainder of baselines
* Limit simplification to single prop or partial types
* 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
* 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
* Add inference priority level for conditional types in contravariant positions
* Accept new API baselines
* Add regression tests
* Accept new baselines
* Propagate 'undefined' instead of the optional type marker at an optional chain boundary
* Update src/compiler/types.ts
Co-Authored-By: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
* Fix alias naming and structure bugs in js declarations
* Add another test case and change condition for ns merge to require signature or export content
* Fix typo in comment
* Add isIntersectionConstituent to relation key
isIntersectionConstituent controls whether relation checking performs
excess property and common property checks. It is possible to fail a
relation check with excess property checks turned on, cache the result,
and then skip a relation check with excess property checks that would
have succeeded. #33133 provides an example of such a program.
Fixes#33133 the right way, so I reverted the fix at #33213Fixes#34762 (by reverting #33213)
Fixes#33944 -- I added the test from #34646
* Update comments in test
* resolve require with entity name postfix
For example, `require("x").c`. This is the value equivalent of
`import("x").a.b.c`, but the syntax tree is not as nicely designed for
this purpose.
Fixes#34802
* Add bug number to test
* Add optional chain test
The constructor function code path in the return type checking of
signatures needs to pass the *merged* symbol of the declaration to
getDeclaredTypeOfClassOrInterface. Other callers of
getDeclaredTypeOfClassOrInterface do this, or used an already-merged
symbol.
Fixes#33993
* Exclude ?? operator from true/false literal check in createFlowCondition
* Accept new API baselines
* Add tests
* Accept new baselines
* Address CR feedback
* Accept new API baselines
* Avoid a crash with `@typedef` in a script file.
Scripts (as opposed to modules) do not have a symbol object. If a script
contains a `@typdef` defined on a namespace called `exports`, TypeScript
crashes because it attempts to create an exported symbol on the
(non-existent) symbol of the SourceFile.
This change avoids the crash by explicitly checking if the source file
has a symbol object, i.e. whether it is a module.
* Add usage of exports.SomeName typedef.
* Fix bug at bind site rather than in declare func
* Fix expando handling in getTypeReferenceType
getExpandoSymbol looks for the initialiser of a symbol when it is an
expando value (IIFEs, function exprs, class exprs and empty object
literals) and returns the symbol.
Previously, however, it returned the symbol of the initialiser without
merging with the declaration symbol itself. This missed, in particular,
the prototype assignment in the following pattern:
```js
var x = function x() {
this.y = 1
}
x.prototype = {
z() { }
}
/** @type {x} */
var xx;
xx.z // missed!
```
getJSDocValueReference had weird try-again code that relied on calling
getTypeOfSymbol, which *does* correctly merge the symbols. This PR
re-removes that code and instead makes getExpandoSymbol call
mergeJSSymbols itself.
* Remove extra newline
* Restore delayed merge check to getTypeFromJSDocValueReference
This is needed when a function merges with a prototype assignment. The
resulting *merged* symbol is a constructor function marked with
SymbolFlags.Class. However, the merge doesn't happen until
getTypeOfFuncClassEnumModule is called, which, in the
getTypeReferenceType code path, doesn't happen until
getTypeFromJSDocValueReference. That means the check for
SymbolFlags.Class is missed.
Previously, getTypeFromJSDocValueReference had a weird check
`symbol !== getTypeOfSymbol(symbol).symbol`, which, if true, ran
getTypeReferenceType again on `getTypeOfSymbol(symbol).symbol`. For
JS "aliases", this had the effect of dereferencing the alias, and for
function-prototype merges, this had the effect of ... just trying again
after the merge had happened.
This is a confusing way to run things. getTypeReferenceType should
instead detect a function-prototype merge, cause it to happen, and
*then* run the rest of its code instead of relying on try-again logic at
the very end. However, for the RC, I want to fix this code by restoring
the old check, with an additional check to make sure that #33106 doesn't
break again:
```ts
const valueType = getTypeOfSymbol(symbol)
symbol !== valueType.symbol && getMergedSymbol(symbol) === valueType.symbol
```
I'll work on the real fix afterwards and put it into 3.8.
* Add bug number
* Fix crash in expando assignment to alias
This PR disallows expando assignments
Fixes#34493, but disallows the prototype assignment nonetheless.
* Revert mistaken changes
* Fix stack overflow in circular assignment declaration
It also needs to have multiple assignments so that it has a ValueModule
flag.
Fixes#33006
* remove errant comment
* Remove other possible circularity
* Restore fallback with additional condition
* global module:Fix crash when exporting+aliasing globalThis
* Fix another globalThis crash
find-all-refs assumed that an export inside a `declare x` was always an
ambient module, but it is not -- `declare global` does not allow
`export`, so find-all-refs shouldn't return any refs for this error case.
* migrate nullish coalescing commit
* add more test case
* add branch type check test
* add more tests
* fix nullish precedence
* update public api
* add rescan question question token to fix regression
* update public api baseline
* Added tests that emit for nullish coalescing operator conforming with grammar restrictions when assertions are used.
* Fixed emit to hoist temporary variables (they previously went undeclared).
Added tests to ensure calls and property accesses are only called once.
* use not equal to null
* rename factory
* add grammar check
* fix more cases
* Fix handling of nullish coalescing oprator in expando objects.
* Fixed classifier to support ?? operator.
* update baseline
* accept baseline
* fix review
* update emitter and more testcase
* update control flow
* make linter happy
* update libs
* avoid unnecessary assert
* fix typooo
* Fixes for control-flow analysis
* Start enabling element access special assignment
* Treat element access assignment as special assignment in JS
* Make declarations for bindable element access expressions
* Fix navigationBar crash
* Add multi-level test for JS
* Propagate element access expressions to more code paths
* Fix property access on `this`
* Add quick info test
* Uhhh I guess this is fine
* Fix module["exports"] and property access chained off element access
* Add test for this property assignment
* Add test for and fix prototype property assignment
* Fix teeeest???
* Update APIs
* Fix element access declarations on `this`
* Fix go-to-definition
* Add declaration emit to tests
* Reconcile with late-bound symbol element access assignment
* Fix baselines
* Add JS declaration back to tests
* Fix JS declaration emit of non-late-bound string literal property names
* Revert accidental auto-format
* Use `isAccessExpression`
* Add underscore escaping member to test
* Fix and test navBar changes
* 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