Commit graph

2583 commits

Author SHA1 Message Date
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
Andrew Branch 1bb6ea038f
Allow type-only namespace imports in implements clauses (#36464)
* Add test

* Allow type-only symbols in implements clauses

* Add more complex test
2020-01-27 16:13:30 -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
Andrew Branch 20e8eba143
Issue better error for exporting primitive type (#36424)
* Issue better error for exporting primitive type

* Delete nonsense
2020-01-27 08:11:21 -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
Wesley Wigham 9e712dd097
Consider SymbolFlags.Method as function-esque during js declaration emit (#36274) 2020-01-24 10:29:23 -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 b05dde747c
Update type-only import semantics to allow type queries (#36092)
* 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”
2020-01-23 12:53:36 -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
Andrew Branch 1d5749ef78
Fix local and exported type alias merging (#36237)
* Fix local and exported type alias merging

* Add baselines
2020-01-22 13:16:49 -08:00
Anders Hejlsberg da61231039
Include super.XXX(...) assertion method calls in CFA (#36293)
* Support super.XXX in assertions

* Add tests
2020-01-22 11:21:11 -08:00
Anders Hejlsberg 8517df6fa2
Fix erroneous optional chain narrowing (#36145)
* Not all optional chains are narrowable references

* Add regression test
2020-01-16 16:49:51 -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
Anders Hejlsberg 357f715382
Check combined intersection properties against target index signatures (#35143)
* 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
2020-01-10 10:46:10 -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
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
Anders Hejlsberg 0aab63b7ff
Fix narrowing of optional chains (#36089)
* Check for definitely not undefined instead of maybe not undefined

* Fix comment

* Add tests
2020-01-08 15:37:27 -08:00
Titian Cernicova-Dragomir 3e4578c9f4 Fixed unreported strict property initialization violations. (#35891) 2020-01-08 15:15:20 -08:00
Eli Barzilay ab1458ac55 Tweak the test and add more duplicate name assignment tests
(Both valid and invalid.)
2020-01-08 14:21:28 -05:00
Klaus Meinhardt 38b53790af Allow destructuring the same property multiple times
Fixes: #35939
2020-01-08 14:21:28 -05: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
Daniel Rosenwasser f807b57356
Add s to importsNotUsedAsValue (#36037)
* Pluralize end of 'importsNotUsedAsValue'.

* Updated baselines.
2020-01-06 13:23:47 -08:00
Anders Hejlsberg f8bfc6f5d6
Contextually typed binding element initializers (#35855)
* 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
2020-01-06 12:53:23 -08:00
Anders Hejlsberg df3b5bbdab
Fix ThisParameterType<T> type (#36013)
* Simplify ThisParameterType<T> type

* Add tests
2020-01-06 08:55:34 -10:00
Eli Barzilay d6c05a1358 Fix getEffectiveTypeAnnotationNode
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.
2020-01-03 22:47:17 -05:00
Andrew Branch 3b396e6124 Type-only imports and exports (#35200)
* Add type-only support for export declarations

* Use a synthetic type alias instead of binding type-only exports as a type alias

* Works for re-exports!

* isolatedModules works fine

* Diagnostic for type-only exporting a value

* Start isolated modules codefix

* Update for LKG control flow changes

* Type-only import clause parsing

* Type-only default import checking

* Type-only named imports

* Fix isolated modules error

* Filter namespaces down to type-only

* Fix class references

* Test nested namespaces

* Test circular type-only imports/exports

* Fix getTypeAtLocation for type-only import/export specifiers

* Fix type-only generic imports

* Update public APIs

* Remove unused WIP comment

* Type-only namespace imports

* Fix factory update calls

* Add grammar errors for JS usage and mixing default and named bindings

* Update updateExportDeclaration API baseline

* Fix grammar checking import clauses

* Enums, sort of

* Dedicated error for type-only enum

* Skip past type-only alias symbols in quick info

* Update error code in baseline

* WIP: convertToTypeOnlyExport

* isolatedModules codefix (single export declaration)

* isolatedModules code fix (all)

* Stop eliding non-type-only imports by default, add compiler flag

* Update to match updated diagnostic messages

* Update more baselines

* Update more tests

* Auto-import as type-only

* Add codefix for splitting type-only import with default and named bindings

* Add more services tests

* Add targeted error message for "export type T;" when T exists

* Add targeted error for "import type T = require(...)"

* Flip emit flag

* Add test for preserveUnusedImports option

* Fix flag flip on import =

* Make compiler option string-valued

* Fix merge conflicts

* Add --importsNotUsedAsValue=error

* Phrasing of messages.

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2020-01-03 14:39:32 -08:00
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
Kagami Sascha Rosylight 0f5ddd2ea0 Add es2020 transformation (#35518)
* Add es2020 transformation

* Add missing comma

Co-authored-by: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com>
2019-12-23 16:45:17 -08:00
Ron Buckton 114dad7f56
Add top-level await for esnext and system modules (#35813) 2019-12-22 13:24:31 -08:00
Kagami Sascha Rosylight deb5288e31 Add module: es2020 (#33893) 2019-12-20 16:29:49 -08:00
Wenlu Wang 4c7844be74 Implement export as namespace from (#34903)
* 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>
2019-12-20 16:00:20 -08:00
Anders Hejlsberg 2f0d07c29a
Increase selectivity of subtype relationship for signatures (#35659)
* 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
2019-12-20 14:52:22 -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 2cc1340a7b
Ignore @private/@protected on constructor functions (#35782)
* 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.
2019-12-20 08:41:52 -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
Ron Buckton 2eb60c2cb2
Fix decoding of HTML entities in TSX/JSX (#35739) 2019-12-17 17:32:48 -08:00
Anders Hejlsberg 71a91763f4
Fix33448 (#35513)
* Filter out discriminants of type 'never'.

* Add tests

* Accept new baselines

* Remove unnecessary '!' assertion
2019-12-12 06:45:46 -08:00
Nathan Shively-Sanders b98cb0645d
Fix binding of this-assignments w/computed properties (#35639)
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.
2019-12-11 15:55:08 -08:00
Anders Hejlsberg 09271f107d
Make no inferences from binding patterns with no defaults (#35454)
* Use nonInferrableAnyType in types inferred from binding patterns

* Add regression tests

* Accept new baselines
2019-12-05 07:09:45 -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
Wesley Wigham b9689228b5
When calculating spreads, merge empty object into nonempty object to … (#34853)
* 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
2019-11-22 17:19:17 -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
Anders Hejlsberg 94d4023043
Add inference priority level for conditional types in contravariant positions (#35199)
* Add inference priority level for conditional types in contravariant positions

* Accept new API baselines

* Add regression tests

* Accept new baselines
2019-11-21 13:05:44 -08:00
Kārlis Gaņģis 17f5469a2c Fix crash with Object.defineProperty for imported alias (--allowJs) (#35198)
Fixes #35196
2019-11-20 10:50:47 -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 fce728e07f fix emit for delete on optional chain (#35090)
* fix emit for delete on optional chain

* Apply suggestions from code review

Co-Authored-By: Ron Buckton <ron.buckton@microsoft.com>
2019-11-18 16:34:47 -08:00
Anders Hejlsberg 8b83703632
Properly strip readonly from rest argument types (#35169)
* Properly strip readonlyness from rest argument types

* Add tests

* Accept new baselines
2019-11-18 13:11:36 -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 8f40ac06cc optimize transform of optional chaining and nullish coalescing (#34951)
* optimize transform of optional chaining and nullish coalescing

* remove unnecessary condition

* typo

* fix lint

* prevent capturing of super

* swap branches again

* accept new baselines

* avoid temporary objects
2019-11-14 17:34:13 -08:00
Anders Hejlsberg 38db7ae59e
Properly analyze switch statement bypass control flow (#35087)
* Properly analyze switch statement bypass control flow

* Add regression test

* Accept new baselines
2019-11-13 09:22:18 -08: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
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
Anders Hejlsberg 3a5230ab3d
Defer switch exhaustiveness checks (#35000)
* Defer switch exhaustiveness checks until they're actually needed

* Add regression test

* Accept new baselines
2019-11-09 07:52:39 -08:00
Anders Hejlsberg 95be956320
Fix switch statement exhaustiveness checking (#34840)
* Don't optimize away CFA nodes representing missing default clauses

* Add regression test

* Accept new baselines
2019-11-05 12:05:41 -08:00
Ron Buckton ba5e86f140
Propagate 'undefined' instead of the optional type marker at an optional chain boundary (#34588)
* 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>
2019-11-01 11:36:22 -07:00
Wesley Wigham 8b7664ae15
Generate more correct property name nodes in declaration emit (#34741)
* Generate more correct property name nodes in declaration emit

* Silly only-on-CI lint rule T.T
2019-10-30 12:40:59 -07:00
Wesley Wigham d28672d97f
Fix alias naming and structure bugs in js declarations (#34786)
* 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
2019-10-30 12:40:06 -07:00
Nathan Shively-Sanders 00dd1f0609
Add isIntersectionConstituent to relation key (#34789)
* 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 #33213
Fixes #34762 (by reverting #33213)
Fixes #33944 -- I added the test from #34646

* Update comments in test
2019-10-29 15:08:59 -07:00
Nathan Shively-Sanders 7635884224
JSDoc type reference understands require with entity name (#34804)
* 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
2019-10-29 14:56:33 -07:00
Nathan Shively-Sanders 080e41dc90
Fix type reference to merged prototype property assignment (#34764)
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
2019-10-28 10:14:04 -07:00
Anders Hejlsberg c404c08fde
Fix reachability analysis for ?? operator (#34702)
* 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
2019-10-24 15:57:14 -07:00
Martin Probst a03227d60e Avoid a crash with @typedef in a script file. (#33847)
* 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
2019-10-24 14:04:42 -07:00
Nathan Shively-Sanders d892fd408f
Fix expando handling in getTypeReferenceType (#34712)
* 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
2019-10-24 13:12:44 -07:00
Nathan Shively-Sanders 969634b97c
Restore delayed merge check to getTypeFromJSDocValueReference (#34706)
* 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
2019-10-24 09:24:58 -07:00
Nathan Shively-Sanders 8223c07527
getTypeFromJSDocValueReference: handle import types (#34683)
Previously it only handled types whose declaration was from `require`,
but now it handles types whose reference is an import type as well.
2019-10-23 15:53:38 -07:00
Kārlis Gaņģis 479d30646f Fix crash in assigning function with this ref to alias (#34650) 2019-10-22 14:33:45 -07:00
Nathan Shively-Sanders 1cbbe288ac
Treat any mix of element/prop access as declaration in JS (#34649)
Fixes #34642 but, notably, doesn't actually make the assignment into a
working declaration. It just fixes the crash.
2019-10-22 11:28:28 -07:00
Anders Hejlsberg f84fd300b8
Merge pull request #34607 from microsoft/fix33490
Fix type inference regression
2019-10-21 12:50:38 -07:00
Anders Hejlsberg ff6626f869
Merge pull request #34597 from microsoft/optionalChainControlFlow
More optional chaining control flow analysis
2019-10-21 12:36:07 -07:00
Anders Hejlsberg 56520da6f0 Add regression tests 2019-10-20 18:00:08 -07:00
Anders Hejlsberg d218a31a7d Add tests 2019-10-19 10:51:59 -07:00
Nathan Shively-Sanders cdf1ab2dec
Bind @class in the right place -- bindWorker not bindChildrenWorker (#34575)
Also add an assert to make future mismatches fail in an obvious place
instead of in a while loop.
2019-10-18 14:13:14 -07:00
Nathan Shively-Sanders fa1884ed1b
Fix crash in expando assignment to alias (#34566)
* Fix crash in expando assignment to alias

This PR disallows expando assignments

Fixes #34493, but disallows the prototype assignment nonetheless.

* Revert mistaken changes
2019-10-18 13:31:44 -07: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 82f927f8dd
Fix stack overflow in circular assignment declaration (#34543)
* 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
2019-10-18 09:01:21 -07:00
Nathan Shively-Sanders f5dbcb78af
Resolve more jsdoc value references as types (#34515)
* Resolve more jsdoc value references as types

* add test
2019-10-17 11:21:34 -07:00
Klaus Meinhardt 45d0ef9441 factory: parenthesize for-of expression when necessary (#34229)
Fixes: #33856
2019-10-17 10:17:33 -07:00
Klaus Meinhardt 178417f431 factory: correctly parenthesize conditional head (#34227)
Fixes: #34109
2019-10-16 10:41:52 -07:00
Nathan Shively-Sanders 29f9493d87
Fix crash when exporting+aliasing globalThis inside declare global (#34408)
* global module:Fix crash when exporting+aliasing globalThis

* Fix another globalThis crash

find-all-refs assumed that an export inside a `declare x` was always an
ambient module, but it is not -- `declare global` does not allow
`export`, so find-all-refs shouldn't return any refs for this error case.
2019-10-15 14:05:39 -07:00
Anders Hejlsberg e0bd810176 Update tests 2019-10-05 18:58:51 -07:00
Anders Hejlsberg eeaa752833 Add tests 2019-10-05 18:33:00 -07:00
Anders Hejlsberg afe6f4c95c
Merge pull request #33821 from microsoft/fix33806
Reflect control flow effects of optional chains in equality checks
2019-10-05 17:48:53 -07:00
Anders Hejlsberg f88518187b Add tests 2019-10-05 13:08:31 -07:00
Anders Hejlsberg 42500d0606 Add tests 2019-10-04 16:12:44 -07:00
Anders Hejlsberg 2447bd775f Update tests 2019-10-04 16:01:09 -07:00
Ron Buckton a47ac63738
Fix for incorrect 'this' type for optional call (#33799) 2019-10-04 13:39:42 -07:00
Andrew Branch e2b4c12596
Detect unbindable exports before setting CommonJS module indicator (#33784)
* Detect unbindable exports before setting CommonJS module indicator

* Fix comment

* Fix unrelated lint?
2019-10-04 11:52:38 -05:00
Ron Buckton c774762723
Fix crash in transformations (#33768) 2019-10-02 16:13:32 -07:00
Wenlu Wang 7c50bccec2 nullish coalescing commit (#32883)
* migrate nullish coalescing commit

* add more test case

* add branch type check test

* add more tests

* fix nullish precedence

* update public api

* add rescan question question token to fix regression

* update public api baseline

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

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

* use not equal to null

* rename factory

* add grammar check

* fix more cases

* Fix handling of nullish coalescing oprator in expando objects.

* Fixed classifier to support ?? operator.

* update baseline

* accept baseline

* fix review

* update emitter and more testcase

* update control flow

* make linter happy

* update libs

* avoid unnecessary assert

* fix typooo

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

* Treat element access assignment as special assignment in JS

* Make declarations for bindable element access expressions

* Fix navigationBar crash

* Add multi-level test for JS

* Propagate element access expressions to more code paths

* Fix property access on `this`

* Add quick info test

* Uhhh I guess this is fine

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

* Add test for this property assignment

* Add test for and fix prototype property assignment

* Fix teeeest???

* Update APIs

* Fix element access declarations on `this`

* Fix go-to-definition

* Add declaration emit to tests

* Reconcile with late-bound symbol element access assignment

* Fix baselines

* Add JS declaration back to tests

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

* Revert accidental auto-format

* Use `isAccessExpression`

* Add underscore escaping member to test

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

* Add grammar error for invalid tagged template, more tests

* Prototype

* PR feedback

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

* Add additional signature help test, fix lint warnings

* Fix to insert text for completions

* Add initial control-flow analysis for optional chains

* PR Feedback and more tests

* Update to control flow

* Remove mangled smart quotes in comments

* Fix lint, PR feedback

* Updates to control flow

* Switch to FlowCondition for CFA of optional chains

* Fix ?. insertion for completions on type variables

* Accept API baseline change

* Clean up types

* improve control-flow debug output

* Revert Debug.formatControlFlowGraph helper
2019-09-30 12:33:28 -07:00
Anders Hejlsberg 7ce793c5b8
Merge pull request #33678 from microsoft/fix33617
Property handle recursive type references in type inference
2019-09-30 11:15:27 -07:00
Wesley Wigham 7f3c03d441
Implement declaration emit for accessors in the js declaration emitter (#33649)
* Implement declaration emit for accessors in the js declaration emitter

* Use `or`
2019-09-30 11:09:35 -07:00
Anders Hejlsberg ff5d38a94b
Merge pull request #33622 from microsoft/fix33580
Error when assertion function calls aren't CFA'd
2019-09-30 10:57:26 -07:00
Anders Hejlsberg 46bddedb4b Add regression tests 2019-09-30 09:28:19 -07:00
Anders Hejlsberg 34f6e681c4 Update tests 2019-09-27 15:23:49 -07:00
Wesley Wigham 293816875c
Support some late-bound special property assignments (#33220)
* Support some late-bound special property assignments

* Integrate PR feedback

* PR feedback

* Enable declaration on core tests

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

* Add test showing current nav bar behavior (specifically the lack thereof)
2019-09-27 13:54:50 -07:00
Wesley Wigham 8d7fd2e691
Respect //@ts-nocheck in TS files (#33383) 2019-09-27 12:06:05 -07:00
Andrii Dieiev a34fdb203e Better template literals support in checker (#32064)
* Support template literals in enum declarations

* Support template literals in const enum access

* Support template literals in swith with typeof narrowing

* Support template literals in element access discriminant

* Support template literals in ambient module declaration

* Unify symbols for template literals in computed properties

* Unify expression position checks for template literals

* Support template literals in rename and find all references

* Mark computed properties with template literals as write access

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

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

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

* Tests & fixes for computed names

* Add test with current @enum tag behavior

* fix declaration emit for jsdoc @enum tags

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

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

* Integrate feedback from PR

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

* Only make one merged getCommonJsExportEquals symbol for a symbol

* Support preserving type reference directives in js declarations

* Skip declare mdoifiers for namespace members in ambient contexts

* FAKE ALIASES AND NAMESPACES EVERYWHERE

* Dont do namespace sugar when type members contain keyword names

* Fix json source file export modifier under new output

* Such clean nested aliasing, very wow

* Fix lint

* Add visibility errors, reuse type nodes where possible

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

* Better support for module.exports = class expression

* Fix discovered crash bug

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

* Add missing semicolon

* Support @enum tag post-merge

* preserve comments on signatures and declarations where possible

* Basic support for js classy functions

* Add example we should do better with

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

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

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

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

* Fix organization nits from PR comments

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

* Merge export declarations with identical specifiers

* Remove completed TODO comment

* Split lint

* Remove now-unused function

* PR feedback

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

* Update project references tests again

* Merge and update project references tests

* Rename case

* Update test to include declaration output

* Remove yet another project refernces redirect extension check

* Update comment

* Add additional import ref to test

* Add shorthand prop to test

* Fix comment text

* Extract var to temp

* Simplify function and add whitespace

* Update project refs test to use incremental edit entry

* Stylistic refactors in the symbol serializer

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

* Use x instead of index
2019-09-26 14:27:16 -07:00
Anders Hejlsberg 894cc63be1 Add tests 2019-09-26 13:51:32 -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
Anders Hejlsberg 250d5a8229
Merge pull request #33050 from microsoft/recursiveTypeReferences
Recursive type references
2019-09-25 13:16:39 -07:00
Anders Hejlsberg cefd1e4251 Add regression test 2019-09-25 09:34:24 -07:00
Anders Hejlsberg 5962a5c08e Merge branch 'master' into recursiveTypeReferences
# Conflicts:
#	src/compiler/checker.ts
#	src/compiler/types.ts
2019-09-24 07:29:05 -07:00
Anders Hejlsberg e3d23cc40e Add tests 2019-09-24 06:55:38 -07:00
Anders Hejlsberg bf992a57f6
Merge pull request #32695 from microsoft/assertionsInControlFlow
Assertions in control flow analysis
2019-09-23 16:57:56 -07:00
Wesley Wigham 367b82055c
Hoist and distribute type parameter constraints over type parameters … (#33453)
* Hoist and distribute type parameter constraints over type parameters when comparing against union targets when fetching union constraints

* Fix PR nits
2019-09-23 16:52:03 -07:00
Anders Hejlsberg c3dcc37c79 Merge branch 'master' into assertionsInControlFlow
# Conflicts:
#	src/compiler/checker.ts
2019-09-20 17:23:27 -07:00
Anders Hejlsberg 21b5418cef Add tests 2019-09-20 17:17:39 -07:00
Wesley Wigham 5e06bea481
getConstraintDeclaration gets the first declaration with a constraint… (#33426)
* getConstraintDeclaration gets the first declaration with a constraint, rather than just the first declaration

* Add type annotation

* Update comment
2019-09-18 13:56:24 -07:00
Jack Williams 1c20aa0b1a Narrow unknown under inequality when assumed false (#33488) 2019-09-18 10:54:42 -07:00
Ron Buckton 344dba8809
Fix incorrect parameter types for AsyncIterator next/return (#33354) 2019-09-17 21:02:12 -07:00
Josh Goldberg 49be51dcf3 Added more helpful syntax error for enum member commas
Switches the error message emitted by the parser to the more specific _"An enum member name must be followed by a ',' or '='."_ when the expected comma doesn't follow the member.
2019-09-09 22:11:56 -04:00
Nathan Shively-Sanders b542bdfbe4
Bind typedef/enum on all assignment decl kinds (#33240)
This fixes a crash on exports, but the code now handles all kinds
returned from getAssignmentDeclarationPropertyAccessKind.
2019-09-04 13:11:03 -07:00
Ron Buckton 3b96729e01
Fix visitLexicalEnvironment to properly merge hoisted declarations (#33219) 2019-09-03 15:29:41 -07:00
Nathan Shively-Sanders 4bddf55328
Fix prototype property type lookup (#33034)
* Fix constructor function type reference lookup

I knew I missed some code in the constructor-functions-as-classes PR.
This simplifies the type reference resolution code as well.

* Simplify and document js alias type resolution
2019-08-22 12:51:15 -07:00
Nathan Shively-Sanders 3c42760765
Cache JS inferred class type symbol (#33010)
* Cache JS inferred class type symbol

Note that many sources merge into a single target, so the *source*
[links] is the one that caches the merged target.

The reason this is a problem is not that many sources merge into a
single target, but that both getTypeOfSymbol and getDeclaredTypeOfSymbol
end up calling mergeJSSymbols with the same [source,target] pair. The
merge should not happen twice.

* Remove more verbose debug assertion message

* Fix isJSConstructor check + update baselines

* inferClassSymbol cache now track multiple targets
2019-08-21 15:36:35 -07:00
Nathan Shively-Sanders 6ca9d04b60
Constructor functions as classes (#32944)
* Initial implementation

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

* Append constructor function construct sigs

Instead of overwriting them

* Grab bag of improvements.

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

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

* Prototype assignments work now

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

Many fewer failing tests now.

* Mark prototype-property assignments as Class

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

* Simplify getJSClassType, remove calls to its guts

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

* isJSDocConstructor doesn't need to check prototype anymore

Because all the properties are merged during getDeclaredTypeOfSymbol.

* outer type parameter lookup follow prototype assignment

* this-type and -expression support in ctor funcs

Pretty cool!

* Fix remaining tests

* Fix minor lint

* Delete now-unused code

* Add class flag to nested class declarations

Also remove old TODOs
2019-08-19 14:12:53 -07:00
Collins Abitekaniza 0341c2fe75 add baseline for unknown type spread 2019-08-19 16:32:09 +03:00
Brendan Kenny f45add0a7d checkJs: require JSDoc type argument for Array, Object, and Promise in noImplicitAny (#32829)
* Require type argument for JSDoc Array, Object, and Promise in noImplicitAny

* add jsdoc Array/Object/Promise noImplicitAny tests
2019-08-16 12:41:09 -07:00
Anders Hejlsberg 489abcacd4
Merge pull request #32919 from microsoft/fix32752
Stricter criteria for eliminating types in unions during inference
2019-08-16 10:55:48 -07:00
Anders Hejlsberg c816cf2562 Add additional test 2019-08-16 07:45:02 -07:00
Orta 6cd8bcd6c9
Merge pull request #31185 from collin5/b30851
Restrict spreading for Instantiable Type with non object constraint
2019-08-15 13:50:01 -07:00
Anders Hejlsberg f929a25407 Add regression test 2019-08-15 10:02:32 -07:00
Wesley Wigham 4ab85bbf35
Add error message for keywords with escapes in them (#32718)
* Add error message for keywords with escapes in them

* Move check into parser during advance to next token to utilize context for contextual keywords

* git add .

* Add tests for extended escapes

* Better error courtesy of @DanielRossenwaser

* Add test of browser-inconsistent case and alter condition to match spec

* Merge adjacent conditions

* Use seperate functions for checking keywords vs not

* Use flags to track unicode escape presence

* Adjust error text
2019-08-12 16:00:38 -07:00
Ron Buckton bf054ae796
Add support for import.meta in System modules (#32797) 2019-08-12 13:00:58 -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
Nathan Shively-Sanders 85b8d27ea3
Remove error on invalid jsdoc tokens (#32769)
* Remove error on invalid jsdoc tokens

In JSDoc:

1. In the scanner, don't issue an error, even for invalid identifiers.
2. In the binder, don't issue an error for reserved (but otherwise valid)
identifiers.

/**
 * Example of 1: "\"
 * Example of 2: @private
 */

* Update baselines

* Add invalid unicode escape test for JSDoc

* Add quotes around invalid unicode escape

* Add another unicode escape JSDoc test
2019-08-09 12:53:15 -07:00
Wesley Wigham f333684179
Fix unicode escapes in jsx identifiers and extended unicode characters in jsdoc (#32716)
* Fix unicode escapes in jsx identifiers and extended unicode characters in jsdoc

* Support unicode escapes in JSDoc

* Add tests for extended escapes
2019-08-06 15:14:32 -07:00
Andrew Branch 73bef22f0b
A merged interface with an inherited member should satisfy an abstract base class member (#32539)
* A merged interface with an inherited member should satisfy an abstract base class member

* Tighten up comments and names
2019-08-01 09:34:11 -07:00
Anders Hejlsberg 4cc6618fc2
Merge pull request #32558 from microsoft/fix32247
Infer between closely matching types in unions and intersections
2019-07-29 11:34:14 -07:00
Andrew Branch 3d09010dc8
Intersect 'this' types in union signatures (#32538)
* Intersect this types in union signatures

* Actually update baselines
2019-07-26 14:56:03 -07:00
Anders Hejlsberg ec38799e2a Add more tests 2019-07-26 13:17:00 -07:00
Anders Hejlsberg b9d27c0f2c Add regression tests 2019-07-25 11:52:08 -07:00
Nathan Shively-Sanders 772bee5e84
Property assignment uses parent type annotation (#32553)
* Property assignment uses parent type annotation

First draft, will write full explanation later.

Also makes sure that jsdoc is ignored in TS. It was not before.

* Update baselines
2019-07-25 10:23:03 -07:00
Anders Hejlsberg 6b29060111 Merge branch 'master' into fix32434 2019-07-20 12:09:03 -07:00
Anders Hejlsberg d96d16e10b Add additional test 2019-07-20 10:01:59 -07:00
Anders Hejlsberg ae1add7210 Update tests 2019-07-17 15:02:20 -07:00
Anders Hejlsberg 7d4259ba9f Update tests 2019-07-17 14:57:26 -07:00
Ron Buckton 049618f7da
Get contextual type of yield from contextual signature of containing function (#32433)
* Get contextual type of yield from contextual signature of containing function

* Add missing baseline
2019-07-16 17:16:21 -07:00
Nathan Shively-Sanders 1de76cd605
Control flow for element access expressions (#31478)
* Control flow for element access expressions

Draft version, just want to see how performance is

* Add baselines

* Fix cast lint

* Cleanup to share code path

* Fix errant diffs
2019-07-16 10:10:58 -07:00
Ron Buckton 17762c480d
Fall back to (Async)IterableIterator if (Async)Generator not found (#32303) 2019-07-15 13:41:17 -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
Andrew Branch 8516127a05
Fix regression of generic T assignability to Partial<T> (#32354) 2019-07-12 07:57:55 -07:00
Anders Hejlsberg de2fb9584e Add regression test 2019-07-04 16:27:03 -10:00
Ron Buckton e8bf9584aa
Improve type checking and inference for Generators and Async Generators (#30790)
* Improve typing for Generators and Async Generators

* Add TReturn and TNext to Iterator, IterableIterator, etc.

* Update ts internal Iterator to be assignable from global Iterator

* Make 'done' optional in IteratorYieldResult

* Revert Iterable and IterableIterator to simpler versions plus other fixes

* Add additional inference tests

* Added additional tests

* PR cleanup and minor async iteration type fix

* Updated diagnostics message and added non-strict tests

* Fix expected arity of Iterator/AsyncIterator
2019-07-03 21:55:59 -07:00
Andrew Branch 16bbb4d002
Merge pull request #32077 from andrewbranch/bug/31114
Fix incorrect noImplicitAny error on contextual union function signature
2019-07-03 10:10:10 -07:00
Anders Hejlsberg 340f81035f
Merge pull request #32178 from microsoft/improveTupleDestructuring
Simplify tuple destructuring logic
2019-07-02 17:25:12 -07:00
Andrew Branch 327bc3cb67
Merge pull request #32071 from andrewbranch/bug/31070
Allow assignability of non-empty object to generic mapped type
2019-07-01 13:18:44 -07:00
Andrew Branch 23f1d5ccb7
Merge pull request #32117 from andrewbranch/bug/31460
Fix declaration emit for negative number properties, allow negative numbers as computed type property names
2019-07-01 10:56:56 -07:00
Anders Hejlsberg f89165d072
Merge pull request #32049 from microsoft/noDuplicateIntersectionSignatures
Remove duplicate signatures in intersections
2019-06-30 19:38:37 -07:00
Anders Hejlsberg 5ad3d1bf08 Add more tests 2019-06-30 08:18:01 -10:00
Nathan Shively-Sanders 8454ef114d JSDoc:Treat tokens between backticks as comments
even `@`, which would otherwise start a new tag.
2019-06-26 16:04:46 -07:00
Klaus Meinhardt 392d775095 allow const-assertion on aliased enum symbol (#32110)
Fixes: #32087
2019-06-26 14:42:06 -07:00
Andrew Branch 5ff3cda078
Add some negative test cases and accept baselines 2019-06-26 14:01:50 -07:00
Andrew Branch 17f6f77de5
Fix declaration emit for negative number property declarations 2019-06-26 11:49:45 -07:00
Andrew Branch 252840ad40
Fix incorrect noImplicitAny error on contextual union function signature 2019-06-24 17:37:14 -07:00
Andrew Branch 7bbd299226
Look at properties of constraint-instantiated optional mapped types when deciding assignability 2019-06-24 15:19:43 -07:00
Anders Hejlsberg 076d9ad2ab Add regression test 2019-06-23 09:19:56 -10:00
Anders Hejlsberg 9223f39f53 Add regression test 2019-06-21 18:07:15 -10:00
Anders Hejlsberg 6def72b3a4
Merge pull request #31950 from microsoft/unionObjectAndArrayLiterals
Union inferences from object and array literals
2019-06-20 09:36:20 -07:00
Anders Hejlsberg 51712fb1ae Add tests 2019-06-17 16:18:13 -10: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
Anders Hejlsberg 98bbb22bc4 Add tests 2019-06-09 10:18:36 -07:00
Anders Hejlsberg 9cc9fb9bd7 Update tests 2019-06-09 08:00:01 -07:00
Anders Hejlsberg 9d2a2c9634 Add tests 2019-06-06 13:33:36 -07:00
Anders Hejlsberg 59dc85797e Add regression test 2019-05-31 11:04:02 -07:00
Wesley Wigham e70f2af25d
Defer union or intersection property type normalization (#31486)
* Defer union or intersection property type normalization

* Accept moved span
2019-05-28 10:51:47 -07:00
Andrew Branch a06ab8532c
Merge pull request #31560 from andrewbranch/bug/31485
Fix crash when creating a union signature from signatures that do and don’t have `this` types
2019-05-24 10:30:47 -07:00
Ron Buckton dfd28d2751
Fix handling of empty 'types', 'typings', etc. fields in package.json (#31539) 2019-05-23 17:19:32 -07:00
Andrew Branch a2b40292fe
Merge pull request #31542 from andrewbranch/bug/31481
Error when writing to rest element range of readonly tuple
2019-05-23 13:38:09 -07:00
Anders Hejlsberg e6013335b9
Merge pull request #31537 from microsoft/fixIndexedAccessConstraint
Fix indexed access constraint
2019-05-22 18:35:15 -07:00
Andrew Branch 300cbef071
Don’t crash when creating a union signature from signatures that do and don’t have this types 2019-05-22 17:42:05 -07:00
Andrew Branch 9f6791a5ab
Error when writing to readonly tuple in rest element range 2019-05-22 15:03:17 -07:00
Andrew Branch eecb6d9049
Add failing test 2019-05-22 13:39:05 -07:00
Ron Buckton 6a559e37ee
Fix crash when checking invalid object rest (#31530) 2019-05-22 11:20:57 -07:00
Ron Buckton c3055e585d
Fix compiler crash with object rest in catch binding (#31522) 2019-05-22 11:20:07 -07:00
Ron Buckton b3dc32fec7
Reset error record in downlevel for-of (#31519) 2019-05-22 11:18:07 -07:00
Ron Buckton 7611c5b931
Fix for computed properties in instance initializers (#31517) 2019-05-22 11:17:54 -07:00
Nathan Shively-Sanders b36c8a0690
Make anyArray.filter(Boolean) return any[], not unknown[] (#31515)
* Add this-parameter workaround to Array.filter

Allows anys.filter(Boolean) to once again return any[], not unknown[].

* Add any constraint to Boolean factory function

I want to test how well this works.

* Remove Boolean factory type guard

* Remove typeGuardBoolean test
2019-05-22 09:45:41 -07:00
Anders Hejlsberg 2fd4aaee92 Add regression test 2019-05-22 06:54:16 -07:00
Anders Hejlsberg 907664c31c
Merge pull request #31454 from microsoft/fixThisTypeIndexSignature
Permit assignment through index signature of 'this' type
2019-05-20 07:02:52 -07:00
Anders Hejlsberg c6a670d26c Add regression test 2019-05-17 15:59:01 -07:00
Nathan Shively-Sanders eeba30afc8
Fix infinite loop: module.exports alias detection (#31436)
* Fix infinite loop: module.exports alias detection

Previously, module.exports alias detection in the binder could enter an
infinite recursion. Now it does not.

Notably, there are *two* safeguards: a counter limiter that I set at
100, and an already-seen set. I actually prefer the counter limiter code
because it's foolproof and uses less memory. But it takes 100
iterations to escape from loops.

* fix space lint

* Remove already-seen map
2019-05-17 12:50:39 -07:00
Anders Hejlsberg ee59cee381 Add regression test 2019-05-10 09:56:17 -07:00
Collins Abitekaniza 2bb2f9ff68 add baseline tests for spreading instantiable type 2019-05-03 05:31:28 +03:00
Andrew Branch 56b19c9bf0
Merge pull request #31119 from andrewbranch/bug/31020
Emit grammar error on quoted constructors and class fields named “constructor”
2019-05-01 10:42:16 -10:00
Andrew Branch 90d3acf6c7
Merge pull request #31078 from andrewbranch/bug/30752
Fix symbol merging of augmentations to pattern ambient modules
2019-04-30 06:18:23 -10:00
Forbes Lindesay 3ce3cde493 Allow Boolean() to be used to perform a null check (#29955)
* Allow Boolean() to be used to perform a null check

* Add missing test case output
2019-04-30 08:09:31 -07:00
Anders Hejlsberg be409fad84
Merge pull request #31137 from Microsoft/fixConditionalInference
Fix conditional type inference involving any or unknown
2019-04-30 06:26:02 -07:00
Anders Hejlsberg a539887893
Merge pull request #31150 from Microsoft/fixReadonlyIndexedAccess
Fix readonly indexed access used in indexed access type
2019-04-29 16:59:13 -07:00
Ron Buckton 2d8527f3f0
Merge pull request #30779 from Microsoft/relateDiscriminants
Relate source types covered by a target discriminated union
2019-04-29 16:58:27 -07:00
Ron Buckton 26fd6dafa6 Relate a source type that is sufficiently covered by a target discriminated union 2019-04-29 15:46:37 -07:00
Anders Hejlsberg bbce336268 Add additional tests 2019-04-28 14:12:00 -07:00
Anders Hejlsberg 3050c62251 Add regression test 2019-04-28 13:58:58 -07:00
Ron Buckton 57a8ee1507 Fix binder performance regression 2019-04-27 16:47:27 -07:00
Anders Hejlsberg 078375765b Add regression test 2019-04-27 09:56:11 -07:00
Wenlu Wang 454b4280b1 check more case for empty binding patten (#25263)
* check more case for empty binding patten

* refactor binding pattern checking  getWidenedType

* fix spelling

* fix merge and rebase
2019-04-26 14:00:04 -07:00
Clay Miller d934401265 Change the type of 'uriComponent' (passed to 'encodeURIComponent') from 'string' to 'string | number | boolean'. Fixes #18159 (#31103)
- According to the ECMAScript 5.1 spec (§15.1.3.4), 'encodeURIComponent' invokes the abstract operation 'ToString': https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3.4
- In the spec (§9.8), 'ToString' accepts an 'Undefined', 'Null', 'Boolean', 'Number', 'String' or 'Object' argument: https://www.ecma-international.org/ecma-262/5.1/#sec-9.8
- TypeScript’s 'StringConstructor' accepts an argument with type 'any': b0100100a1/lib/lib.es5.d.ts (L518)
2019-04-26 13:07:14 -07:00
Andrew Branch e81fa2198d
Emit error on class fields named "constructor" 2019-04-25 17:30:41 -07:00
Anders Hejlsberg 95413f0a24
Merge pull request #31000 from Microsoft/ignoreStringIndexSignaturesOnly
Ignore string (but keep numeric) index signatures from constraints
2019-04-25 17:01:46 -07:00
Andrew Branch c5e6913ede
Add grammar error on quoted constructors for TS 3.5 2019-04-25 15:44:23 -07:00
Klaus Meinhardt b45df892a8 emit error on destructuring of rest property (#29609)
Fixes: #26005
2019-04-25 13:33:49 -07:00
Andrew Branch 72f30a8308
Add test for quoted constructors 2019-04-25 11:35:10 -07:00
Wenlu Wang 583edce6b0 fix compiler crash (#25925) 2019-04-25 10:51:36 -07:00
Andrew Branch d69f9f3328
Add bad test case 2019-04-24 08:44:24 -07:00
Andrew Branch f2ec02b971
Add additional test to ensure merging more than augmentations still works 2019-04-23 13:26:00 -07:00
Andrew Branch 7409a04010
Fix merging module augmentations to pattern ambient modules 2019-04-23 12:06:56 -07:00
Daniel Rosenwasser 2eea21636b
Merge pull request #29242 from Kingwl/attach_property_to_default_export
add transformer for emit add property to default export
2019-04-18 23:30:48 -04:00
Andrew Branch b6a0988052
Merge pull request #30776 from andrewbranch/feature/10178
Add flag to allow access to UMD globals from modules
2019-04-18 18:05:44 -07:00
Anders Hejlsberg 3a89fead70 Merge branch 'master' into ignoreStringIndexSignaturesOnly
# Conflicts:
#	tests/baselines/reference/keyofAndIndexedAccess2.errors.txt
#	tests/baselines/reference/keyofAndIndexedAccess2.js
#	tests/baselines/reference/keyofAndIndexedAccess2.symbols
#	tests/baselines/reference/keyofAndIndexedAccess2.types
#	tests/cases/conformance/types/keyof/keyofAndIndexedAccess2.ts
2019-04-18 11:31:06 -07:00
Anders Hejlsberg 4d0244c798 Add regression test 2019-04-17 15:05:57 -07:00
Anders Hejlsberg 07d259593a Add regression test 2019-04-17 12:37:01 -07:00
Wesley Wigham d405662eb6
Explicitly encode keyof behaviors for never and unknown into getIndexType (#30753)
* Explicitly encode keyof behaviors for never and unknown into getIndexType

* Merge similar cases
2019-04-15 17:52:13 -07:00
Anders Hejlsberg 2c951b3ca9 Add regression test 2019-04-13 08:24:27 -10:00
Anders Hejlsberg 6282645e3c
Merge pull request #30857 from Microsoft/fixInferenceToIntersection
Fix inference to intersections
2019-04-12 07:34:40 -10:00
Anders Hejlsberg 6cd229b4b9
Merge pull request #30769 from Microsoft/saferIndexedAccessTypes
Improve soundness of indexed access types
2019-04-12 07:33:50 -10:00
Anders Hejlsberg a764729b38 Add tests 2019-04-10 17:42:08 -10:00
Anders Hejlsberg 68eb7b9fe2 Add test 2019-04-09 15:29:51 -10:00
Nathan Shively-Sanders 90b304aa5e
Merge pull request #30786 from Microsoft/always-check-class-extends
Always check extends clause of classes
2019-04-08 10:25:05 -07:00
Andrew Branch 6d1d680c0e
Add test 2019-04-08 09:46:47 -07:00
Andrew Branch bafa4c90c1
Merge pull request #30758 from andrewbranch/bug/30647
Fix crash when checking function call
2019-04-08 09:22:39 -07:00
Anders Hejlsberg 2b6e7304c1 Merge branch 'master' into tweakUnionTypeInference 2019-04-06 08:12:45 -10:00
Anders Hejlsberg cd646dab7e Add tests 2019-04-06 07:59:39 -10:00
Anders Hejlsberg 294580287d Merge branch 'master' into saferIndexedAccessTypes 2019-04-05 16:23:48 -10:00
Nathan Shively-Sanders dabf2a6af2 Always check extends clause of classes
Even if (1) @extends is provided and (2) we're not producing
diagnostics. That's because we need to know whether the extends clause
references an imported alias.
2019-04-05 16:37:27 -07:00
Anders Hejlsberg 739acee1c9 Add tests 2019-04-04 16:30:26 -07:00
Wesley Wigham 16450a027a
Change the default type parameter constraints and defaults to unknown from {} (#30637)
* Change the default type parameter constraint and default to unknown from {}

* Relax unknown checking outside of strictNullChecks a bit

* Increase strictness on index signatures with type `unknown` so inference doesnt change surprisingly

* Remove redundant switch
2019-04-04 12:25:15 -07:00
Andrew Branch 8576018af1
Add failing test for function calls that have at least one non-spread argument, a spread argument, and overall potentially too few arguments 2019-04-04 11:47:25 -07:00
Ron Buckton f04a40dd49 Treat hoisted temp variables as a custom prologue 2019-04-02 17:35:26 -07:00
Andrew Branch 3f3444be80
Merge pull request #30699 from andrewbranch/bug/30635
Fix ternaries where "true" is a parenthesized variable and "false" is a function expression
2019-04-02 14:03:11 -07:00
Andrew Branch f383c3c42d
Add test for parenthesized variable and function keyword within ternary 2019-04-01 14:11:30 -07:00
Andrew Branch 9a3149b967
Add failing tests for destructuring void 2019-04-01 13:33:41 -07:00
Nathan Shively-Sanders 32054f1c31
Forbid accessing block-scoped variables on globalThis (#30510)
* Forbid accessing const & let on globalThis

It's just an error; you still get the type of the property.

* Disallow access of blockscoped vars on globalThis

Also change Array, Function, String, et al from `const` to `var` so that
they remain accessible via `globalThis.String`.

* Update baselines after lib.d.ts change

Note especially the change in redefineArray, which is now allowed as
long as you provide a type that is assignable to ArrayConstructor.

* Remove blockscoped vars from typeof globalThis

Unlike forbidding them, this removes the properties entirely.

Unfortunately, this means that accessing these properties is only an
error with noImplicitAny, and that error is quite confusing.

Let's discuss our options. I see 3:

1. Forbid access of block-scoped vars as properties (in all flag
settings), but leave them on the type. Simple to implement.
2. Remove block-scoped vars from the globalThis type. Has the bad
error/flag behaviour described above, but simple to implement.
3. Remove block-scoped vars from the globalThis type. Also, forbid
accessing them by executing another resolveName lookup for failed
property accesses on globalThisSymbol. If the second lookup returns a
blockscoped var, issue an error instead of falling back to the index
signature. This seems too complex to me.

* Update baselines

* Better error for block-scoped usage on globalThis

So that value-space references have as clear an error as type-space
references.

* Update fourslash tests

* Fix semi-colon lint

* Don't copy so much when filtering blockscoped vars
2019-03-25 14:07:48 -07:00
王文璐 35ded510bb Merge branch 'master' into attach_property_to_default_export 2019-03-22 17:40:37 +08:00
Ron Buckton 2932421370
Merge pull request #30495 from Microsoft/fix29427
Adjust offset to account for 'this' parameter when emitting parameter decorators
2019-03-20 12:56:50 -07:00
Ron Buckton 07bec2893f Adjust offset to account for 'this' parameter when emitting parameter decorators 2019-03-19 11:46:18 -07:00
Ron Buckton e19c7f1a45 Prevent substitution of 'super' in async super helper 2019-03-19 11:35:18 -07:00
Ron Buckton 4e54f30fb4 Fix _superIndex emit when super access captured in async arrow 2019-03-19 10:20:08 -07:00
Collins Abitekaniza 7b55d1846b Giving too many arguments should error on the first argument that exceeds arity (#27982)
* span on first arg that exceeds arity

* refactor baseline

* handle cases for spread arguments

* refactor + add coverage for tuple spread cases

* create diagnostic on NodeArray of exceeding args

* test function overloading
2019-03-12 15:57:12 -07:00
Wenlu Wang d2476759e2 add related error span for default exports (#25396)
* add related error span for default exports

* accept baseline

* stash

* accept baseline and fix lint

* update testcase

* Add missing semicolon
2019-03-12 13:15:14 -07:00
Wenlu Wang bd27296ba6 improve stripInternal with inline comments (#23611)
* improve stripInternal with inline comments

* fix lint

* stash

* simptify StripInternal

* fix internal type declaration

* fix internal type declaration again

* accept baseline

* refactor inline

* simply prev check

* remove getTrailingCommentRangesOfNode

* Merge implementation with new isInternalDeclaration method, accept lkg-based baseline
2019-03-12 13:14:47 -07:00
Jack Williams 5bef1aa13c Add regressions for conditional types that affect parameter variance (#30146) 2019-02-28 16:14:16 -08:00
Anders Hejlsberg 7f5052bf7b
Merge pull request #30114 from Microsoft/contextualGenericRestParameter
Improve contextual typing by generic rest parameters
2019-02-28 11:00:12 -10:00
Anders Hejlsberg 237c33b444
Merge pull request #30109 from Microsoft/circularConstraintErrors
Consistently error on circular constraints
2019-02-28 10:57:01 -10:00
Nathan Shively-Sanders be2db9db12
Add globalThis (#29332)
* Restore original code from bind-toplevel-this

With one or two additional comments

* Working in JS, but the symbol is not right.

Still need to

1. Make it work in Typescript.
2. Add test (and make them work) for the other uses of GlobalThis:
window, globalThis, etc.

* Check in TS also; update some tests

Lots of tests still fail, but all but 1 change so far has been correct.

* Update baselines

A couple of tests still fail and need to be fixed.

* Handle type references to globalThis

The type reference must be `typeof globalThis`. Just `globalThis` will
be treated as a value reference in type position -- an error.

* Restore former behaviour of implicitThis errors

I left the noImplicitThis rule for captured use of global this in an
arrow function, even though technically it isn't `any` any more --
it's typeof globalThis.  However, you should still use some other method
to access globals inside an arrow, because captured-global-this is super
confusing there.

* Test values with type globalThis

I ran into a problem with intersecting `Window & typeof globalThis`:

1. This adds a new index signature to Window, which is probably not
desired. In fact, with noImplicitAny, it's not desired on globalThis
either I think.
2. Adding this type requires editing TSJS-lib-generator, not this repo.

So I added the test cases and will probably update them later, when
those two problems are fixed.

* Add esnext declaration for globalThis

* Switch to symbol-based approach

I decided I didn't like the import-type-based approach.

Update baselines to reflect the difference.

* Do not suggest globals for completions at toplevel

* Add tests of element and property access

* Look up globalThis using normal resolution

globalThis is no longer constructed lazily. Its synthetic Identifier
node is also now more realistic.

* Update fourslash tests

* Add missed fourslash test update

* Remove esnext.globalthis.d.ts too

* Add chained globalThis self-lookup test

* Attempt at making globalThis readonly

In progress, had to interrupt for other work.

* Add/update tests

* Addres PR comments:

1. Add parameter to tryGetThisTypeAt to exclude globalThis.
2. Use combined Module flag instead combining them in-place.
3. SymbolDisplay doesn't print 'module globalThis' for this expressions
anymore.
2019-02-27 14:14:34 -08:00