From dc78c4f4de381e3afbb0066b3ee42afa0812bdce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Sun, 8 Apr 2018 16:14:29 +0800 Subject: [PATCH 001/146] improve parser and error message if definite assignment assertions in object short hand --- src/compiler/checker.ts | 15 ++++++++++-- src/compiler/parser.ts | 6 ++++- src/compiler/types.ts | 2 ++ .../reference/api/tsserverlibrary.d.ts | 2 ++ tests/baselines/reference/api/typescript.d.ts | 2 ++ ...ntAssertionsWithObjectShortHand.errors.txt | 15 ++++++++++++ ...AssignmentAssertionsWithObjectShortHand.js | 23 +++++++++++++++++++ ...nmentAssertionsWithObjectShortHand.symbols | 14 +++++++++++ ...ignmentAssertionsWithObjectShortHand.types | 17 ++++++++++++++ ...AssignmentAssertionsWithObjectShortHand.ts | 9 ++++++++ 10 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.errors.txt create mode 100644 tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.js create mode 100644 tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.symbols create mode 100644 tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.types create mode 100644 tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1e6a16aa75f..45eed69974f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -26871,12 +26871,18 @@ namespace ts { } } - function checkGrammarForInvalidQuestionMark(questionToken: Node, message: DiagnosticMessage): boolean { + function checkGrammarForInvalidQuestionMark(questionToken: QuestionToken, message: DiagnosticMessage): boolean { if (questionToken) { return grammarErrorOnNode(questionToken, message); } } + function checkGrammarForInvalidExclamationToken(exclamationToken: ExclamationToken, message: DiagnosticMessage): boolean { + if (exclamationToken) { + return grammarErrorOnNode(exclamationToken, message); + } + } + function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) { const enum Flags { Property = 1, @@ -26921,8 +26927,10 @@ namespace ts { // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields let currentKind: Flags; switch (prop.kind) { - case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: + checkGrammarForInvalidExclamationToken(prop.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context); + /* tslint:disable:no-switch-case-fall-through */ + case SyntaxKind.PropertyAssignment: // Grammar checking for computedPropertyName and shorthandPropertyAssignment checkGrammarForInvalidQuestionMark(prop.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional); if (name.kind === SyntaxKind.NumericLiteral) { @@ -27162,6 +27170,9 @@ namespace ts { else if (checkGrammarForInvalidQuestionMark(node.questionToken, Diagnostics.An_object_member_cannot_be_declared_optional)) { return true; } + else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) { + return true; + } else if (node.body === undefined) { return grammarErrorAtPos(node, node.end - 1, ";".length, Diagnostics._0_expected, "{"); } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 3c118d943a2..dbc989e0c51 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -90,6 +90,7 @@ namespace ts { visitNodes(cbNode, cbNodes, node.modifiers) || visitNode(cbNode, (node).name) || visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).exclamationToken) || visitNode(cbNode, (node).equalsToken) || visitNode(cbNode, (node).objectAssignmentInitializer); case SyntaxKind.SpreadAssignment: @@ -160,6 +161,7 @@ namespace ts { visitNode(cbNode, (node).asteriskToken) || visitNode(cbNode, (node).name) || visitNode(cbNode, (node).questionToken) || + visitNode(cbNode, (node).exclamationToken) || visitNodes(cbNode, cbNodes, (node).typeParameters) || visitNodes(cbNode, cbNodes, (node).parameters) || visitNode(cbNode, (node).type) || @@ -4580,8 +4582,10 @@ namespace ts { const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); const tokenIsIdentifier = isIdentifier(); node.name = parsePropertyName(); - // Disallowing of optional property assignments happens in the grammar checker. + // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker. (node).questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + (node).exclamationToken = parseOptionalToken(SyntaxKind.ExclamationToken); + if (asteriskToken || token() === SyntaxKind.OpenParenToken || token() === SyntaxKind.LessThanToken) { return parseMethodDeclaration(node, asteriskToken); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4edfc29a2a1..085d2c95acf 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -912,6 +912,7 @@ namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; // used when ObjectLiteralExpression is used in ObjectAssignmentPattern // it is grammar error to appear in actual object initializer equalsToken?: Token; @@ -970,6 +971,7 @@ namespace ts { asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index aca4e956181..1ac5055e0c7 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -608,6 +608,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -644,6 +645,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index aa77372db45..4def1db34f8 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -608,6 +608,7 @@ declare namespace ts { kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; equalsToken?: Token; objectAssignmentInitializer?: Expression; } @@ -644,6 +645,7 @@ declare namespace ts { _functionLikeDeclarationBrand: any; asteriskToken?: AsteriskToken; questionToken?: QuestionToken; + exclamationToken?: ExclamationToken; body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; diff --git a/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.errors.txt b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.errors.txt new file mode 100644 index 00000000000..30a1cc39aeb --- /dev/null +++ b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts(2,16): error TS1255: A definite assignment assertion '!' is not permitted in this context. +tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts(5,7): error TS1162: An object member cannot be declared optional. + + +==== tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts (2 errors) ==== + const a: string | undefined = 'ff'; + const foo = { a! } + ~ +!!! error TS1255: A definite assignment assertion '!' is not permitted in this context. + + const bar = { + a ? () { } + ~ +!!! error TS1162: An object member cannot be declared optional. + } \ No newline at end of file diff --git a/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.js b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.js new file mode 100644 index 00000000000..c3bfe922374 --- /dev/null +++ b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.js @@ -0,0 +1,23 @@ +//// [definiteAssignmentAssertionsWithObjectShortHand.ts] +const a: string | undefined = 'ff'; +const foo = { a! } + +const bar = { + a ? () { } +} + +//// [definiteAssignmentAssertionsWithObjectShortHand.js] +"use strict"; +var a = 'ff'; +var foo = { a: a }; +var bar = { + a: function () { } +}; + + +//// [definiteAssignmentAssertionsWithObjectShortHand.d.ts] +declare const a: string | undefined; +declare const foo: { + a: string; +}; +declare const bar: {}; diff --git a/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.symbols b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.symbols new file mode 100644 index 00000000000..7b8afc1d657 --- /dev/null +++ b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts === +const a: string | undefined = 'ff'; +>a : Symbol(a, Decl(definiteAssignmentAssertionsWithObjectShortHand.ts, 0, 5)) + +const foo = { a! } +>foo : Symbol(foo, Decl(definiteAssignmentAssertionsWithObjectShortHand.ts, 1, 5)) +>a : Symbol(a, Decl(definiteAssignmentAssertionsWithObjectShortHand.ts, 1, 13)) + +const bar = { +>bar : Symbol(bar, Decl(definiteAssignmentAssertionsWithObjectShortHand.ts, 3, 5)) + + a ? () { } +>a : Symbol(a, Decl(definiteAssignmentAssertionsWithObjectShortHand.ts, 3, 13)) +} diff --git a/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.types b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.types new file mode 100644 index 00000000000..73c3edfdaa5 --- /dev/null +++ b/tests/baselines/reference/definiteAssignmentAssertionsWithObjectShortHand.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts === +const a: string | undefined = 'ff'; +>a : string | undefined +>'ff' : "ff" + +const foo = { a! } +>foo : { a: string; } +>{ a! } : { a: string; } +>a : string + +const bar = { +>bar : {} +>{ a ? () { }} : {} + + a ? () { } +>a : (() => void) | undefined +} diff --git a/tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts b/tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts new file mode 100644 index 00000000000..56c22310433 --- /dev/null +++ b/tests/cases/conformance/controlFlow/definiteAssignmentAssertionsWithObjectShortHand.ts @@ -0,0 +1,9 @@ +// @strict: true +// @declaration: true + +const a: string | undefined = 'ff'; +const foo = { a! } + +const bar = { + a ? () { } +} \ No newline at end of file From 0d79831ead51bda2fd38dd169e0bf04a0cdb4e72 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Tue, 13 Feb 2018 01:14:47 +0000 Subject: [PATCH 002/146] Add typeof-for-switch Initial draft that works for union types First draft of PR ready code with tests Revert changed line for testing Add exhaustiveness checking and move narrowByTypeOfWitnesses Try caching mechanism Comment out exhaustiveness checking to find perf regression Re-enable exhaustiveness checking for typeof switches Check if changes to narrowByTypeOfWitnesses fix perf alone. Improve switch narrowing: + Take into account repeated clauses in the switch. + Handle unions of constrained type parameters. Add more tests Comments Revert back to if-like behaviour Remove redundant checks and simplify exhaustiveness checks Change comment for narrowBySwitchOnTypeOf Reduce implied type with getAssignmentReducedType Remove any annotations --- src/compiler/binder.ts | 2 + src/compiler/checker.ts | 119 +++ .../reference/narrowingByTypeofInSwitch.js | 427 +++++++++++ .../narrowingByTypeofInSwitch.symbols | 542 ++++++++++++++ .../reference/narrowingByTypeofInSwitch.types | 695 ++++++++++++++++++ .../compiler/narrowingByTypeofInSwitch.ts | 190 +++++ 6 files changed, 1975 insertions(+) create mode 100644 tests/baselines/reference/narrowingByTypeofInSwitch.js create mode 100644 tests/baselines/reference/narrowingByTypeofInSwitch.symbols create mode 100644 tests/baselines/reference/narrowingByTypeofInSwitch.types create mode 100644 tests/cases/compiler/narrowingByTypeofInSwitch.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index e6e3364840d..555c13f1f61 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -737,6 +737,8 @@ namespace ts { return isNarrowingBinaryExpression(expr); case SyntaxKind.PrefixUnaryExpression: return (expr).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr).operand); + case SyntaxKind.TypeOfExpression: + return isNarrowingExpression((expr).expression); } return false; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f497ba82e47..ab2cc1f3b85 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12840,6 +12840,21 @@ namespace ts { return links.switchTypes; } + function getSwitchClauseTypeOfWitnesses(switchStatement: SwitchStatement): (string | undefined)[] { + const witnesses: (string | undefined)[] = []; + for (const clause of switchStatement.caseBlock.clauses) { + if (clause.kind === SyntaxKind.CaseClause) { + if (clause.expression.kind === SyntaxKind.StringLiteral) { + witnesses.push((clause.expression as StringLiteral).text); + continue; + } + return emptyArray; + } + witnesses.push(/*explicitDefaultStatement*/ undefined); + } + return witnesses; + } + function eachTypeContainedIn(source: Type, types: Type[]) { return source.flags & TypeFlags.Union ? !forEach((source).types, t => !contains(types, t)) : contains(types, source); } @@ -13253,6 +13268,9 @@ namespace ts { else if (isMatchingReferenceDiscriminant(expr, type)) { type = narrowTypeByDiscriminant(type, expr, t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); } + else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) { + type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); + } return createFlowType(type, isIncomplete(flowType)); } @@ -13549,6 +13567,57 @@ namespace ts { return caseType.flags & TypeFlags.Never ? defaultType : getUnionType([caseType, defaultType]); } + function narrowBySwitchOnTypeOf(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): Type { + const switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement); + if (!switchWitnesses.length) { + return type; + } + const clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause + const hasDefaultClause = clauseStart === clauseEnd || contains(clauseWitnesses, /*explicitDefaultStatement*/ undefined); + const switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + // The implied type is the raw type suggested by a + // value being caught in this clause. + // - If there is a default the implied type is not used. + // - Otherwise, take the union of the types in the + // clause. We narrow the union using facts to remove + // types that appear multiple types and are + // unreachable. + // Example: + // + // switch (typeof x) { + // case 'number': + // case 'string': break; + // default: break; + // case 'number': + // case 'boolean': break + // } + // + // The implied type of the first clause number | string. + // The implied type of the second clause is string (but this doesn't get used). + // The implied type of the third clause is boolean (number has already be caught). + if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { + let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); + if (impliedType.flags & TypeFlags.Union) { + impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOfType(type) || type); + } + if (!(impliedType.flags & TypeFlags.Never)) { + if (isTypeSubtypeOf(impliedType, type)) { + return impliedType; + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(impliedType, constraint)) { + return getIntersectionType([type, impliedType]); + } + } + } + } + return hasDefaultClause ? + filterType(type, t => (getTypeFacts(t) & switchFacts) === switchFacts) : + getTypeWithFacts(type, switchFacts); + } + function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { const left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { @@ -18944,10 +19013,60 @@ namespace ts { : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member); } + /** + * Collect the TypeFacts learned from a typeof switch with + * total clauses `witnesses`, and the active clause ranging + * from `start` to `end`. Parameter `hasDefault` denotes + * whether the active clause contains a default clause. + */ + function getFactsFromTypeofSwitch(start: number, end: number, witnesses: (string | undefined)[], hasDefault: boolean): TypeFacts { + let facts: TypeFacts = TypeFacts.None; + // When in the default we only collect inequality facts + // because default is 'in theory' a set of infinite + // equalities. + if (hasDefault) { + // Value is not equal to any types after the active clause. + for (let i = end; i < witnesses.length; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; + } + // Remove inequalities for types that appear in the + // active clause because they appear before other + // types collected so far. + for (let i = start; i < end; i++) { + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + } + // Add inequalities for types before the active clause unconditionally. + for (let i = 0; i < start; i++) { + facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; + } + } + // When in an active clause without default the set of + // equalities is finite. + else { + // Add equalities for all types in the active clause. + for (let i = start; i < end; i++) { + facts |= typeofEQFacts.get(witnesses[i]) || TypeFacts.TypeofEQHostObject; + } + // Remove equalities for types that appear before the + // active clause. + for (let i = 0; i < start; i++) { + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + } + } + return facts; + } + function isExhaustiveSwitchStatement(node: SwitchStatement): boolean { if (!node.possiblyExhaustive) { return false; } + if (node.expression.kind === SyntaxKind.TypeOfExpression) { + const operandType = getTypeOfExpression((node.expression as TypeOfExpression).expression); + // Type is not equal to every type in the switch. + const notEqualFacts = getFactsFromTypeofSwitch(0, 0, getSwitchClauseTypeOfWitnesses(node), /*hasDefault*/ true); + const type = getBaseConstraintOfType(operandType) || operandType; + return !!(filterType(type, t => (getTypeFacts(t) & notEqualFacts) === notEqualFacts).flags & TypeFlags.Never); + } const type = getTypeOfExpression(node.expression); if (!isLiteralType(type)) { return false; diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.js b/tests/baselines/reference/narrowingByTypeofInSwitch.js new file mode 100644 index 00000000000..2cf4b9027c2 --- /dev/null +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.js @@ -0,0 +1,427 @@ +//// [narrowingByTypeofInSwitch.ts] +function assertNever(x: never) { + return x; +} + +function assertNumber(x: number) { + return x; +} + +function assertBoolean(x: boolean) { + return x; +} + +function assertString(x: string) { + return x; +} + +function assertSymbol(x: symbol) { + return x; +} + +function assertFunction(x: Function) { + return x; +} + +function assertObject(x: object) { + return x; +} + +function assertUndefined(x: undefined) { + return x; +} + +function assertAll(x: Basic) { + return x; +} + +type Basic = number | boolean | string | symbol | object | Function | undefined; + +function testUnion(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObject(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertNever(x); +} + +function testExtendsUnion(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertAll(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertAll(x); +} + +function testAny(x: any) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObject(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertAll(x); // is any +} + +function a1(x: string | object | undefined) { + return x; +} + +function testUnionExplicitDefault(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + default: a1(x); return; + } +} + +function testUnionImplicitDefault(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + } + return a1(x); +} + +function testExtendsExplicitDefault(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + default: assertAll(x); return; + + } +} + +function testExtendsImplicitDefault(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + } + return assertAll(x); +} + +type L = (x: number) => string; +type R = { x: string, y: number } + +function exhaustiveChecks(x: number | string | L | R): string { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return x(42); + case 'object': return x.x; + } +} + +function exhaustiveChecksGenerics(x: T): string { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return (x as L)(42); // Can't narrow generic + case 'object': return (x as R).x; // Can't narrow generic + } +} + +function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { + switch (typeof xy) { + case 'function': return [xy, xy(42)]; + case 'object': return [xy, xy.y]; + default: return assertNever(xy); + } +} + +function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { + switch (typeof xy) { + case 'function': return [xy, 1]; + case 'object': return [xy, 'two']; + case 'number': return [xy] + } +} + +function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { + switch (typeof xy) { + case 'object': return [xy, xy.y]; + case 'function': return [xy, xy(42)]; + } +} + +function switchOrdering(x: string | number | boolean) { + switch (typeof x) { + case 'string': return assertString(x); + case 'number': return assertNumber(x); + case 'boolean': return assertBoolean(x); + case 'number': return assertNever(x); + } +} + +function switchOrderingWithDefault(x: string | number | boolean) { + function local(y: string | number | boolean) { + return x; + } + switch (typeof x) { + case 'string': + case 'number': + default: return local(x) + case 'string': return assertNever(x); + case 'number': return assertNever(x); + } +} + + +//// [narrowingByTypeofInSwitch.js] +function assertNever(x) { + return x; +} +function assertNumber(x) { + return x; +} +function assertBoolean(x) { + return x; +} +function assertString(x) { + return x; +} +function assertSymbol(x) { + return x; +} +function assertFunction(x) { + return x; +} +function assertObject(x) { + return x; +} +function assertUndefined(x) { + return x; +} +function assertAll(x) { + return x; +} +function testUnion(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + case 'object': + assertObject(x); + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + } + assertNever(x); +} +function testExtendsUnion(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertAll(x); + return; + case 'symbol': + assertSymbol(x); + return; + case 'object': + assertAll(x); + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + } + assertAll(x); +} +function testAny(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + case 'object': + assertObject(x); + return; + case 'string': + assertString(x); + return; + case 'undefined': + assertUndefined(x); + return; + } + assertAll(x); // is any +} +function a1(x) { + return x; +} +function testUnionExplicitDefault(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + default: + a1(x); + return; + } +} +function testUnionImplicitDefault(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertFunction(x); + return; + case 'symbol': + assertSymbol(x); + return; + } + return a1(x); +} +function testExtendsExplicitDefault(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertAll(x); + return; + case 'symbol': + assertSymbol(x); + return; + default: + assertAll(x); + return; + } +} +function testExtendsImplicitDefault(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + return; + case 'boolean': + assertBoolean(x); + return; + case 'function': + assertAll(x); + return; + case 'symbol': + assertSymbol(x); + return; + } + return assertAll(x); +} +function exhaustiveChecks(x) { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return x(42); + case 'object': return x.x; + } +} +function exhaustiveChecksGenerics(x) { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return x(42); // Can't narrow generic + case 'object': return x.x; // Can't narrow generic + } +} +function multipleGeneric(xy) { + switch (typeof xy) { + case 'function': return [xy, xy(42)]; + case 'object': return [xy, xy.y]; + default: return assertNever(xy); + } +} +function multipleGenericFuse(xy) { + switch (typeof xy) { + case 'function': return [xy, 1]; + case 'object': return [xy, 'two']; + case 'number': return [xy]; + } +} +function multipleGenericExhaustive(xy) { + switch (typeof xy) { + case 'object': return [xy, xy.y]; + case 'function': return [xy, xy(42)]; + } +} +function switchOrdering(x) { + switch (typeof x) { + case 'string': return assertString(x); + case 'number': return assertNumber(x); + case 'boolean': return assertBoolean(x); + case 'number': return assertNever(x); + } +} +function switchOrderingWithDefault(x) { + function local(y) { + return x; + } + switch (typeof x) { + case 'string': + case 'number': + default: return local(x); + case 'string': return assertNever(x); + case 'number': return assertNever(x); + } +} diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols new file mode 100644 index 00000000000..2d1bd06baba --- /dev/null +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols @@ -0,0 +1,542 @@ +=== tests/cases/compiler/narrowingByTypeofInSwitch.ts === +function assertNever(x: never) { +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 0, 21)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 0, 21)) +} + +function assertNumber(x: number) { +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 4, 22)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 4, 22)) +} + +function assertBoolean(x: boolean) { +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 8, 23)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 8, 23)) +} + +function assertString(x: string) { +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 12, 22)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 12, 22)) +} + +function assertSymbol(x: symbol) { +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 16, 22)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 16, 22)) +} + +function assertFunction(x: Function) { +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 20, 24)) +>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 20, 24)) +} + +function assertObject(x: object) { +>assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 24, 22)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 24, 22)) +} + +function assertUndefined(x: undefined) { +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 25)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 28, 25)) +} + +function assertAll(x: Basic) { +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) +} + +type Basic = number | boolean | string | symbol | object | Function | undefined; +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) + +function testUnion(x: Basic) { +>testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 36, 80)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'object': assertObject(x); return; +>assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) + } + assertNever(x); +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +} + +function testExtendsUnion(x: T) { +>testExtendsUnion : Symbol(testExtendsUnion, Decl(narrowingByTypeofInSwitch.ts, 49, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 51, 26)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 51, 26)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'function': assertAll(x); return; +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'object': assertAll(x); return; +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) + } + assertAll(x); +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +} + +function testAny(x: any) { +>testAny : Symbol(testAny, Decl(narrowingByTypeofInSwitch.ts, 62, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'object': assertObject(x); return; +>assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'string': assertString(x); return; +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + + case 'undefined': assertUndefined(x); return; +>assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) + } + assertAll(x); // is any +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +} + +function a1(x: string | object | undefined) { +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 77, 12)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 77, 12)) +} + +function testUnionExplicitDefault(x: Basic) { +>testUnionExplicitDefault : Symbol(testUnionExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 79, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + + default: a1(x); return; +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) + } +} + +function testUnionImplicitDefault(x: Basic) { +>testUnionImplicitDefault : Symbol(testUnionImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 89, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) + + case 'function': assertFunction(x); return; +>assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) + } + return a1(x); +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +} + +function testExtendsExplicitDefault(x: T) { +>testExtendsExplicitDefault : Symbol(testExtendsExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 99, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 101, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 101, 36)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + case 'function': assertAll(x); return; +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + default: assertAll(x); return; +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) + + } +} + +function testExtendsImplicitDefault(x: T) { +>testExtendsImplicitDefault : Symbol(testExtendsImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 110, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 112, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 112, 36)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) + + case 'number': assertNumber(x); return; +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) + + case 'boolean': assertBoolean(x); return; +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) + + case 'function': assertAll(x); return; +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) + + case 'symbol': assertSymbol(x); return; +>assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) + } + return assertAll(x); +>assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +} + +type L = (x: number) => string; +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 122, 10)) + +type R = { x: string, y: number } +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) + +function exhaustiveChecks(x: number | string | L | R): string { +>exhaustiveChecks : Symbol(exhaustiveChecks, Decl(narrowingByTypeofInSwitch.ts, 123, 33)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) + + case 'number': return x.toString(2); +>x.toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) + + case 'string': return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) + + case 'function': return x(42); +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) + + case 'object': return x.x; +>x.x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) + } +} + +function exhaustiveChecksGenerics(x: T): string { +>exhaustiveChecksGenerics : Symbol(exhaustiveChecksGenerics, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 134, 34)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 134, 34)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) + + case 'number': return x.toString(2); +>x.toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) + + case 'string': return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) + + case 'function': return (x as L)(42); // Can't narrow generic +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) + + case 'object': return (x as R).x; // Can't narrow generic +>(x as R).x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) + } +} + +function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { +>multipleGeneric : Symbol(multipleGeneric, Decl(narrowingByTypeofInSwitch.ts, 141, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) + + switch (typeof xy) { +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) + + case 'function': return [xy, xy(42)]; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) + + case 'object': return [xy, xy.y]; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) + + default: return assertNever(xy); +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) + } +} + +function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { +>multipleGenericFuse : Symbol(multipleGenericFuse, Decl(narrowingByTypeofInSwitch.ts, 149, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) + + switch (typeof xy) { +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) + + case 'function': return [xy, 1]; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) + + case 'object': return [xy, 'two']; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) + + case 'number': return [xy] +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) + } +} + +function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { +>multipleGenericExhaustive : Symbol(multipleGenericExhaustive, Decl(narrowingByTypeofInSwitch.ts, 157, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) + + switch (typeof xy) { +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) + + case 'object': return [xy, xy.y]; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) + + case 'function': return [xy, xy(42)]; +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) + } +} + +function switchOrdering(x: string | number | boolean) { +>switchOrdering : Symbol(switchOrdering, Decl(narrowingByTypeofInSwitch.ts, 164, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + + case 'string': return assertString(x); +>assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + + case 'number': return assertNumber(x); +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + + case 'boolean': return assertBoolean(x); +>assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + + case 'number': return assertNever(x); +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) + } +} + +function switchOrderingWithDefault(x: string | number | boolean) { +>switchOrderingWithDefault : Symbol(switchOrderingWithDefault, Decl(narrowingByTypeofInSwitch.ts, 173, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + + function local(y: string | number | boolean) { +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 175, 66)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 176, 19)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + } + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + + case 'string': + case 'number': + default: return local(x) +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 175, 66)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + + case 'string': return assertNever(x); +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + + case 'number': return assertNever(x); +>assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) + } +} + diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types new file mode 100644 index 00000000000..785bdd23609 --- /dev/null +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -0,0 +1,695 @@ +=== tests/cases/compiler/narrowingByTypeofInSwitch.ts === +function assertNever(x: never) { +>assertNever : (x: never) => never +>x : never + + return x; +>x : never +} + +function assertNumber(x: number) { +>assertNumber : (x: number) => number +>x : number + + return x; +>x : number +} + +function assertBoolean(x: boolean) { +>assertBoolean : (x: boolean) => boolean +>x : boolean + + return x; +>x : boolean +} + +function assertString(x: string) { +>assertString : (x: string) => string +>x : string + + return x; +>x : string +} + +function assertSymbol(x: symbol) { +>assertSymbol : (x: symbol) => symbol +>x : symbol + + return x; +>x : symbol +} + +function assertFunction(x: Function) { +>assertFunction : (x: Function) => Function +>x : Function +>Function : Function + + return x; +>x : Function +} + +function assertObject(x: object) { +>assertObject : (x: object) => object +>x : object + + return x; +>x : object +} + +function assertUndefined(x: undefined) { +>assertUndefined : (x: undefined) => undefined +>x : undefined + + return x; +>x : undefined +} + +function assertAll(x: Basic) { +>assertAll : (x: Basic) => Basic +>x : Basic +>Basic : Basic + + return x; +>x : Basic +} + +type Basic = number | boolean | string | symbol | object | Function | undefined; +>Basic : Basic +>Function : Function + +function testUnion(x: Basic) { +>testUnion : (x: Basic) => void +>x : Basic +>Basic : Basic + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : Basic + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : Function + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + + case 'object': assertObject(x); return; +>'object' : "object" +>assertObject(x) : object +>assertObject : (x: object) => object +>x : object + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : string + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : undefined + } + assertNever(x); +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never +} + +function testExtendsUnion(x: T) { +>testExtendsUnion : (x: T) => void +>T : T +>Basic : Basic +>x : T +>T : T + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : T + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : T & number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : (T & true) | (T & false) + + case 'function': assertAll(x); return; +>'function' : "function" +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : T & symbol + + case 'object': assertAll(x); return; +>'object' : "object" +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : T & string + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : T & undefined + } + assertAll(x); +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T +} + +function testAny(x: any) { +>testAny : (x: any) => void +>x : any + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : any + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : any + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + + case 'object': assertObject(x); return; +>'object' : "object" +>assertObject(x) : object +>assertObject : (x: object) => object +>x : any + + case 'string': assertString(x); return; +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : string + + case 'undefined': assertUndefined(x); return; +>'undefined' : "undefined" +>assertUndefined(x) : undefined +>assertUndefined : (x: undefined) => undefined +>x : undefined + } + assertAll(x); // is any +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : any +} + +function a1(x: string | object | undefined) { +>a1 : (x: string | object | undefined) => string | object | undefined +>x : string | object | undefined + + return x; +>x : string | object | undefined +} + +function testUnionExplicitDefault(x: Basic) { +>testUnionExplicitDefault : (x: Basic) => void +>x : Basic +>Basic : Basic + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : Basic + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : Function + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + + default: a1(x); return; +>a1(x) : string | object | undefined +>a1 : (x: string | object | undefined) => string | object | undefined +>x : string | object | undefined + } +} + +function testUnionImplicitDefault(x: Basic) { +>testUnionImplicitDefault : (x: Basic) => string | object | undefined +>x : Basic +>Basic : Basic + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : Basic + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'function': assertFunction(x); return; +>'function' : "function" +>assertFunction(x) : Function +>assertFunction : (x: Function) => Function +>x : Function + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : symbol + } + return a1(x); +>a1(x) : string | object | undefined +>a1 : (x: string | object | undefined) => string | object | undefined +>x : string | object | undefined +} + +function testExtendsExplicitDefault(x: T) { +>testExtendsExplicitDefault : (x: T) => void +>T : T +>Basic : Basic +>x : T +>T : T + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : T + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : T & number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : (T & true) | (T & false) + + case 'function': assertAll(x); return; +>'function' : "function" +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : T & symbol + + default: assertAll(x); return; +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T + + } +} + +function testExtendsImplicitDefault(x: T) { +>testExtendsImplicitDefault : (x: T) => string | number | boolean | symbol | object | undefined +>T : T +>Basic : Basic +>x : T +>T : T + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : T + + case 'number': assertNumber(x); return; +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : T & number + + case 'boolean': assertBoolean(x); return; +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : (T & true) | (T & false) + + case 'function': assertAll(x); return; +>'function' : "function" +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T + + case 'symbol': assertSymbol(x); return; +>'symbol' : "symbol" +>assertSymbol(x) : symbol +>assertSymbol : (x: symbol) => symbol +>x : T & symbol + } + return assertAll(x); +>assertAll(x) : Basic +>assertAll : (x: Basic) => Basic +>x : T +} + +type L = (x: number) => string; +>L : L +>x : number + +type R = { x: string, y: number } +>R : R +>x : string +>y : number + +function exhaustiveChecks(x: number | string | L | R): string { +>exhaustiveChecks : (x: string | number | R | L) => string +>x : string | number | R | L +>L : L +>R : R + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : string | number | R | L + + case 'number': return x.toString(2); +>'number' : "number" +>x.toString(2) : string +>x.toString : (radix?: number | undefined) => string +>x : number +>toString : (radix?: number | undefined) => string +>2 : 2 + + case 'string': return x; +>'string' : "string" +>x : string + + case 'function': return x(42); +>'function' : "function" +>x(42) : string +>x : L +>42 : 42 + + case 'object': return x.x; +>'object' : "object" +>x.x : string +>x : R +>x : string + } +} + +function exhaustiveChecksGenerics(x: T): string { +>exhaustiveChecksGenerics : (x: T) => string +>T : T +>L : L +>R : R +>x : T +>T : T + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : T + + case 'number': return x.toString(2); +>'number' : "number" +>x.toString(2) : string +>x.toString : ((radix?: number | undefined) => string) | ((() => string) & ((radix?: number | undefined) => string)) | ((() => string) & ((radix?: number | undefined) => string)) | ((() => string) & ((radix?: number | undefined) => string)) +>x : T & number +>toString : ((radix?: number | undefined) => string) | ((() => string) & ((radix?: number | undefined) => string)) | ((() => string) & ((radix?: number | undefined) => string)) | ((() => string) & ((radix?: number | undefined) => string)) +>2 : 2 + + case 'string': return x; +>'string' : "string" +>x : T & string + + case 'function': return (x as L)(42); // Can't narrow generic +>'function' : "function" +>(x as L)(42) : string +>(x as L) : L +>x as L : L +>x : T +>L : L +>42 : 42 + + case 'object': return (x as R).x; // Can't narrow generic +>'object' : "object" +>(x as R).x : string +>(x as R) : R +>x as R : R +>x : T +>R : R +>x : string + } +} + +function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { +>multipleGeneric : (xy: X | Y) => [X, string] | [Y, number] +>X : X +>L : L +>Y : Y +>R : R +>xy : X | Y +>X : X +>Y : Y +>X : X +>Y : Y + + switch (typeof xy) { +>typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>xy : X | Y + + case 'function': return [xy, xy(42)]; +>'function' : "function" +>[xy, xy(42)] : [X, string] +>xy : X +>xy(42) : string +>xy : X +>42 : 42 + + case 'object': return [xy, xy.y]; +>'object' : "object" +>[xy, xy.y] : [Y, number] +>xy : Y +>xy.y : number +>xy : Y +>y : number + + default: return assertNever(xy); +>assertNever(xy) : never +>assertNever : (x: never) => never +>xy : never + } +} + +function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { +>multipleGenericFuse : (xy: X | Y) => [X, number] | [Y, string] | [X | Y] +>X : X +>L : L +>Y : Y +>R : R +>xy : X | Y +>X : X +>Y : Y +>X : X +>Y : Y +>X : X +>Y : Y + + switch (typeof xy) { +>typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>xy : X | Y + + case 'function': return [xy, 1]; +>'function' : "function" +>[xy, 1] : [X, number] +>xy : X +>1 : 1 + + case 'object': return [xy, 'two']; +>'object' : "object" +>[xy, 'two'] : [Y, string] +>xy : Y +>'two' : "two" + + case 'number': return [xy] +>'number' : "number" +>[xy] : [X | Y] +>xy : X | Y + } +} + +function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { +>multipleGenericExhaustive : (xy: X | Y) => [X, string] | [Y, number] +>X : X +>L : L +>Y : Y +>R : R +>xy : X | Y +>X : X +>Y : Y +>X : X +>Y : Y + + switch (typeof xy) { +>typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>xy : X | Y + + case 'object': return [xy, xy.y]; +>'object' : "object" +>[xy, xy.y] : [Y, number] +>xy : Y +>xy.y : number +>xy : Y +>y : number + + case 'function': return [xy, xy(42)]; +>'function' : "function" +>[xy, xy(42)] : [X, string] +>xy : X +>xy(42) : string +>xy : X +>42 : 42 + } +} + +function switchOrdering(x: string | number | boolean) { +>switchOrdering : (x: string | number | boolean) => string | number | boolean +>x : string | number | boolean + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : string | number | boolean + + case 'string': return assertString(x); +>'string' : "string" +>assertString(x) : string +>assertString : (x: string) => string +>x : string + + case 'number': return assertNumber(x); +>'number' : "number" +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'boolean': return assertBoolean(x); +>'boolean' : "boolean" +>assertBoolean(x) : boolean +>assertBoolean : (x: boolean) => boolean +>x : boolean + + case 'number': return assertNever(x); +>'number' : "number" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + } +} + +function switchOrderingWithDefault(x: string | number | boolean) { +>switchOrderingWithDefault : (x: string | number | boolean) => string | number | boolean +>x : string | number | boolean + + function local(y: string | number | boolean) { +>local : (y: string | number | boolean) => string | number | boolean +>y : string | number | boolean + + return x; +>x : string | number | boolean + } + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : string | number | boolean + + case 'string': +>'string' : "string" + + case 'number': +>'number' : "number" + + default: return local(x) +>local(x) : string | number | boolean +>local : (y: string | number | boolean) => string | number | boolean +>x : string | number | boolean + + case 'string': return assertNever(x); +>'string' : "string" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + + case 'number': return assertNever(x); +>'number' : "number" +>assertNever(x) : never +>assertNever : (x: never) => never +>x : never + } +} + diff --git a/tests/cases/compiler/narrowingByTypeofInSwitch.ts b/tests/cases/compiler/narrowingByTypeofInSwitch.ts new file mode 100644 index 00000000000..aadd351b87e --- /dev/null +++ b/tests/cases/compiler/narrowingByTypeofInSwitch.ts @@ -0,0 +1,190 @@ +// @strictNullChecks: true +// @strictFunctionTypes: true + +function assertNever(x: never) { + return x; +} + +function assertNumber(x: number) { + return x; +} + +function assertBoolean(x: boolean) { + return x; +} + +function assertString(x: string) { + return x; +} + +function assertSymbol(x: symbol) { + return x; +} + +function assertFunction(x: Function) { + return x; +} + +function assertObject(x: object) { + return x; +} + +function assertUndefined(x: undefined) { + return x; +} + +function assertAll(x: Basic) { + return x; +} + +type Basic = number | boolean | string | symbol | object | Function | undefined; + +function testUnion(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObject(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertNever(x); +} + +function testExtendsUnion(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertAll(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertAll(x); +} + +function testAny(x: any) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + case 'object': assertObject(x); return; + case 'string': assertString(x); return; + case 'undefined': assertUndefined(x); return; + } + assertAll(x); // is any +} + +function a1(x: string | object | undefined) { + return x; +} + +function testUnionExplicitDefault(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + default: a1(x); return; + } +} + +function testUnionImplicitDefault(x: Basic) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertFunction(x); return; + case 'symbol': assertSymbol(x); return; + } + return a1(x); +} + +function testExtendsExplicitDefault(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + default: assertAll(x); return; + + } +} + +function testExtendsImplicitDefault(x: T) { + switch (typeof x) { + case 'number': assertNumber(x); return; + case 'boolean': assertBoolean(x); return; + case 'function': assertAll(x); return; + case 'symbol': assertSymbol(x); return; + } + return assertAll(x); +} + +type L = (x: number) => string; +type R = { x: string, y: number } + +function exhaustiveChecks(x: number | string | L | R): string { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return x(42); + case 'object': return x.x; + } +} + +function exhaustiveChecksGenerics(x: T): string { + switch (typeof x) { + case 'number': return x.toString(2); + case 'string': return x; + case 'function': return (x as L)(42); // Can't narrow generic + case 'object': return (x as R).x; // Can't narrow generic + } +} + +function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { + switch (typeof xy) { + case 'function': return [xy, xy(42)]; + case 'object': return [xy, xy.y]; + default: return assertNever(xy); + } +} + +function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { + switch (typeof xy) { + case 'function': return [xy, 1]; + case 'object': return [xy, 'two']; + case 'number': return [xy] + } +} + +function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { + switch (typeof xy) { + case 'object': return [xy, xy.y]; + case 'function': return [xy, xy(42)]; + } +} + +function switchOrdering(x: string | number | boolean) { + switch (typeof x) { + case 'string': return assertString(x); + case 'number': return assertNumber(x); + case 'boolean': return assertBoolean(x); + case 'number': return assertNever(x); + } +} + +function switchOrderingWithDefault(x: string | number | boolean) { + function local(y: string | number | boolean) { + return x; + } + switch (typeof x) { + case 'string': + case 'number': + default: return local(x) + case 'string': return assertNever(x); + case 'number': return assertNever(x); + } +} From 9e43183884825fa3b17359ac167fdaa6aacb2530 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 23 May 2018 01:03:04 +0100 Subject: [PATCH 003/146] Add fall-through test and correct comment about implied type --- src/compiler/checker.ts | 19 +- .../reference/narrowingByTypeofInSwitch.js | 45 ++ .../narrowingByTypeofInSwitch.symbols | 415 ++++++++++-------- .../reference/narrowingByTypeofInSwitch.types | 62 +++ .../compiler/narrowingByTypeofInSwitch.ts | 24 + 5 files changed, 375 insertions(+), 190 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ab2cc1f3b85..1629717ff28 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13594,10 +13594,10 @@ namespace ts { // } // // The implied type of the first clause number | string. - // The implied type of the second clause is string (but this doesn't get used). + // The implied type of the second clause is never, but this does not get just because it includes a default case. // The implied type of the third clause is boolean (number has already be caught). if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { - let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); + let impliedType = getTypeWithFacts(getUnionType((clauseWitnesses).map(text => typeofTypesByName.get(text) || neverType)), switchFacts); if (impliedType.flags & TypeFlags.Union) { impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOfType(type) || type); } @@ -19027,17 +19027,20 @@ namespace ts { if (hasDefault) { // Value is not equal to any types after the active clause. for (let i = end; i < witnesses.length; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; + const witness = witnesses[i]; + facts |= (witness && typeofNEFacts.get(witness)) || TypeFacts.TypeofNEHostObject; } // Remove inequalities for types that appear in the // active clause because they appear before other // types collected so far. for (let i = start; i < end; i++) { - facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); + const witness = witnesses[i]; + facts &= ~((witness && typeofNEFacts.get(witness)) || 0); } // Add inequalities for types before the active clause unconditionally. for (let i = 0; i < start; i++) { - facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; + const witness = witnesses[i]; + facts |= (witness && typeofNEFacts.get(witness)) || TypeFacts.TypeofNEHostObject; } } // When in an active clause without default the set of @@ -19045,12 +19048,14 @@ namespace ts { else { // Add equalities for all types in the active clause. for (let i = start; i < end; i++) { - facts |= typeofEQFacts.get(witnesses[i]) || TypeFacts.TypeofEQHostObject; + const witness = witnesses[i]; + facts |= (witness && typeofEQFacts.get(witness)) || TypeFacts.TypeofEQHostObject; } // Remove equalities for types that appear before the // active clause. for (let i = 0; i < start; i++) { - facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); + const witness = witnesses[i]; + facts &= ~((witness && typeofEQFacts.get(witness)) || 0); } } return facts; diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.js b/tests/baselines/reference/narrowingByTypeofInSwitch.js index 2cf4b9027c2..95ec120a85d 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.js +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.js @@ -35,6 +35,14 @@ function assertAll(x: Basic) { return x; } +function assertStringOrNumber(x: string | number) { + return x; +} + +function assertBooleanOrObject(x: boolean | object) { + return x; +} + type Basic = number | boolean | string | symbol | object | Function | undefined; function testUnion(x: Basic) { @@ -186,6 +194,22 @@ function switchOrderingWithDefault(x: string | number | boolean) { case 'number': return assertNever(x); } } + +function fallThroughTest(x: string | number | boolean | object) { + switch (typeof x) { + case 'number': + assertNumber(x) + case 'string': + assertStringOrNumber(x) + break; + default: + assertObject(x); + case 'number': + case 'boolean': + assertBooleanOrObject(x); + break; + } +} //// [narrowingByTypeofInSwitch.js] @@ -216,6 +240,12 @@ function assertUndefined(x) { function assertAll(x) { return x; } +function assertStringOrNumber(x) { + return x; +} +function assertBooleanOrObject(x) { + return x; +} function testUnion(x) { switch (typeof x) { case 'number': @@ -425,3 +455,18 @@ function switchOrderingWithDefault(x) { case 'number': return assertNever(x); } } +function fallThroughTest(x) { + switch (typeof x) { + case 'number': + assertNumber(x); + case 'string': + assertStringOrNumber(x); + break; + default: + assertObject(x); + case 'number': + case 'boolean': + assertBooleanOrObject(x); + break; + } +} diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols index 2d1bd06baba..b451b39ac7c 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols @@ -67,476 +67,525 @@ function assertUndefined(x: undefined) { function assertAll(x: Basic) { >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) return x; >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 32, 19)) } +function assertStringOrNumber(x: string | number) { +>assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 30)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 36, 30)) +} + +function assertBooleanOrObject(x: boolean | object) { +>assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 31)) + + return x; +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 40, 31)) +} + type Basic = number | boolean | string | symbol | object | Function | undefined; ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) >Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) function testUnion(x: Basic) { ->testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 36, 80)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 44, 80)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'object': assertObject(x); return; >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) case 'undefined': assertUndefined(x); return; >assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) } assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 38, 19)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 46, 19)) } function testExtendsUnion(x: T) { ->testExtendsUnion : Symbol(testExtendsUnion, Decl(narrowingByTypeofInSwitch.ts, 49, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 51, 26)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 51, 26)) +>testExtendsUnion : Symbol(testExtendsUnion, Decl(narrowingByTypeofInSwitch.ts, 57, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 59, 26)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 59, 26)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'function': assertAll(x); return; >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'object': assertAll(x); return; >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) case 'undefined': assertUndefined(x); return; >assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) } assertAll(x); >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 51, 43)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 59, 43)) } function testAny(x: any) { ->testAny : Symbol(testAny, Decl(narrowingByTypeofInSwitch.ts, 62, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>testAny : Symbol(testAny, Decl(narrowingByTypeofInSwitch.ts, 70, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'object': assertObject(x); return; >assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'string': assertString(x); return; >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) case 'undefined': assertUndefined(x); return; >assertUndefined : Symbol(assertUndefined, Decl(narrowingByTypeofInSwitch.ts, 26, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) } assertAll(x); // is any >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 64, 17)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 72, 17)) } function a1(x: string | object | undefined) { ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 77, 12)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 85, 12)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 77, 12)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 85, 12)) } function testUnionExplicitDefault(x: Basic) { ->testUnionExplicitDefault : Symbol(testUnionExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 79, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>testUnionExplicitDefault : Symbol(testUnionExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 87, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) default: a1(x); return; ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 81, 34)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 89, 34)) } } function testUnionImplicitDefault(x: Basic) { ->testUnionImplicitDefault : Symbol(testUnionImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 89, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>testUnionImplicitDefault : Symbol(testUnionImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 97, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) case 'function': assertFunction(x); return; >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) } return a1(x); ->a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 75, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 91, 34)) +>a1 : Symbol(a1, Decl(narrowingByTypeofInSwitch.ts, 83, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 99, 34)) } function testExtendsExplicitDefault(x: T) { ->testExtendsExplicitDefault : Symbol(testExtendsExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 99, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 101, 36)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 101, 36)) +>testExtendsExplicitDefault : Symbol(testExtendsExplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 107, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 109, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 109, 36)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) case 'function': assertAll(x); return; >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) default: assertAll(x); return; >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 101, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 109, 53)) } } function testExtendsImplicitDefault(x: T) { ->testExtendsImplicitDefault : Symbol(testExtendsImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 110, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 112, 36)) ->Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 112, 36)) +>testExtendsImplicitDefault : Symbol(testExtendsImplicitDefault, Decl(narrowingByTypeofInSwitch.ts, 118, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 120, 36)) +>Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 120, 36)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) case 'number': assertNumber(x); return; >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) case 'boolean': assertBoolean(x); return; >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) case 'function': assertAll(x); return; >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) case 'symbol': assertSymbol(x); return; >assertSymbol : Symbol(assertSymbol, Decl(narrowingByTypeofInSwitch.ts, 14, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) } return assertAll(x); >assertAll : Symbol(assertAll, Decl(narrowingByTypeofInSwitch.ts, 30, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 112, 53)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 120, 53)) } type L = (x: number) => string; ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 122, 10)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 130, 10)) type R = { x: string, y: number } ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) function exhaustiveChecks(x: number | string | L | R): string { ->exhaustiveChecks : Symbol(exhaustiveChecks, Decl(narrowingByTypeofInSwitch.ts, 123, 33)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) +>exhaustiveChecks : Symbol(exhaustiveChecks, Decl(narrowingByTypeofInSwitch.ts, 131, 33)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) case 'number': return x.toString(2); >x.toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) >toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) case 'string': return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) case 'function': return x(42); ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) case 'object': return x.x; ->x.x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 125, 26)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) +>x.x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) } } function exhaustiveChecksGenerics(x: T): string { ->exhaustiveChecksGenerics : Symbol(exhaustiveChecksGenerics, Decl(narrowingByTypeofInSwitch.ts, 132, 1)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 134, 34)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) ->T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 134, 34)) +>exhaustiveChecksGenerics : Symbol(exhaustiveChecksGenerics, Decl(narrowingByTypeofInSwitch.ts, 140, 1)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 142, 34)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>T : Symbol(T, Decl(narrowingByTypeofInSwitch.ts, 142, 34)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) case 'number': return x.toString(2); >x.toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) >toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) case 'string': return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) case 'function': return (x as L)(42); // Can't narrow generic ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) case 'object': return (x as R).x; // Can't narrow generic ->(x as R).x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 134, 69)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 123, 10)) +>(x as R).x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 131, 10)) } } function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { ->multipleGeneric : Symbol(multipleGeneric, Decl(narrowingByTypeofInSwitch.ts, 141, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 143, 25)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 143, 37)) +>multipleGeneric : Symbol(multipleGeneric, Decl(narrowingByTypeofInSwitch.ts, 149, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 25)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 37)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) case 'function': return [xy, xy(42)]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) case 'object': return [xy, xy.y]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) ->xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) default: return assertNever(xy); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 143, 51)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 51)) } } function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { ->multipleGenericFuse : Symbol(multipleGenericFuse, Decl(narrowingByTypeofInSwitch.ts, 149, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 151, 29)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 151, 50)) +>multipleGenericFuse : Symbol(multipleGenericFuse, Decl(narrowingByTypeofInSwitch.ts, 157, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 29)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 50)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) case 'function': return [xy, 1]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) case 'object': return [xy, 'two']; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) case 'number': return [xy] ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 151, 73)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 73)) } } function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { ->multipleGenericExhaustive : Symbol(multipleGenericExhaustive, Decl(narrowingByTypeofInSwitch.ts, 157, 1)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) ->L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 120, 1)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) ->R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 122, 31)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) ->X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 159, 35)) ->Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 159, 47)) +>multipleGenericExhaustive : Symbol(multipleGenericExhaustive, Decl(narrowingByTypeofInSwitch.ts, 165, 1)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) +>L : Symbol(L, Decl(narrowingByTypeofInSwitch.ts, 128, 1)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) +>R : Symbol(R, Decl(narrowingByTypeofInSwitch.ts, 130, 31)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) +>X : Symbol(X, Decl(narrowingByTypeofInSwitch.ts, 167, 35)) +>Y : Symbol(Y, Decl(narrowingByTypeofInSwitch.ts, 167, 47)) switch (typeof xy) { ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) case 'object': return [xy, xy.y]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) ->xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 123, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>xy.y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 131, 21)) case 'function': return [xy, xy(42)]; ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) ->xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 159, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) +>xy : Symbol(xy, Decl(narrowingByTypeofInSwitch.ts, 167, 61)) } } function switchOrdering(x: string | number | boolean) { ->switchOrdering : Symbol(switchOrdering, Decl(narrowingByTypeofInSwitch.ts, 164, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>switchOrdering : Symbol(switchOrdering, Decl(narrowingByTypeofInSwitch.ts, 172, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) case 'string': return assertString(x); >assertString : Symbol(assertString, Decl(narrowingByTypeofInSwitch.ts, 10, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) case 'number': return assertNumber(x); >assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) case 'boolean': return assertBoolean(x); >assertBoolean : Symbol(assertBoolean, Decl(narrowingByTypeofInSwitch.ts, 6, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) case 'number': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 166, 24)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 174, 24)) } } function switchOrderingWithDefault(x: string | number | boolean) { ->switchOrderingWithDefault : Symbol(switchOrderingWithDefault, Decl(narrowingByTypeofInSwitch.ts, 173, 1)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>switchOrderingWithDefault : Symbol(switchOrderingWithDefault, Decl(narrowingByTypeofInSwitch.ts, 181, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) function local(y: string | number | boolean) { ->local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 175, 66)) ->y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 176, 19)) +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 183, 66)) +>y : Symbol(y, Decl(narrowingByTypeofInSwitch.ts, 184, 19)) return x; ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) } switch (typeof x) { ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) case 'string': case 'number': default: return local(x) ->local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 175, 66)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>local : Symbol(local, Decl(narrowingByTypeofInSwitch.ts, 183, 66)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) case 'string': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) case 'number': return assertNever(x); >assertNever : Symbol(assertNever, Decl(narrowingByTypeofInSwitch.ts, 0, 0)) ->x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 175, 35)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 183, 35)) + } +} + +function fallThroughTest(x: string | number | boolean | object) { +>fallThroughTest : Symbol(fallThroughTest, Decl(narrowingByTypeofInSwitch.ts, 194, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + switch (typeof x) { +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + case 'number': + assertNumber(x) +>assertNumber : Symbol(assertNumber, Decl(narrowingByTypeofInSwitch.ts, 2, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + case 'string': + assertStringOrNumber(x) +>assertStringOrNumber : Symbol(assertStringOrNumber, Decl(narrowingByTypeofInSwitch.ts, 34, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + break; + default: + assertObject(x); +>assertObject : Symbol(assertObject, Decl(narrowingByTypeofInSwitch.ts, 22, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + case 'number': + case 'boolean': + assertBooleanOrObject(x); +>assertBooleanOrObject : Symbol(assertBooleanOrObject, Decl(narrowingByTypeofInSwitch.ts, 38, 1)) +>x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 196, 25)) + + break; } } diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index 785bdd23609..8672f4c9e7d 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -73,6 +73,22 @@ function assertAll(x: Basic) { >x : Basic } +function assertStringOrNumber(x: string | number) { +>assertStringOrNumber : (x: string | number) => string | number +>x : string | number + + return x; +>x : string | number +} + +function assertBooleanOrObject(x: boolean | object) { +>assertBooleanOrObject : (x: boolean | object) => boolean | object +>x : boolean | object + + return x; +>x : boolean | object +} + type Basic = number | boolean | string | symbol | object | Function | undefined; >Basic : Basic >Function : Function @@ -693,3 +709,49 @@ function switchOrderingWithDefault(x: string | number | boolean) { } } +function fallThroughTest(x: string | number | boolean | object) { +>fallThroughTest : (x: string | number | boolean | object) => void +>x : string | number | boolean | object + + switch (typeof x) { +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : string | number | boolean | object + + case 'number': +>'number' : "number" + + assertNumber(x) +>assertNumber(x) : number +>assertNumber : (x: number) => number +>x : number + + case 'string': +>'string' : "string" + + assertStringOrNumber(x) +>assertStringOrNumber(x) : string | number +>assertStringOrNumber : (x: string | number) => string | number +>x : string | number + + break; + default: + assertObject(x); +>assertObject(x) : object +>assertObject : (x: object) => object +>x : object + + case 'number': +>'number' : "number" + + case 'boolean': +>'boolean' : "boolean" + + assertBooleanOrObject(x); +>assertBooleanOrObject(x) : boolean | object +>assertBooleanOrObject : (x: boolean | object) => boolean | object +>x : boolean | object + + break; + } +} + diff --git a/tests/cases/compiler/narrowingByTypeofInSwitch.ts b/tests/cases/compiler/narrowingByTypeofInSwitch.ts index aadd351b87e..252c1d9445a 100644 --- a/tests/cases/compiler/narrowingByTypeofInSwitch.ts +++ b/tests/cases/compiler/narrowingByTypeofInSwitch.ts @@ -37,6 +37,14 @@ function assertAll(x: Basic) { return x; } +function assertStringOrNumber(x: string | number) { + return x; +} + +function assertBooleanOrObject(x: boolean | object) { + return x; +} + type Basic = number | boolean | string | symbol | object | Function | undefined; function testUnion(x: Basic) { @@ -188,3 +196,19 @@ function switchOrderingWithDefault(x: string | number | boolean) { case 'number': return assertNever(x); } } + +function fallThroughTest(x: string | number | boolean | object) { + switch (typeof x) { + case 'number': + assertNumber(x) + case 'string': + assertStringOrNumber(x) + break; + default: + assertObject(x); + case 'number': + case 'boolean': + assertBooleanOrObject(x); + break; + } +} From 6391742dca16cdddbf5a9fd5a5a42c216a80f92f Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 23 May 2018 03:12:50 +0100 Subject: [PATCH 004/146] Make undefined for default case less pervasive by removing once done with it --- src/compiler/checker.ts | 50 ++++++++++++++++++++++++++--------------- 1 file changed, 32 insertions(+), 18 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1629717ff28..25a9039009e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -13572,10 +13572,27 @@ namespace ts { if (!switchWitnesses.length) { return type; } - const clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); // Equal start and end denotes implicit fallthrough; undefined marks explicit default clause - const hasDefaultClause = clauseStart === clauseEnd || contains(clauseWitnesses, /*explicitDefaultStatement*/ undefined); - const switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + const defaultCaseLocation = findIndex(switchWitnesses, elem => elem === undefined); + const hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd); + let clauseWitnesses: string[]; + let switchFacts: TypeFacts; + if (defaultCaseLocation > -1) { + // We no longer need the undefined denoting an + // explicit default case. Remove the undefined and + // fix-up clauseStart and clauseEnd. This means + // that we don't have to worry about undefined + // in the witness array. + const witnesses = switchWitnesses.filter(witness => witness !== undefined); + const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; + const fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; + clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); + switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause); + } + else { + clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); + switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); + } // The implied type is the raw type suggested by a // value being caught in this clause. // - If there is a default the implied type is not used. @@ -13594,10 +13611,10 @@ namespace ts { // } // // The implied type of the first clause number | string. - // The implied type of the second clause is never, but this does not get just because it includes a default case. + // The implied type of the second clause is never, but this does not get used because it includes a default case. // The implied type of the third clause is boolean (number has already be caught). if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { - let impliedType = getTypeWithFacts(getUnionType((clauseWitnesses).map(text => typeofTypesByName.get(text) || neverType)), switchFacts); + let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); if (impliedType.flags & TypeFlags.Union) { impliedType = getAssignmentReducedType(impliedType as UnionType, getBaseConstraintOfType(type) || type); } @@ -19019,7 +19036,7 @@ namespace ts { * from `start` to `end`. Parameter `hasDefault` denotes * whether the active clause contains a default clause. */ - function getFactsFromTypeofSwitch(start: number, end: number, witnesses: (string | undefined)[], hasDefault: boolean): TypeFacts { + function getFactsFromTypeofSwitch(start: number, end: number, witnesses: string[], hasDefault: boolean): TypeFacts { let facts: TypeFacts = TypeFacts.None; // When in the default we only collect inequality facts // because default is 'in theory' a set of infinite @@ -19027,20 +19044,17 @@ namespace ts { if (hasDefault) { // Value is not equal to any types after the active clause. for (let i = end; i < witnesses.length; i++) { - const witness = witnesses[i]; - facts |= (witness && typeofNEFacts.get(witness)) || TypeFacts.TypeofNEHostObject; + facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; } // Remove inequalities for types that appear in the // active clause because they appear before other // types collected so far. for (let i = start; i < end; i++) { - const witness = witnesses[i]; - facts &= ~((witness && typeofNEFacts.get(witness)) || 0); + facts &= ~(typeofNEFacts.get(witnesses[i]) || 0); } // Add inequalities for types before the active clause unconditionally. for (let i = 0; i < start; i++) { - const witness = witnesses[i]; - facts |= (witness && typeofNEFacts.get(witness)) || TypeFacts.TypeofNEHostObject; + facts |= typeofNEFacts.get(witnesses[i]) || TypeFacts.TypeofNEHostObject; } } // When in an active clause without default the set of @@ -19048,14 +19062,12 @@ namespace ts { else { // Add equalities for all types in the active clause. for (let i = start; i < end; i++) { - const witness = witnesses[i]; - facts |= (witness && typeofEQFacts.get(witness)) || TypeFacts.TypeofEQHostObject; + facts |= typeofEQFacts.get(witnesses[i]) || TypeFacts.TypeofEQHostObject; } // Remove equalities for types that appear before the // active clause. for (let i = 0; i < start; i++) { - const witness = witnesses[i]; - facts &= ~((witness && typeofEQFacts.get(witness)) || 0); + facts &= ~(typeofEQFacts.get(witnesses[i]) || 0); } } return facts; @@ -19067,8 +19079,10 @@ namespace ts { } if (node.expression.kind === SyntaxKind.TypeOfExpression) { const operandType = getTypeOfExpression((node.expression as TypeOfExpression).expression); - // Type is not equal to every type in the switch. - const notEqualFacts = getFactsFromTypeofSwitch(0, 0, getSwitchClauseTypeOfWitnesses(node), /*hasDefault*/ true); + // This cast is safe because the switch is possibly exhaustive and does not contain a default case, so there can be no undefined. + const witnesses = getSwitchClauseTypeOfWitnesses(node); + // notEqualFacts states that the type of the switched value is not equal to every type in the switch. + const notEqualFacts = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true); const type = getBaseConstraintOfType(operandType) || operandType; return !!(filterType(type, t => (getTypeFacts(t) & notEqualFacts) === notEqualFacts).flags & TypeFlags.Never); } From 4d8529c9eb6c1cab39eabe4636525d4e79cfdc70 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 11 Jul 2018 11:00:44 +0100 Subject: [PATCH 005/146] Improve comments in narrowBySwitchOnTypeOf --- src/compiler/checker.ts | 51 +++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 25a9039009e..539430c2642 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12840,6 +12840,8 @@ namespace ts { return links.switchTypes; } + // Get the types from all cases in a switch on `typeof`. An + // `undefined` element denotes an explicit `default` clause. function getSwitchClauseTypeOfWitnesses(switchStatement: SwitchStatement): (string | undefined)[] { const witnesses: (string | undefined)[] = []; for (const clause of switchStatement.caseBlock.clauses) { @@ -13584,6 +13586,7 @@ namespace ts { // that we don't have to worry about undefined // in the witness array. const witnesses = switchWitnesses.filter(witness => witness !== undefined); + // The adjust clause start and end after removing the `default` statement. const fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart; const fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd; clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd); @@ -13593,26 +13596,34 @@ namespace ts { clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd); switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause); } - // The implied type is the raw type suggested by a - // value being caught in this clause. - // - If there is a default the implied type is not used. - // - Otherwise, take the union of the types in the - // clause. We narrow the union using facts to remove - // types that appear multiple types and are - // unreachable. - // Example: - // - // switch (typeof x) { - // case 'number': - // case 'string': break; - // default: break; - // case 'number': - // case 'boolean': break - // } - // - // The implied type of the first clause number | string. - // The implied type of the second clause is never, but this does not get used because it includes a default case. - // The implied type of the third clause is boolean (number has already be caught). + /* + The implied type is the raw type suggested by a + value being caught in this clause. + + When the clause contains a default case we ignore + the implied type and try to narrow using any facts + we can learn: see `switchFacts`. + + Example: + switch (typeof x) { + case 'number': + case 'string': break; + default: break; + case 'number': + case 'boolean': break + } + + In the first clause (case `number` and `string`) the + implied type is number | string. + + In the default clause we de not compute an implied type. + + In the third clause (case `number` and `boolean`) + the naive implied type is number | boolean, however + we use the type facts to narrow the implied type to + boolean. We know that number cannot be selected + because it is caught in the first clause. + */ if (!(hasDefaultClause || (type.flags & TypeFlags.Union))) { let impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(text => typeofTypesByName.get(text) || neverType)), switchFacts); if (impliedType.flags & TypeFlags.Union) { From 5aaf1e6b7a13955bcaa67413715581bd53c88d52 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Wed, 11 Jul 2018 17:45:22 +0100 Subject: [PATCH 006/146] Accept new baselines --- .../reference/narrowingByTypeofInSwitch.symbols | 12 ++++++------ .../reference/narrowingByTypeofInSwitch.types | 6 +++--- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols index b451b39ac7c..80246251815 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.symbols +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.symbols @@ -42,7 +42,7 @@ function assertSymbol(x: symbol) { function assertFunction(x: Function) { >assertFunction : Symbol(assertFunction, Decl(narrowingByTypeofInSwitch.ts, 18, 1)) >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 20, 24)) ->Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) return x; >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 20, 24)) @@ -91,7 +91,7 @@ function assertBooleanOrObject(x: boolean | object) { type Basic = number | boolean | string | symbol | object | Function | undefined; >Basic : Symbol(Basic, Decl(narrowingByTypeofInSwitch.ts, 42, 1)) ->Function : Symbol(Function, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +>Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) function testUnion(x: Basic) { >testUnion : Symbol(testUnion, Decl(narrowingByTypeofInSwitch.ts, 44, 80)) @@ -367,9 +367,9 @@ function exhaustiveChecks(x: number | string | L | R): string { >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) case 'number': return x.toString(2); ->x.toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) +>x.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) ->toString : Symbol(Number.toString, Decl(lib.d.ts, --, --)) +>toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) case 'string': return x; >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 133, 26)) @@ -396,9 +396,9 @@ function exhaustiveChecksGenerics(x: T): stri >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) case 'number': return x.toString(2); ->x.toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) +>x.toString : Symbol(toString, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --) ... and 2 more) >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) ->toString : Symbol(toString, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --) ... and 2 more) +>toString : Symbol(toString, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --) ... and 2 more) case 'string': return x; >x : Symbol(x, Decl(narrowingByTypeofInSwitch.ts, 142, 69)) diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index 8672f4c9e7d..a2aef98feb4 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -171,7 +171,7 @@ function testExtendsUnion(x: T) { >'boolean' : "boolean" >assertBoolean(x) : boolean >assertBoolean : (x: boolean) => boolean ->x : (T & true) | (T & false) +>x : (T & false) | (T & true) case 'function': assertAll(x); return; >'function' : "function" @@ -373,7 +373,7 @@ function testExtendsExplicitDefault(x: T) { >'boolean' : "boolean" >assertBoolean(x) : boolean >assertBoolean : (x: boolean) => boolean ->x : (T & true) | (T & false) +>x : (T & false) | (T & true) case 'function': assertAll(x); return; >'function' : "function" @@ -416,7 +416,7 @@ function testExtendsImplicitDefault(x: T) { >'boolean' : "boolean" >assertBoolean(x) : boolean >assertBoolean : (x: boolean) => boolean ->x : (T & true) | (T & false) +>x : (T & false) | (T & true) case 'function': assertAll(x); return; >'function' : "function" From cdfef4fa571a87b39d44622026108cc16868b927 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Fri, 13 Jul 2018 15:07:38 +0800 Subject: [PATCH 007/146] add use strict and simple parameter check --- src/compiler/checker.ts | 40 +++++- src/compiler/diagnosticMessages.json | 12 ++ src/compiler/factory.ts | 27 +++-- ...tionWithUseStrictAndSimpleParameterList.js | 101 ++++++++++++++++ ...ithUseStrictAndSimpleParameterList.symbols | 83 +++++++++++++ ...nWithUseStrictAndSimpleParameterList.types | 109 +++++++++++++++++ ...ctAndSimpleParameterList_es2016.errors.txt | 114 ++++++++++++++++++ ...hUseStrictAndSimpleParameterList_es2016.js | 83 +++++++++++++ ...trictAndSimpleParameterList_es2016.symbols | 83 +++++++++++++ ...eStrictAndSimpleParameterList_es2016.types | 109 +++++++++++++++++ ...tionWithUseStrictAndSimpleParameterList.ts | 44 +++++++ ...hUseStrictAndSimpleParameterList_es2016.ts | 46 +++++++ 12 files changed, 838 insertions(+), 13 deletions(-) create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols create mode 100644 tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types create mode 100644 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts create mode 100644 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cd91f427248..e97fc933839 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28515,11 +28515,49 @@ namespace ts { } } + function getNonSimpleParameters(parameters: ReadonlyArray): ReadonlyArray { + // ECMA-262 14.1.13 + if (parameters.length === 0) return []; + + const last = lastOrUndefined(parameters); + if (last && isRestParameter(last)) return [last]; + + return filter(parameters, parameter => { + // ECMA-262 13.3.3.4 + return !!parameter.initializer || isBindingPattern(parameter.name); + }); + } + + function checkGrammarForUseStrictSimpleParameterList(node: FunctionLikeDeclaration): boolean { + if (languageVersion >= ScriptTarget.ES2016) { + const useStrictDirective = node.body && isBlock(node.body) && findUseStrictPrologue(node.body.statements); + if (useStrictDirective) { + const nonSimpleParameters = getNonSimpleParameters(node.parameters); + if (length(nonSimpleParameters)) { + forEach(nonSimpleParameters, parameter => { + addRelatedInfo( + error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), + createDiagnosticForNode(useStrictDirective, Diagnostics._0_is_here, "use strict directive") + ); + }); + + const diagnostics = nonSimpleParameters.map((parameter, index) => ( + index === 0 ? createDiagnosticForNode(parameter, Diagnostics._0_is_here, "parameter") : createDiagnosticForNode(parameter, Diagnostics.and_here) + )) as [DiagnosticWithLocation, ...DiagnosticWithLocation[]]; + addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics); + return true; + } + } + } + return false; + } + function checkGrammarFunctionLikeDeclaration(node: FunctionLikeDeclaration | MethodSignature): boolean { // Prevent cascading error by short-circuit const file = getSourceFileOfNode(node); return checkGrammarDecoratorsAndModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || - checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); + checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || + (isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node)); } function checkGrammarClassLikeDeclaration(node: ClassLikeDeclaration): boolean { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 73be2b46b79..9a1690ebe55 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -983,6 +983,18 @@ "category": "Error", "code": 1343 }, + "This parameter is not allowed with 'use strict' directive.": { + "category": "Error", + "code": 1344 + }, + "'use strict' directive cannot be used with non simple parameter list.": { + "category": "Error", + "code": 1345 + }, + "{0} is here.": { + "category": "Error", + "code": 1346 + }, "Duplicate identifier '{0}'.": { "category": "Error", diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 86911417cb6..09b3386d24e 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -3934,6 +3934,20 @@ namespace ts { return statementOffset; } + export function findUseStrictPrologue(statements: ReadonlyArray): Statement | undefined { + for (const statement of statements) { + if (isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + return statement; + } + } + else { + break; + } + } + return undefined; + } + export function startsWithUseStrict(statements: ReadonlyArray) { const firstStatement = firstOrUndefined(statements); return firstStatement !== undefined @@ -3947,18 +3961,7 @@ namespace ts { * @param statements An array of statements */ export function ensureUseStrict(statements: NodeArray): NodeArray { - let foundUseStrict = false; - for (const statement of statements) { - if (isPrologueDirective(statement)) { - if (isUseStrictPrologue(statement as ExpressionStatement)) { - foundUseStrict = true; - break; - } - } - else { - break; - } - } + const foundUseStrict = findUseStrictPrologue(statements); if (!foundUseStrict) { return setTextRange( diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js new file mode 100644 index 00000000000..260f0df874a --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js @@ -0,0 +1,101 @@ +//// [functionWithUseStrictAndSimpleParameterList.ts] +function a(a = 10) { + "use strict"; +} + +export var foo = 10; +function b(a = 10) { +} + +function container() { + "use strict"; + function f(a = 10) { + } +} + +function rest(...args: any[]) { + 'use strict'; +} + +function paramDefault(param = 1) { + 'use strict'; +} + +function objectBindingPattern({foo}: any) { + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; +} + + +//// [functionWithUseStrictAndSimpleParameterList.js] +"use strict"; +exports.__esModule = true; +function a(a) { + "use strict"; + if (a === void 0) { a = 10; } +} +exports.foo = 10; +function b(a) { + if (a === void 0) { a = 10; } +} +function container() { + "use strict"; + function f(a) { + if (a === void 0) { a = 10; } + } +} +function rest() { + 'use strict'; + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } +} +function paramDefault(param) { + 'use strict'; + if (param === void 0) { param = 1; } +} +function objectBindingPattern(_a) { + 'use strict'; + var foo = _a.foo; +} +function arrayBindingPattern(_a) { + 'use strict'; + var foo = _a[0]; +} +function manyParameter(a, b) { + "use strict"; + if (a === void 0) { a = 10; } + if (b === void 0) { b = 20; } +} +function manyPrologue(a, b) { + "foo"; + "use strict"; + if (a === void 0) { a = 10; } + if (b === void 0) { b = 20; } +} +function invalidPrologue(a, b) { + "foo"; + if (a === void 0) { a = 10; } + if (b === void 0) { b = 20; } + var c = 1; + "use strict"; +} diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols new file mode 100644 index 00000000000..59c8190883f --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols @@ -0,0 +1,83 @@ +=== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts === +function a(a = 10) { +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 0, 0)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 0, 11)) + + "use strict"; +} + +export var foo = 10; +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 4, 10)) + +function b(a = 10) { +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 4, 20)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 5, 11)) +} + +function container() { +>container : Symbol(container, Decl(functionWithUseStrictAndSimpleParameterList.ts, 6, 1)) + + "use strict"; + function f(a = 10) { +>f : Symbol(f, Decl(functionWithUseStrictAndSimpleParameterList.ts, 9, 17)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 10, 15)) + } +} + +function rest(...args: any[]) { +>rest : Symbol(rest, Decl(functionWithUseStrictAndSimpleParameterList.ts, 12, 1)) +>args : Symbol(args, Decl(functionWithUseStrictAndSimpleParameterList.ts, 14, 14)) + + 'use strict'; +} + +function paramDefault(param = 1) { +>paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList.ts, 16, 1)) +>param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList.ts, 18, 22)) + + 'use strict'; +} + +function objectBindingPattern({foo}: any) { +>objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 20, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 22, 31)) + + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { +>arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 24, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 26, 30)) + + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { +>manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList.ts, 28, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 30, 23)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 30, 30)) + + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { +>manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 32, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 22)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 29)) + + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { +>invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 37, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 39, 25)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 39, 32)) + + "foo"; + const c = 1; +>c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList.ts, 41, 9)) + + "use strict"; +} + diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types new file mode 100644 index 00000000000..c64c3c30036 --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types @@ -0,0 +1,109 @@ +=== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts === +function a(a = 10) { +>a : (a?: number) => void +>a : number +>10 : 10 + + "use strict"; +>"use strict" : "use strict" +} + +export var foo = 10; +>foo : number +>10 : 10 + +function b(a = 10) { +>b : (a?: number) => void +>a : number +>10 : 10 +} + +function container() { +>container : () => void + + "use strict"; +>"use strict" : "use strict" + + function f(a = 10) { +>f : (a?: number) => void +>a : number +>10 : 10 + } +} + +function rest(...args: any[]) { +>rest : (...args: any[]) => void +>args : any[] + + 'use strict'; +>'use strict' : "use strict" +} + +function paramDefault(param = 1) { +>paramDefault : (param?: number) => void +>param : number +>1 : 1 + + 'use strict'; +>'use strict' : "use strict" +} + +function objectBindingPattern({foo}: any) { +>objectBindingPattern : ({ foo }: any) => void +>foo : any + + 'use strict'; +>'use strict' : "use strict" +} + +function arrayBindingPattern([foo]: any[]) { +>arrayBindingPattern : ([foo]: any[]) => void +>foo : any + + 'use strict'; +>'use strict' : "use strict" +} + +function manyParameter(a = 10, b = 20) { +>manyParameter : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "use strict"; +>"use strict" : "use strict" +} + +function manyPrologue(a = 10, b = 20) { +>manyPrologue : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "foo"; +>"foo" : "foo" + + "use strict"; +>"use strict" : "use strict" +} + +function invalidPrologue(a = 10, b = 20) { +>invalidPrologue : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "foo"; +>"foo" : "foo" + + const c = 1; +>c : 1 +>1 : 1 + + "use strict"; +>"use strict" : "use strict" +} + diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt new file mode 100644 index 00000000000..84d69721c61 --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt @@ -0,0 +1,114 @@ +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(1,12): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(2,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(15,15): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(16,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,23): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(20,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(23,31): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(24,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(27,30): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(28,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,24): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,32): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(32,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,23): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,31): error TS1344: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(37,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. + + +==== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts (16 errors) ==== + function a(a = 10) { + ~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:2:5: use strict directive is here. + "use strict"; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:1:12: parameter is here. + } + + export var foo = 10; + function b(a = 10) { + } + + function container() { + "use strict"; + function f(a = 10) { + } + } + + function rest(...args: any[]) { + ~~~~~~~~~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:16:5: use strict directive is here. + 'use strict'; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:15:15: parameter is here. + } + + function paramDefault(param = 1) { + ~~~~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: use strict directive is here. + 'use strict'; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:23: parameter is here. + } + + function objectBindingPattern({foo}: any) { + ~~~~~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:24:5: use strict directive is here. + 'use strict'; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:23:31: parameter is here. + } + + function arrayBindingPattern([foo]: any[]) { + ~~~~~~~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:28:5: use strict directive is here. + 'use strict'; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:27:30: parameter is here. + } + + function manyParameter(a = 10, b = 20) { + ~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: use strict directive is here. + ~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: use strict directive is here. + "use strict"; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:24: parameter is here. +!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:32: and here. + } + + function manyPrologue(a = 10, b = 20) { + ~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:37:5: use strict directive is here. + ~~~~~~ +!!! error TS1344: This parameter is not allowed with 'use strict' directive. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:37:5: use strict directive is here. + "foo"; + "use strict"; + ~~~~~~~~~~~~~ +!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. +!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:23: parameter is here. +!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:31: and here. + } + + function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; + } + \ No newline at end of file diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js new file mode 100644 index 00000000000..d8e50e9d1b6 --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js @@ -0,0 +1,83 @@ +//// [functionWithUseStrictAndSimpleParameterList_es2016.ts] +function a(a = 10) { + "use strict"; +} + +export var foo = 10; +function b(a = 10) { +} + +function container() { + "use strict"; + function f(a = 10) { + } +} + +function rest(...args: any[]) { + 'use strict'; +} + +function paramDefault(param = 1) { + 'use strict'; +} + +function objectBindingPattern({foo}: any) { + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; +} + + +//// [functionWithUseStrictAndSimpleParameterList_es2016.js] +function a(a = 10) { + "use strict"; +} +export var foo = 10; +function b(a = 10) { +} +function container() { + "use strict"; + function f(a = 10) { + } +} +function rest(...args) { + 'use strict'; +} +function paramDefault(param = 1) { + 'use strict'; +} +function objectBindingPattern({ foo }) { + 'use strict'; +} +function arrayBindingPattern([foo]) { + 'use strict'; +} +function manyParameter(a = 10, b = 20) { + "use strict"; +} +function manyPrologue(a = 10, b = 20) { + "foo"; + "use strict"; +} +function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; +} diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols new file mode 100644 index 00000000000..444f219ab2f --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols @@ -0,0 +1,83 @@ +=== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts === +function a(a = 10) { +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 0, 0)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 0, 11)) + + "use strict"; +} + +export var foo = 10; +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 4, 10)) + +function b(a = 10) { +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 4, 20)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 5, 11)) +} + +function container() { +>container : Symbol(container, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 6, 1)) + + "use strict"; + function f(a = 10) { +>f : Symbol(f, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 9, 17)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 10, 15)) + } +} + +function rest(...args: any[]) { +>rest : Symbol(rest, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 12, 1)) +>args : Symbol(args, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 14, 14)) + + 'use strict'; +} + +function paramDefault(param = 1) { +>paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 16, 1)) +>param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 18, 22)) + + 'use strict'; +} + +function objectBindingPattern({foo}: any) { +>objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 20, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 22, 31)) + + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { +>arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 24, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 26, 30)) + + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { +>manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 28, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 30, 23)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 30, 30)) + + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { +>manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 32, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 22)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 29)) + + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { +>invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 37, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 39, 25)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 39, 32)) + + "foo"; + const c = 1; +>c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 41, 9)) + + "use strict"; +} + diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types new file mode 100644 index 00000000000..19f3d7f015b --- /dev/null +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types @@ -0,0 +1,109 @@ +=== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts === +function a(a = 10) { +>a : (a?: number) => void +>a : number +>10 : 10 + + "use strict"; +>"use strict" : "use strict" +} + +export var foo = 10; +>foo : number +>10 : 10 + +function b(a = 10) { +>b : (a?: number) => void +>a : number +>10 : 10 +} + +function container() { +>container : () => void + + "use strict"; +>"use strict" : "use strict" + + function f(a = 10) { +>f : (a?: number) => void +>a : number +>10 : 10 + } +} + +function rest(...args: any[]) { +>rest : (...args: any[]) => void +>args : any[] + + 'use strict'; +>'use strict' : "use strict" +} + +function paramDefault(param = 1) { +>paramDefault : (param?: number) => void +>param : number +>1 : 1 + + 'use strict'; +>'use strict' : "use strict" +} + +function objectBindingPattern({foo}: any) { +>objectBindingPattern : ({ foo }: any) => void +>foo : any + + 'use strict'; +>'use strict' : "use strict" +} + +function arrayBindingPattern([foo]: any[]) { +>arrayBindingPattern : ([foo]: any[]) => void +>foo : any + + 'use strict'; +>'use strict' : "use strict" +} + +function manyParameter(a = 10, b = 20) { +>manyParameter : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "use strict"; +>"use strict" : "use strict" +} + +function manyPrologue(a = 10, b = 20) { +>manyPrologue : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "foo"; +>"foo" : "foo" + + "use strict"; +>"use strict" : "use strict" +} + +function invalidPrologue(a = 10, b = 20) { +>invalidPrologue : (a?: number, b?: number) => void +>a : number +>10 : 10 +>b : number +>20 : 20 + + "foo"; +>"foo" : "foo" + + const c = 1; +>c : 1 +>1 : 1 + + "use strict"; +>"use strict" : "use strict" +} + diff --git a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts new file mode 100644 index 00000000000..65be76d500c --- /dev/null +++ b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts @@ -0,0 +1,44 @@ +function a(a = 10) { + "use strict"; +} + +export var foo = 10; +function b(a = 10) { +} + +function container() { + "use strict"; + function f(a = 10) { + } +} + +function rest(...args: any[]) { + 'use strict'; +} + +function paramDefault(param = 1) { + 'use strict'; +} + +function objectBindingPattern({foo}: any) { + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; +} diff --git a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts new file mode 100644 index 00000000000..ed17746931a --- /dev/null +++ b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts @@ -0,0 +1,46 @@ +// @target: es2016 + +function a(a = 10) { + "use strict"; +} + +export var foo = 10; +function b(a = 10) { +} + +function container() { + "use strict"; + function f(a = 10) { + } +} + +function rest(...args: any[]) { + 'use strict'; +} + +function paramDefault(param = 1) { + 'use strict'; +} + +function objectBindingPattern({foo}: any) { + 'use strict'; +} + +function arrayBindingPattern([foo]: any[]) { + 'use strict'; +} + +function manyParameter(a = 10, b = 20) { + "use strict"; +} + +function manyPrologue(a = 10, b = 20) { + "foo"; + "use strict"; +} + +function invalidPrologue(a = 10, b = 20) { + "foo"; + const c = 1; + "use strict"; +} From 1c522a6e994b83eda2aec3223c0850e8ac6fe0b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Fri, 20 Jul 2018 15:48:26 +0800 Subject: [PATCH 008/146] improve enum rechability check --- src/compiler/binder.ts | 6 ++--- src/compiler/checker.ts | 15 ++++++----- ...ScopedEnumVariablesUseBeforeDef.errors.txt | 16 ++++++++++++ .../blockScopedEnumVariablesUseBeforeDef.js | 22 ++++++++++++++++ ...ockScopedEnumVariablesUseBeforeDef.symbols | 26 +++++++++++++++++++ ...blockScopedEnumVariablesUseBeforeDef.types | 26 +++++++++++++++++++ ...mVariablesUseBeforeDef_preserve.errors.txt | 20 ++++++++++++++ ...copedEnumVariablesUseBeforeDef_preserve.js | 26 +++++++++++++++++++ ...EnumVariablesUseBeforeDef_preserve.symbols | 26 +++++++++++++++++++ ...edEnumVariablesUseBeforeDef_preserve.types | 26 +++++++++++++++++++ ...lockScopedVariablesUseBeforeDef.errors.txt | 3 ++- .../blockScopedVariablesUseBeforeDef.js | 3 ++- .../blockScopedVariablesUseBeforeDef.symbols | 1 + .../blockScopedVariablesUseBeforeDef.types | 1 + .../reference/reachabilityChecks1.errors.txt | 12 +-------- .../blockScopedEnumVariablesUseBeforeDef.ts | 10 +++++++ ...copedEnumVariablesUseBeforeDef_preserve.ts | 12 +++++++++ .../blockScopedVariablesUseBeforeDef.ts | 2 +- .../cases/fourslash/codeFixUnreachableCode.ts | 18 ++++++++++--- 19 files changed, 244 insertions(+), 27 deletions(-) create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.errors.txt create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.js create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.symbols create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.errors.txt create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.js create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.symbols create mode 100644 tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types create mode 100644 tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts create mode 100644 tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 7fb79b2efa2..abc4d2fc66d 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2789,9 +2789,7 @@ namespace ts { // report error on class declarations node.kind === SyntaxKind.ClassDeclaration || // report error on instantiated modules or const-enums only modules if preserveConstEnums is set - (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node)) || - // report error on regular enums and const enums if preserveConstEnums is set - (isEnumDeclaration(node) && (!isEnumConst(node) || options.preserveConstEnums)); + (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node)); if (reportError) { currentFlow = reportedUnreachableFlow; @@ -2836,7 +2834,7 @@ namespace ts { // As opposed to a pure declaration like an `interface` function isExecutableStatement(s: Statement): boolean { // Don't remove statements that can validly be used before they appear. - return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && + return !isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !isEnumDeclaration(s) && // `var x;` may declare a variable used above !(isVariableStatement(s) && !(getCombinedNodeFlags(s) & (NodeFlags.Let | NodeFlags.Const)) && s.declarationList.declarations.some(d => !d.initializer)); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e01c97af492..9d2c133704a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1679,6 +1679,9 @@ namespace ts { } else { Debug.assert(!!(result.flags & SymbolFlags.ConstEnum)); + if (compilerOptions.preserveConstEnums) { + diagnosticMessage = error(errorLocation, Diagnostics.Class_0_used_before_its_declaration, declarationName); + } } if (diagnosticMessage) { @@ -22786,6 +22789,12 @@ namespace ts { } } + const enum DeclarationSpaces { + None = 0, + ExportValue = 1 << 0, + ExportType = 1 << 1, + ExportNamespace = 1 << 2, + } function checkExportsOnMergedDeclarations(node: Node): void { if (!produceDiagnostics) { return; @@ -22850,12 +22859,6 @@ namespace ts { } } - const enum DeclarationSpaces { - None = 0, - ExportValue = 1 << 0, - ExportType = 1 << 1, - ExportNamespace = 1 << 2, - } function getDeclarationSpaces(decl: Declaration): DeclarationSpaces { let d = decl as Node; switch (d.kind) { diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.errors.txt b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.errors.txt new file mode 100644 index 00000000000..5927caba434 --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.errors.txt @@ -0,0 +1,16 @@ +tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts(2,12): error TS2450: Enum 'E' used before its declaration. + + +==== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts (1 errors) ==== + function foo1() { + return E.A + ~ +!!! error TS2450: Enum 'E' used before its declaration. +!!! related TS2728 tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts:3:10: 'E' is declared here. + enum E { A } + } + + function foo2() { + return E.A + const enum E { A } + } \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.js b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.js new file mode 100644 index 00000000000..552d099b07c --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.js @@ -0,0 +1,22 @@ +//// [blockScopedEnumVariablesUseBeforeDef.ts] +function foo1() { + return E.A + enum E { A } +} + +function foo2() { + return E.A + const enum E { A } +} + +//// [blockScopedEnumVariablesUseBeforeDef.js] +function foo1() { + return E.A; + var E; + (function (E) { + E[E["A"] = 0] = "A"; + })(E || (E = {})); +} +function foo2() { + return 0 /* A */; +} diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.symbols b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.symbols new file mode 100644 index 00000000000..73f8419c8c1 --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts === +function foo1() { +>foo1 : Symbol(foo1, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 0, 0)) + + return E.A +>E.A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 2, 12)) +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 1, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 2, 12)) + + enum E { A } +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 1, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 2, 12)) +} + +function foo2() { +>foo2 : Symbol(foo2, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 3, 1)) + + return E.A +>E.A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 7, 18)) +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 6, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 7, 18)) + + const enum E { A } +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 6, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef.ts, 7, 18)) +} diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types new file mode 100644 index 00000000000..5c4dc43f774 --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts === +function foo1() { +>foo1 : () => E + + return E.A +>E.A : E +>E : typeof E +>A : E + + enum E { A } +>E : E +>A : E +} + +function foo2() { +>foo2 : () => E + + return E.A +>E.A : E +>E : typeof E +>A : E + + const enum E { A } +>E : E +>A : E +} diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.errors.txt b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.errors.txt new file mode 100644 index 00000000000..94b2ff97d9f --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.errors.txt @@ -0,0 +1,20 @@ +tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts(2,12): error TS2450: Enum 'E' used before its declaration. +tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts(7,12): error TS2449: Class 'E' used before its declaration. + + +==== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts (2 errors) ==== + function foo1() { + return E.A + ~ +!!! error TS2450: Enum 'E' used before its declaration. +!!! related TS2728 tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts:3:10: 'E' is declared here. + enum E { A } + } + + function foo2() { + return E.A + ~ +!!! error TS2449: Class 'E' used before its declaration. +!!! related TS2728 tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts:8:16: 'E' is declared here. + const enum E { A } + } \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.js b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.js new file mode 100644 index 00000000000..239a87f0042 --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.js @@ -0,0 +1,26 @@ +//// [blockScopedEnumVariablesUseBeforeDef_preserve.ts] +function foo1() { + return E.A + enum E { A } +} + +function foo2() { + return E.A + const enum E { A } +} + +//// [blockScopedEnumVariablesUseBeforeDef_preserve.js] +function foo1() { + return E.A; + var E; + (function (E) { + E[E["A"] = 0] = "A"; + })(E || (E = {})); +} +function foo2() { + return 0 /* A */; + var E; + (function (E) { + E[E["A"] = 0] = "A"; + })(E || (E = {})); +} diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.symbols b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.symbols new file mode 100644 index 00000000000..b76089c0a0f --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.symbols @@ -0,0 +1,26 @@ +=== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts === +function foo1() { +>foo1 : Symbol(foo1, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 0, 0)) + + return E.A +>E.A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 2, 12)) +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 1, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 2, 12)) + + enum E { A } +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 1, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 2, 12)) +} + +function foo2() { +>foo2 : Symbol(foo2, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 3, 1)) + + return E.A +>E.A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 7, 18)) +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 6, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 7, 18)) + + const enum E { A } +>E : Symbol(E, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 6, 14)) +>A : Symbol(E.A, Decl(blockScopedEnumVariablesUseBeforeDef_preserve.ts, 7, 18)) +} diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types new file mode 100644 index 00000000000..5194114112e --- /dev/null +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts === +function foo1() { +>foo1 : () => E + + return E.A +>E.A : E +>E : typeof E +>A : E + + enum E { A } +>E : E +>A : E +} + +function foo2() { +>foo2 : () => E + + return E.A +>E.A : E +>E : typeof E +>A : E + + const enum E { A } +>E : E +>A : E +} diff --git a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.errors.txt b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.errors.txt index 4de97fa02a4..91bd5dde00c 100644 --- a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.errors.txt +++ b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.errors.txt @@ -119,4 +119,5 @@ tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts(100,12): error TS2448: !!! related TS2728 tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts:102:9: 'x' is declared here. } let x - } \ No newline at end of file + } + \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.js b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.js index b14ea2a3069..7e6b452302b 100644 --- a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.js +++ b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.js @@ -101,7 +101,8 @@ function foo14() { a: x } let x -} +} + //// [blockScopedVariablesUseBeforeDef.js] function foo0() { diff --git a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.symbols b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.symbols index 9dcb26712fb..83cb91db1d0 100644 --- a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.symbols +++ b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.symbols @@ -212,3 +212,4 @@ function foo14() { let x >x : Symbol(x, Decl(blockScopedVariablesUseBeforeDef.ts, 101, 7)) } + diff --git a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.types b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.types index 771518e5901..3098b8c0f91 100644 --- a/tests/baselines/reference/blockScopedVariablesUseBeforeDef.types +++ b/tests/baselines/reference/blockScopedVariablesUseBeforeDef.types @@ -224,3 +224,4 @@ function foo14() { let x >x : any } + diff --git a/tests/baselines/reference/reachabilityChecks1.errors.txt b/tests/baselines/reference/reachabilityChecks1.errors.txt index 041d10bfecd..97fd5302d45 100644 --- a/tests/baselines/reference/reachabilityChecks1.errors.txt +++ b/tests/baselines/reference/reachabilityChecks1.errors.txt @@ -3,11 +3,9 @@ tests/cases/compiler/reachabilityChecks1.ts(6,5): error TS7027: Unreachable code tests/cases/compiler/reachabilityChecks1.ts(18,5): error TS7027: Unreachable code detected. tests/cases/compiler/reachabilityChecks1.ts(30,5): error TS7027: Unreachable code detected. tests/cases/compiler/reachabilityChecks1.ts(47,5): error TS7027: Unreachable code detected. -tests/cases/compiler/reachabilityChecks1.ts(60,5): error TS7027: Unreachable code detected. -tests/cases/compiler/reachabilityChecks1.ts(69,5): error TS7027: Unreachable code detected. -==== tests/cases/compiler/reachabilityChecks1.ts (7 errors) ==== +==== tests/cases/compiler/reachabilityChecks1.ts (5 errors) ==== while (true); var x = 1; ~~~~~~~~~~ @@ -83,12 +81,8 @@ tests/cases/compiler/reachabilityChecks1.ts(69,5): error TS7027: Unreachable cod do { } while (true); enum E { - ~~~~~~~~ X = 1 - ~~~~~~~~~~~~~ } - ~~~~~ -!!! error TS7027: Unreachable code detected. } function f4() { @@ -96,12 +90,8 @@ tests/cases/compiler/reachabilityChecks1.ts(69,5): error TS7027: Unreachable cod throw new Error(); } const enum E { - ~~~~~~~~~~~~~~ X = 1 - ~~~~~~~~~~~~~ } - ~~~~~ -!!! error TS7027: Unreachable code detected. } \ No newline at end of file diff --git a/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts b/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts new file mode 100644 index 00000000000..84eff340164 --- /dev/null +++ b/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef.ts @@ -0,0 +1,10 @@ +// @target: ES5 +function foo1() { + return E.A + enum E { A } +} + +function foo2() { + return E.A + const enum E { A } +} \ No newline at end of file diff --git a/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts b/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts new file mode 100644 index 00000000000..0d7cb73b3ad --- /dev/null +++ b/tests/cases/compiler/blockScopedEnumVariablesUseBeforeDef_preserve.ts @@ -0,0 +1,12 @@ +// @target: ES5 +// @preserveConstEnums: true + +function foo1() { + return E.A + enum E { A } +} + +function foo2() { + return E.A + const enum E { A } +} \ No newline at end of file diff --git a/tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts b/tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts index 956705bd7d3..351bdde122e 100644 --- a/tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts +++ b/tests/cases/compiler/blockScopedVariablesUseBeforeDef.ts @@ -101,4 +101,4 @@ function foo14() { a: x } let x -} \ No newline at end of file +} diff --git a/tests/cases/fourslash/codeFixUnreachableCode.ts b/tests/cases/fourslash/codeFixUnreachableCode.ts index 9c9eea6dae4..eb5731081e7 100644 --- a/tests/cases/fourslash/codeFixUnreachableCode.ts +++ b/tests/cases/fourslash/codeFixUnreachableCode.ts @@ -3,12 +3,12 @@ ////function f() { //// return f(); //// [|return 1;|] -//// function f() {} +//// function f(a?: EE) { return a; } //// [|return 2;|] //// type T = number; //// interface I {} //// const enum E {} -//// [|enum E {}|] +//// enum EE {} //// namespace N { export type T = number; } //// [|namespace N { export const x: T = 0; }|] //// var x: I; @@ -29,11 +29,23 @@ verify.codeFixAll({ newFileContent: `function f() { return f(); - function f() {} + function f(a?: EE) { return a; } type T = number; interface I {} const enum E {} + enum EE {} namespace N { export type T = number; } var x: I; }`, }); + +function f() { + return f(); + function f(a?: EE) { return a; } + type T = number; + interface I {} + const enum E {} + enum EE {} + namespace N { export type T = number; } + var x: I; +} \ No newline at end of file From 02f5365e080686c9b89b3dc55abf27267eaf2a96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Wed, 1 Aug 2018 10:21:50 +0800 Subject: [PATCH 009/146] improve error message and update testcase --- src/compiler/checker.ts | 15 +-- src/compiler/diagnosticMessages.json | 8 +- ...tionWithUseStrictAndSimpleParameterList.js | 12 ++ ...ithUseStrictAndSimpleParameterList.symbols | 40 +++--- ...nWithUseStrictAndSimpleParameterList.types | 10 ++ ...ctAndSimpleParameterList_es2016.errors.txt | 119 ++++++++++-------- ...hUseStrictAndSimpleParameterList_es2016.js | 7 ++ ...trictAndSimpleParameterList_es2016.symbols | 40 +++--- ...eStrictAndSimpleParameterList_es2016.types | 10 ++ ...tionWithUseStrictAndSimpleParameterList.ts | 4 + ...hUseStrictAndSimpleParameterList_es2016.ts | 4 + 11 files changed, 172 insertions(+), 97 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index de9521031f6..eaf18a5078f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28717,16 +28717,7 @@ namespace ts { } function getNonSimpleParameters(parameters: ReadonlyArray): ReadonlyArray { - // ECMA-262 14.1.13 - if (parameters.length === 0) return []; - - const last = lastOrUndefined(parameters); - if (last && isRestParameter(last)) return [last]; - - return filter(parameters, parameter => { - // ECMA-262 13.3.3.4 - return !!parameter.initializer || isBindingPattern(parameter.name); - }); + return filter(parameters, parameter => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter)); } function checkGrammarForUseStrictSimpleParameterList(node: FunctionLikeDeclaration): boolean { @@ -28738,12 +28729,12 @@ namespace ts { forEach(nonSimpleParameters, parameter => { addRelatedInfo( error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive), - createDiagnosticForNode(useStrictDirective, Diagnostics._0_is_here, "use strict directive") + createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here) ); }); const diagnostics = nonSimpleParameters.map((parameter, index) => ( - index === 0 ? createDiagnosticForNode(parameter, Diagnostics._0_is_here, "parameter") : createDiagnosticForNode(parameter, Diagnostics.and_here) + index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here) )) as [DiagnosticWithLocation, ...DiagnosticWithLocation[]]; addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics); return true; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 0831ab7fba2..0a35bb0e85b 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -991,14 +991,18 @@ "category": "Error", "code": 1345 }, - "'use strict' directive cannot be used with non simple parameter list.": { + "'use strict' directive cannot be used with non-simple parameter list.": { "category": "Error", "code": 1346 }, - "{0} is here.": { + "Non-simple parameter declared here.": { "category": "Error", "code": 1347 }, + "'use strict' directive used here.": { + "category": "Error", + "code": 1348 + }, "Duplicate identifier '{0}'.": { "category": "Error", diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js index 260f0df874a..1cf35579976 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.js @@ -17,6 +17,10 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { + 'use strict'; +} + function paramDefault(param = 1) { 'use strict'; } @@ -69,6 +73,14 @@ function rest() { args[_i] = arguments[_i]; } } +function rest1(a) { + 'use strict'; + if (a === void 0) { a = 1; } + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } +} function paramDefault(param) { 'use strict'; if (param === void 0) { param = 1; } diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols index 59c8190883f..9c2ad86d974 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.symbols @@ -31,52 +31,60 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { +>rest1 : Symbol(rest1, Decl(functionWithUseStrictAndSimpleParameterList.ts, 16, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 18, 15)) +>args : Symbol(args, Decl(functionWithUseStrictAndSimpleParameterList.ts, 18, 21)) + + 'use strict'; +} + function paramDefault(param = 1) { ->paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList.ts, 16, 1)) ->param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList.ts, 18, 22)) +>paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList.ts, 20, 1)) +>param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList.ts, 22, 22)) 'use strict'; } function objectBindingPattern({foo}: any) { ->objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 20, 1)) ->foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 22, 31)) +>objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 24, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 26, 31)) 'use strict'; } function arrayBindingPattern([foo]: any[]) { ->arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 24, 1)) ->foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 26, 30)) +>arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList.ts, 28, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList.ts, 30, 30)) 'use strict'; } function manyParameter(a = 10, b = 20) { ->manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList.ts, 28, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 30, 23)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 30, 30)) +>manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList.ts, 32, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 23)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 30)) "use strict"; } function manyPrologue(a = 10, b = 20) { ->manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 32, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 22)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 34, 29)) +>manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 36, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 38, 22)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 38, 29)) "foo"; "use strict"; } function invalidPrologue(a = 10, b = 20) { ->invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 37, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 39, 25)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 39, 32)) +>invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList.ts, 41, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList.ts, 43, 25)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList.ts, 43, 32)) "foo"; const c = 1; ->c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList.ts, 41, 9)) +>c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList.ts, 45, 9)) "use strict"; } diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types index c64c3c30036..462086d28ad 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList.types @@ -39,6 +39,16 @@ function rest(...args: any[]) { >'use strict' : "use strict" } +function rest1(a = 1, ...args) { +>rest1 : (a?: number, ...args: any[]) => void +>a : number +>1 : 1 +>args : any[] + + 'use strict'; +>'use strict' : "use strict" +} + function paramDefault(param = 1) { >paramDefault : (param?: number) => void >param : number diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt index 84d69721c61..4887cb4f07a 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt @@ -1,30 +1,33 @@ -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(1,12): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(2,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(15,15): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(16,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,23): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(20,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(23,31): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(24,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(27,30): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(28,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,24): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,32): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(32,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,23): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,31): error TS1344: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(37,5): error TS1345: 'use strict' directive cannot be used with non simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(1,12): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(2,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(15,15): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(16,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,16): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,23): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(20,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(23,23): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(24,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(27,31): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(28,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,30): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(32,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,24): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,32): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(36,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,23): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,31): error TS1345: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(41,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -==== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts (16 errors) ==== +==== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts (19 errors) ==== function a(a = 10) { ~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:2:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:2:5: 'use strict' directive used here. "use strict"; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:1:12: parameter is here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:1:12: Non-simple parameter declared here. } export var foo = 10; @@ -39,71 +42,85 @@ tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es function rest(...args: any[]) { ~~~~~~~~~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:16:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:16:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:15:15: parameter is here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:15:15: Non-simple parameter declared here. + } + + function rest1(a = 1, ...args) { + ~~~~~ +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. + ~~~~~~~ +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. + 'use strict'; + ~~~~~~~~~~~~~ +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:16: Non-simple parameter declared here. +!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:23: and here. } function paramDefault(param = 1) { ~~~~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:24:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:23: parameter is here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:23:23: Non-simple parameter declared here. } function objectBindingPattern({foo}: any) { ~~~~~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:24:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:28:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:23:31: parameter is here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:27:31: Non-simple parameter declared here. } function arrayBindingPattern([foo]: any[]) { ~~~~~~~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:28:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:27:30: parameter is here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:30: Non-simple parameter declared here. } function manyParameter(a = 10, b = 20) { ~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. ~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. "use strict"; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:24: parameter is here. -!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:32: and here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:24: Non-simple parameter declared here. +!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:32: and here. } function manyPrologue(a = 10, b = 20) { ~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:37:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. ~~~~~~ -!!! error TS1344: This parameter is not allowed with 'use strict' directive. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:37:5: use strict directive is here. +!!! error TS1345: This parameter is not allowed with 'use strict' directive. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. "foo"; "use strict"; ~~~~~~~~~~~~~ -!!! error TS1345: 'use strict' directive cannot be used with non simple parameter list. -!!! related TS1346 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:23: parameter is here. -!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:31: and here. +!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:39:23: Non-simple parameter declared here. +!!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:39:31: and here. } function invalidPrologue(a = 10, b = 20) { diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js index d8e50e9d1b6..f9e07fc96ea 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.js @@ -17,6 +17,10 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { + 'use strict'; +} + function paramDefault(param = 1) { 'use strict'; } @@ -60,6 +64,9 @@ function container() { function rest(...args) { 'use strict'; } +function rest1(a = 1, ...args) { + 'use strict'; +} function paramDefault(param = 1) { 'use strict'; } diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols index 444f219ab2f..8f3d1366ad2 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.symbols @@ -31,52 +31,60 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { +>rest1 : Symbol(rest1, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 16, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 18, 15)) +>args : Symbol(args, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 18, 21)) + + 'use strict'; +} + function paramDefault(param = 1) { ->paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 16, 1)) ->param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 18, 22)) +>paramDefault : Symbol(paramDefault, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 20, 1)) +>param : Symbol(param, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 22, 22)) 'use strict'; } function objectBindingPattern({foo}: any) { ->objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 20, 1)) ->foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 22, 31)) +>objectBindingPattern : Symbol(objectBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 24, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 26, 31)) 'use strict'; } function arrayBindingPattern([foo]: any[]) { ->arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 24, 1)) ->foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 26, 30)) +>arrayBindingPattern : Symbol(arrayBindingPattern, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 28, 1)) +>foo : Symbol(foo, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 30, 30)) 'use strict'; } function manyParameter(a = 10, b = 20) { ->manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 28, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 30, 23)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 30, 30)) +>manyParameter : Symbol(manyParameter, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 32, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 23)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 30)) "use strict"; } function manyPrologue(a = 10, b = 20) { ->manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 32, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 22)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 34, 29)) +>manyPrologue : Symbol(manyPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 36, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 38, 22)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 38, 29)) "foo"; "use strict"; } function invalidPrologue(a = 10, b = 20) { ->invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 37, 1)) ->a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 39, 25)) ->b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 39, 32)) +>invalidPrologue : Symbol(invalidPrologue, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 41, 1)) +>a : Symbol(a, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 43, 25)) +>b : Symbol(b, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 43, 32)) "foo"; const c = 1; ->c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 41, 9)) +>c : Symbol(c, Decl(functionWithUseStrictAndSimpleParameterList_es2016.ts, 45, 9)) "use strict"; } diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types index 19f3d7f015b..c5268cd8e48 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.types @@ -39,6 +39,16 @@ function rest(...args: any[]) { >'use strict' : "use strict" } +function rest1(a = 1, ...args) { +>rest1 : (a?: number, ...args: any[]) => void +>a : number +>1 : 1 +>args : any[] + + 'use strict'; +>'use strict' : "use strict" +} + function paramDefault(param = 1) { >paramDefault : (param?: number) => void >param : number diff --git a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts index 65be76d500c..d4b8ced9b42 100644 --- a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts +++ b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList.ts @@ -16,6 +16,10 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { + 'use strict'; +} + function paramDefault(param = 1) { 'use strict'; } diff --git a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts index ed17746931a..6c9fadd1ac1 100644 --- a/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts +++ b/tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts @@ -18,6 +18,10 @@ function rest(...args: any[]) { 'use strict'; } +function rest1(a = 1, ...args) { + 'use strict'; +} + function paramDefault(param = 1) { 'use strict'; } From 23640d971b09c8cf931cb59292b40ce96692a5db Mon Sep 17 00:00:00 2001 From: Rhys van der Waerden Date: Wed, 1 Aug 2018 16:44:53 +1000 Subject: [PATCH 010/146] Fix issue with Array#flatMap callback return type Closes #22685 --- src/lib/esnext.array.d.ts | 4 +-- tests/baselines/reference/arrayFlatMap.js | 12 +++++++++ .../baselines/reference/arrayFlatMap.symbols | 20 +++++++++++++++ tests/baselines/reference/arrayFlatMap.types | 25 +++++++++++++++++++ tests/cases/compiler/arrayFlatMap.ts | 6 +++++ 5 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/arrayFlatMap.js create mode 100644 tests/baselines/reference/arrayFlatMap.symbols create mode 100644 tests/baselines/reference/arrayFlatMap.types create mode 100644 tests/cases/compiler/arrayFlatMap.ts diff --git a/src/lib/esnext.array.d.ts b/src/lib/esnext.array.d.ts index b602e8cc0e8..33bee0c205e 100644 --- a/src/lib/esnext.array.d.ts +++ b/src/lib/esnext.array.d.ts @@ -11,7 +11,7 @@ interface ReadonlyArray { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] @@ -125,7 +125,7 @@ interface Array { * thisArg is omitted, undefined is used as the this value. */ flatMap ( - callback: (this: This, value: T, index: number, array: T[]) => U|U[], + callback: (this: This, value: T, index: number, array: T[]) => U|ReadonlyArray, thisArg?: This ): U[] diff --git a/tests/baselines/reference/arrayFlatMap.js b/tests/baselines/reference/arrayFlatMap.js new file mode 100644 index 00000000000..3c35cedc1f3 --- /dev/null +++ b/tests/baselines/reference/arrayFlatMap.js @@ -0,0 +1,12 @@ +//// [arrayFlatMap.ts] +const array: number[] = []; +const readonlyArray: ReadonlyArray = []; +array.flatMap((): ReadonlyArray => []); // ok +readonlyArray.flatMap((): ReadonlyArray => []); // ok + + +//// [arrayFlatMap.js] +var array = []; +var readonlyArray = []; +array.flatMap(function () { return []; }); // ok +readonlyArray.flatMap(function () { return []; }); // ok diff --git a/tests/baselines/reference/arrayFlatMap.symbols b/tests/baselines/reference/arrayFlatMap.symbols new file mode 100644 index 00000000000..0a97341657b --- /dev/null +++ b/tests/baselines/reference/arrayFlatMap.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/arrayFlatMap.ts === +const array: number[] = []; +>array : Symbol(array, Decl(arrayFlatMap.ts, 0, 5)) + +const readonlyArray: ReadonlyArray = []; +>readonlyArray : Symbol(readonlyArray, Decl(arrayFlatMap.ts, 1, 5)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) + +array.flatMap((): ReadonlyArray => []); // ok +>array.flatMap : Symbol(Array.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>array : Symbol(array, Decl(arrayFlatMap.ts, 0, 5)) +>flatMap : Symbol(Array.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) + +readonlyArray.flatMap((): ReadonlyArray => []); // ok +>readonlyArray.flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>readonlyArray : Symbol(readonlyArray, Decl(arrayFlatMap.ts, 1, 5)) +>flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) + diff --git a/tests/baselines/reference/arrayFlatMap.types b/tests/baselines/reference/arrayFlatMap.types new file mode 100644 index 00000000000..7eb4d444ecf --- /dev/null +++ b/tests/baselines/reference/arrayFlatMap.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/arrayFlatMap.ts === +const array: number[] = []; +>array : number[] +>[] : undefined[] + +const readonlyArray: ReadonlyArray = []; +>readonlyArray : ReadonlyArray +>[] : undefined[] + +array.flatMap((): ReadonlyArray => []); // ok +>array.flatMap((): ReadonlyArray => []) : number[] +>array.flatMap : (callback: (this: This, value: number, index: number, array: number[]) => U | ReadonlyArray, thisArg?: This) => U[] +>array : number[] +>flatMap : (callback: (this: This, value: number, index: number, array: number[]) => U | ReadonlyArray, thisArg?: This) => U[] +>(): ReadonlyArray => [] : () => ReadonlyArray +>[] : undefined[] + +readonlyArray.flatMap((): ReadonlyArray => []); // ok +>readonlyArray.flatMap((): ReadonlyArray => []) : number[] +>readonlyArray.flatMap : (callback: (this: This, value: number, index: number, array: number[]) => U | ReadonlyArray, thisArg?: This) => U[] +>readonlyArray : ReadonlyArray +>flatMap : (callback: (this: This, value: number, index: number, array: number[]) => U | ReadonlyArray, thisArg?: This) => U[] +>(): ReadonlyArray => [] : () => ReadonlyArray +>[] : undefined[] + diff --git a/tests/cases/compiler/arrayFlatMap.ts b/tests/cases/compiler/arrayFlatMap.ts new file mode 100644 index 00000000000..dc67bf02490 --- /dev/null +++ b/tests/cases/compiler/arrayFlatMap.ts @@ -0,0 +1,6 @@ +// @lib: esnext + +const array: number[] = []; +const readonlyArray: ReadonlyArray = []; +array.flatMap((): ReadonlyArray => []); // ok +readonlyArray.flatMap((): ReadonlyArray => []); // ok From 6df61272f3058db3c13f820009f8a2595d47a5a7 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Fri, 3 Aug 2018 17:54:15 +0200 Subject: [PATCH 011/146] createProgram: don't use TypeChecker Avoids using the TypeChecker when trying to reuse the Program structure. This allows SourceFiles contained in the old Program to be updated using ts.updateSourceFile Fixes: #26166 --- src/compiler/program.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c70477b4a17..14063029c59 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -951,8 +951,11 @@ namespace ts { // If we change our policy of rechecking failed lookups on each program create, // we should adjust the value returned here. function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, oldProgramState: OldProgramState): boolean { + if (!oldProgramState.program) { + return false; + } const resolutionToFile = getResolvedModule(oldProgramState.oldSourceFile!, moduleName); // TODO: GH#18217 - const resolvedFile = resolutionToFile && oldProgramState.program && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); + const resolvedFile = resolutionToFile && oldProgramState.program.getSourceFile(resolutionToFile.resolvedFileName); if (resolutionToFile && resolvedFile && !resolvedFile.externalModuleIndicator) { // In the old program, we resolved to an ambient module that was in the same // place as we expected to find an actual module file. @@ -960,16 +963,11 @@ namespace ts { // because the normal module resolution algorithm will find this anyway. return false; } - const ambientModule = oldProgramState.program && oldProgramState.program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(moduleName); - if (!(ambientModule && ambientModule.declarations)) { - return false; - } // at least one of declarations should come from non-modified source file - const firstUnmodifiedFile = forEach(ambientModule.declarations, d => { - const f = getSourceFileOfNode(d); - return !contains(oldProgramState.modifiedFilePaths, f.path) && f; - }); + const firstUnmodifiedFile = oldProgramState.program.getSourceFiles().find( + f => !contains(oldProgramState.modifiedFilePaths, f.path) && contains(f.ambientModuleNames, moduleName) + ); if (!firstUnmodifiedFile) { return false; From a1978eb8a1e2d6697230299fb29d250582af124d Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Fri, 3 Aug 2018 22:09:53 +0200 Subject: [PATCH 012/146] add test --- .../unittests/reuseProgramStructure.ts | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index 44082f3a302..cf0881dfefa 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -399,6 +399,29 @@ namespace ts { assert.isDefined(program2.getSourceFile("/a.ts")!.resolvedModules!.get("a"), "'a' is not an unresolved module after re-use"); }); + it("works with updated SourceFiles", () => { + const files = [ + { name: "/a.ts", text: SourceText.New("", "", 'import * as a from "a";a;') }, + { name: "/types/zzz/index.d.ts", text: SourceText.New("", "", 'declare module "a" { }') }, + ]; + const host = createTestCompilerHost(files, target); + const options: CompilerOptions = { target, typeRoots: ["/types"] }; + const program1 = createProgram(["/a.ts"], options, host); + let sourceFile = program1.getSourceFile("/a.ts")!; + assert.isDefined(sourceFile, "'/a.ts' is included in the program"); + sourceFile = updateSourceFile(sourceFile, "'use strict';" + sourceFile.text, { newLength: "'use strict';".length, span: { start: 0, length: 0 } }); + assert.strictEqual(sourceFile.statements[2].getSourceFile(), sourceFile, "parent pointers are updated"); + const updateHost: TestCompilerHost = { + ...host, + getSourceFile(fileName) { + return fileName === sourceFile.fileName ? sourceFile : program1.getSourceFile(fileName); + } + }; + const program2 = createProgram(["/a.ts"], options, updateHost, program1); + assert.isDefined(program2.getSourceFile("/a.ts")!.resolvedModules!.get("a"), "'a' is not an unresolved module after re-use"); + assert.strictEqual(sourceFile.statements[2].getSourceFile(), sourceFile, "parent pointers are not altered"); + }); + it("resolved type directives cache follows type directives", () => { const files = [ { name: "/a.ts", text: SourceText.New("/// ", "", "var x = $") }, From 3b022a4e6633e79a1cf79e0b4bb13132864a9668 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Fri, 3 Aug 2018 23:19:04 +0200 Subject: [PATCH 013/146] add link to issue --- src/testRunner/unittests/reuseProgramStructure.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index cf0881dfefa..23d658ad483 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -400,6 +400,7 @@ namespace ts { }); it("works with updated SourceFiles", () => { + // adapted repro from https://github.com/Microsoft/TypeScript/issues/26166 const files = [ { name: "/a.ts", text: SourceText.New("", "", 'import * as a from "a";a;') }, { name: "/types/zzz/index.d.ts", text: SourceText.New("", "", 'declare module "a" { }') }, From 711b5660cbe1cb715d34713461821733a6af0e40 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Wed, 8 Aug 2018 21:16:09 +0200 Subject: [PATCH 014/146] unittests/moduleResolution: actually assert in checkResolvedModule this change uncovered a bug in testPreserveSymlinks which always silently failed --- src/testRunner/unittests/moduleResolution.ts | 29 +++++++++++++------ .../unittests/reuseProgramStructure.ts | 13 +++------ 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index e97a3f5fc42..52c11d04fd9 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -1,14 +1,21 @@ namespace ts { - export function checkResolvedModule(expected: ResolvedModuleFull | undefined, actual: ResolvedModuleFull): boolean { - if (!expected === !actual) { - if (expected) { - assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`); - assert.isTrue(expected.extension === actual.extension, `'ext': expected '${expected.extension}' to be equal to '${actual.extension}'`); - assert.isTrue(expected.isExternalLibraryImport === actual.isExternalLibraryImport, `'isExternalLibraryImport': expected '${expected.isExternalLibraryImport}' to be equal to '${actual.isExternalLibraryImport}'`); + export function checkResolvedModule(actual: ResolvedModuleFull | undefined, expected: ResolvedModuleFull | undefined): boolean { + if (!expected) { + if (actual) { + assert.fail(actual, expected, "expected resolved module to be undefined"); + return false; } return true; } - return false; + else if (!actual) { + assert.fail(actual, expected, "expected resolved module to be defined"); + return false; + } + + assert.isTrue(actual.resolvedFileName === expected.resolvedFileName, `'resolvedFileName': expected '${actual.resolvedFileName}' to be equal to '${expected.resolvedFileName}'`); + assert.isTrue(actual.extension === expected.extension, `'ext': expected '${actual.extension}' to be equal to '${expected.extension}'`); + assert.isTrue(actual.isExternalLibraryImport === expected.isExternalLibraryImport, `'isExternalLibraryImport': expected '${actual.isExternalLibraryImport}' to be equal to '${expected.isExternalLibraryImport}'`); + return true; } export function checkResolvedModuleWithFailedLookupLocations(actual: ResolvedModuleWithFailedLookupLocations, expectedResolvedModule: ResolvedModuleFull, expectedFailedLookupLocations: string[]): void { @@ -314,8 +321,12 @@ namespace ts { function testPreserveSymlinks(preserveSymlinks: boolean) { it(`preserveSymlinks: ${preserveSymlinks}`, () => { const realFileName = "/linked/index.d.ts"; - const symlinkFileName = "/app/node_modulex/linked/index.d.ts"; - const host = createModuleResolutionHost(/*hasDirectoryExists*/ true, { name: realFileName, symlinks: [symlinkFileName] }); + const symlinkFileName = "/app/node_modules/linked/index.d.ts"; + const host = createModuleResolutionHost( + /*hasDirectoryExists*/ true, + { name: realFileName, symlinks: [symlinkFileName] }, + { name: "/app/node_modules/linked/package.json", content: '{"version": "0.0.0", "main": "./index"}' }, + ); const resolution = nodeModuleNameResolver("linked", "/app/app.ts", { preserveSymlinks }, host); const resolvedFileName = preserveSymlinks ? symlinkFileName : realFileName; checkResolvedModule(resolution.resolvedModule, createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ true)); diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index 44082f3a302..63095e3c018 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -177,15 +177,10 @@ namespace ts { file.text = file.text.updateProgram(newProgramText); } - function checkResolvedTypeDirective(expected: ResolvedTypeReferenceDirective, actual: ResolvedTypeReferenceDirective): boolean { - if (!expected === !actual) { - if (expected) { - assert.equal(expected.resolvedFileName, actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`); - assert.equal(expected.primary, actual.primary, `'primary': expected '${expected.primary}' to be equal to '${actual.primary}'`); - } - return true; - } - return false; + function checkResolvedTypeDirective(actual: ResolvedTypeReferenceDirective, expected: ResolvedTypeReferenceDirective) { + assert.equal(actual.resolvedFileName, expected.resolvedFileName, `'resolvedFileName': expected '${actual.resolvedFileName}' to be equal to '${expected.resolvedFileName}'`); + assert.equal(actual.primary, expected.primary, `'primary': expected '${actual.primary}' to be equal to '${expected.primary}'`); + return true; } function checkCache(caption: string, program: Program, fileName: string, expectedContent: Map | undefined, getCache: (f: SourceFile) => Map | undefined, entryChecker: (expected: T, original: T) => boolean): void { From 6432bd9defc25917a0f55b9440a9321e61e81482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Wed, 8 Aug 2018 16:01:15 +0800 Subject: [PATCH 015/146] check index access for fixed length tuple --- src/compiler/checker.ts | 7 +++ src/compiler/diagnosticMessages.json | 4 ++ .../bestCommonTypeOfTuple.errors.txt | 40 +++++++++++++++ .../bestCommonTypeOfTuple2.errors.txt | 40 +++++++++++++++ .../reference/castingTuple.errors.txt | 5 +- .../emptyTuplesTypeAssertion01.errors.txt | 8 +++ .../emptyTuplesTypeAssertion02.errors.txt | 8 +++ .../genericCallWithTupleType.errors.txt | 11 ++++- .../reference/indexerWithTuple.errors.txt | 47 ++++++++++++++++++ .../reference/tupleLengthCheck.errors.txt | 21 ++++++++ tests/baselines/reference/tupleLengthCheck.js | 22 +++++++++ .../reference/tupleLengthCheck.symbols | 37 ++++++++++++++ .../reference/tupleLengthCheck.types | 49 +++++++++++++++++++ .../baselines/reference/tupleTypes.errors.txt | 8 ++- .../types/tuple/tupleLengthCheck.ts | 11 +++++ 15 files changed, 315 insertions(+), 3 deletions(-) create mode 100644 tests/baselines/reference/bestCommonTypeOfTuple.errors.txt create mode 100644 tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt create mode 100644 tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt create mode 100644 tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt create mode 100644 tests/baselines/reference/indexerWithTuple.errors.txt create mode 100644 tests/baselines/reference/tupleLengthCheck.errors.txt create mode 100644 tests/baselines/reference/tupleLengthCheck.js create mode 100644 tests/baselines/reference/tupleLengthCheck.symbols create mode 100644 tests/baselines/reference/tupleLengthCheck.types create mode 100644 tests/cases/conformance/types/tuple/tupleLengthCheck.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2a38d425afb..2e3b37d2a16 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -18293,6 +18293,13 @@ namespace ts { error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); return errorType; } + if (isTupleType(objectType) && !objectType.target.hasRestElement && isNumericLiteral(indexExpression)) { + const index = +indexExpression.text; + const maximumIndex = length(objectType.target.typeParameters); + if (index >= maximumIndex) { + error(indexExpression, Diagnostics.Index_0_is_out_of_bounds_in_tuple_of_length_1, index, maximumIndex); + } + } return checkIndexedAccessIndexType(getIndexedAccessType(objectType, indexType, node), node); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ae6ec40fd93..83cf6db75e8 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2437,6 +2437,10 @@ "category": "Error", "code": 2732 }, + "Index '{0}' is out-of-bounds in tuple of length {1}.": { + "category": "Error", + "code": 2733 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt new file mode 100644 index 00000000000..2c57099c3e8 --- /dev/null +++ b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt @@ -0,0 +1,40 @@ +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2733: Index '3' is out-of-bounds in tuple of length 3. + + +==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts (4 errors) ==== + function f1(x: number): string { return "foo"; } + + function f2(x: number): number { return 10; } + + function f3(x: number): boolean { return true; } + + enum E1 { one } + + enum E2 { two } + + + var t1: [(x: number) => string, (x: number) => number]; + var t2: [E1, E2]; + var t3: [number, any]; + var t4: [E1, E2, number]; + + // no error + t1 = [f1, f2]; + t2 = [E1.one, E2.two]; + t3 = [5, undefined]; + t4 = [E1.one, E2.two, 20]; + var e1 = t1[2]; // {} + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var e2 = t2[2]; // {} + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var e3 = t3[2]; // any + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var e4 = t4[3]; // number + ~ +!!! error TS2733: Index '3' is out-of-bounds in tuple of length 3. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt new file mode 100644 index 00000000000..80f40c74a07 --- /dev/null +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt @@ -0,0 +1,40 @@ +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. + + +==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts (5 errors) ==== + interface base { } + interface base1 { i } + class C implements base { c } + class D implements base { d } + class E implements base { e } + class F extends C { f } + + class C1 implements base1 { i = "foo"; c } + class D1 extends C1 { i = "bar"; d } + + var t1: [C, base]; + var t2: [C, D]; + var t3: [C1, D1]; + var t4: [base1, C1]; + var t5: [C1, F] + + var e11 = t1[4]; // base + ~ +!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. + var e21 = t2[4]; // {} + ~ +!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. + var e31 = t3[4]; // C1 + ~ +!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. + var e41 = t4[2]; // base1 + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var e51 = t5[2]; // {} + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + \ No newline at end of file diff --git a/tests/baselines/reference/castingTuple.errors.txt b/tests/baselines/reference/castingTuple.errors.txt index c7b00e2a0ca..e8bc9133a8a 100644 --- a/tests/baselines/reference/castingTuple.errors.txt +++ b/tests/baselines/reference/castingTuple.errors.txt @@ -6,6 +6,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(14,15): error TS2352: Conver tests/cases/conformance/types/tuple/castingTuple.ts(15,14): error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. tests/cases/conformance/types/tuple/castingTuple.ts(18,21): error TS2352: Conversion of type '[C, D]' to type '[C, D, A]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property '2' is missing in type '[C, D]'. +tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2733: Index '5' is out-of-bounds in tuple of length 3. tests/cases/conformance/types/tuple/castingTuple.ts(30,10): error TS2352: Conversion of type '[number, string]' to type '[number, number]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'string' is not comparable to type 'number'. tests/cases/conformance/types/tuple/castingTuple.ts(31,10): error TS2352: Conversion of type '[C, D]' to type '[A, I]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. @@ -15,7 +16,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(32,5): error TS2403: Subsequ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot find name 't4'. -==== tests/cases/conformance/types/tuple/castingTuple.ts (8 errors) ==== +==== tests/cases/conformance/types/tuple/castingTuple.ts (9 errors) ==== interface I { } class A { a = 10; } class C implements I { c }; @@ -48,6 +49,8 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot !!! error TS2352: Property '2' is missing in type '[C, D]'. var eleFromCDA1 = classCDATuple[2]; // A var eleFromCDA2 = classCDATuple[5]; // C | D | A + ~ +!!! error TS2733: Index '5' is out-of-bounds in tuple of length 3. var t10: [E1, E2] = [E1.one, E2.one]; var t11 = <[number, number]>t10; var array1 = <{}[]>emptyObjTuple; diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt b/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt new file mode 100644 index 00000000000..4b85b821a89 --- /dev/null +++ b/tests/baselines/reference/emptyTuplesTypeAssertion01.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion01.ts(2,11): error TS2733: Index '0' is out-of-bounds in tuple of length 0. + + +==== tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion01.ts (1 errors) ==== + let x = <[]>[]; + let y = x[0]; + ~ +!!! error TS2733: Index '0' is out-of-bounds in tuple of length 0. \ No newline at end of file diff --git a/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt b/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt new file mode 100644 index 00000000000..3969ed0fc2d --- /dev/null +++ b/tests/baselines/reference/emptyTuplesTypeAssertion02.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion02.ts(2,11): error TS2733: Index '0' is out-of-bounds in tuple of length 0. + + +==== tests/cases/conformance/types/tuple/emptyTuples/emptyTuplesTypeAssertion02.ts (1 errors) ==== + let x = [] as []; + let y = x[0]; + ~ +!!! error TS2733: Index '0' is out-of-bounds in tuple of length 0. \ No newline at end of file diff --git a/tests/baselines/reference/genericCallWithTupleType.errors.txt b/tests/baselines/reference/genericCallWithTupleType.errors.txt index 1136022e2fe..6e6732ebb09 100644 --- a/tests/baselines/reference/genericCallWithTupleType.errors.txt +++ b/tests/baselines/reference/genericCallWithTupleType.errors.txt @@ -1,8 +1,11 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(12,1): error TS2322: Type '[string, number, boolean, boolean]' is not assignable to type '[string, number]'. Types of property 'length' are incompatible. Type '4' is not assignable to type '2'. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(13,20): error TS2733: Index '2' is out-of-bounds in tuple of length 2. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,1): error TS2322: Type '{ a: string; }' is not assignable to type 'string | number'. Type '{ a: string; }' is not assignable to type 'number'. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(14,11): error TS2733: Index '3' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(15,20): error TS2733: Index '3' is out-of-bounds in tuple of length 2. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,14): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(22,17): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts(23,14): error TS2322: Type '{}' is not assignable to type 'string'. @@ -11,7 +14,7 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup Property '1' is missing in type '[{}]'. -==== tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts (7 errors) ==== +==== tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTupleType.ts (10 errors) ==== interface I { tuple1: [T, U]; } @@ -29,11 +32,17 @@ tests/cases/conformance/types/typeRelationships/typeInference/genericCallWithTup !!! error TS2322: Types of property 'length' are incompatible. !!! error TS2322: Type '4' is not assignable to type '2'. var e3 = i1.tuple1[2]; // {} + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. i1.tuple1[3] = { a: "string" }; ~~~~~~~~~~~~ !!! error TS2322: Type '{ a: string; }' is not assignable to type 'string | number'. !!! error TS2322: Type '{ a: string; }' is not assignable to type 'number'. + ~ +!!! error TS2733: Index '3' is out-of-bounds in tuple of length 2. var e4 = i1.tuple1[3]; // {} + ~ +!!! error TS2733: Index '3' is out-of-bounds in tuple of length 2. i2.tuple1 = ["foo", 5]; i2.tuple1 = ["foo", "bar"]; i2.tuple1 = [5, "bar"]; diff --git a/tests/baselines/reference/indexerWithTuple.errors.txt b/tests/baselines/reference/indexerWithTuple.errors.txt new file mode 100644 index 00000000000..4e931a3ad6e --- /dev/null +++ b/tests/baselines/reference/indexerWithTuple.errors.txt @@ -0,0 +1,47 @@ +tests/cases/conformance/types/tuple/indexerWithTuple.ts(11,25): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(17,27): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(20,30): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/indexerWithTuple.ts(28,30): error TS2733: Index '2' is out-of-bounds in tuple of length 2. + + +==== tests/cases/conformance/types/tuple/indexerWithTuple.ts (4 errors) ==== + var strNumTuple: [string, number] = ["foo", 10]; + var numTupleTuple: [number, [string, number]] = [10, ["bar", 20]]; + var unionTuple1: [number, string| number] = [10, "foo"]; + var unionTuple2: [boolean, string| number] = [true, "foo"]; + + // no error + var idx0 = 0; + var idx1 = 1; + var ele10 = strNumTuple[0]; // string + var ele11 = strNumTuple[1]; // number + var ele12 = strNumTuple[2]; // string | number + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var ele13 = strNumTuple[idx0]; // string | number + var ele14 = strNumTuple[idx1]; // string | number + var ele15 = strNumTuple["0"]; // string + var ele16 = strNumTuple["1"]; // number + var strNumTuple1 = numTupleTuple[1]; //[string, number]; + var ele17 = numTupleTuple[2]; // number | [string, number] + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var eleUnion10 = unionTuple1[0]; // number + var eleUnion11 = unionTuple1[1]; // string | number + var eleUnion12 = unionTuple1[2]; // string | number + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var eleUnion13 = unionTuple1[idx0]; // string | number + var eleUnion14 = unionTuple1[idx1]; // string | number + var eleUnion15 = unionTuple1["0"]; // number + var eleUnion16 = unionTuple1["1"]; // string | number + + var eleUnion20 = unionTuple2[0]; // boolean + var eleUnion21 = unionTuple2[1]; // string | number + var eleUnion22 = unionTuple2[2]; // string | number | boolean + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + var eleUnion23 = unionTuple2[idx0]; // string | number | boolean + var eleUnion24 = unionTuple2[idx1]; // string | number | boolean + var eleUnion25 = unionTuple2["0"]; // boolean + var eleUnion26 = unionTuple2["1"]; // string | number \ No newline at end of file diff --git a/tests/baselines/reference/tupleLengthCheck.errors.txt b/tests/baselines/reference/tupleLengthCheck.errors.txt new file mode 100644 index 00000000000..f90adbf3525 --- /dev/null +++ b/tests/baselines/reference/tupleLengthCheck.errors.txt @@ -0,0 +1,21 @@ +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(5,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/tuple/tupleLengthCheck.ts(6,14): error TS2733: Index '1000' is out-of-bounds in tuple of length 2. + + +==== tests/cases/conformance/types/tuple/tupleLengthCheck.ts (2 errors) ==== + declare const a: [number, string] + declare const rest: [number, string, ...boolean[]] + + const a1 = a[1] + const a2 = a[2] + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. + const a3 = a[1000] + ~~~~ +!!! error TS2733: Index '1000' is out-of-bounds in tuple of length 2. + + const a4 = rest[1] + const a5 = rest[2] + const a6 = rest[3] + const a7 = rest[1000] + \ No newline at end of file diff --git a/tests/baselines/reference/tupleLengthCheck.js b/tests/baselines/reference/tupleLengthCheck.js new file mode 100644 index 00000000000..23e97c47593 --- /dev/null +++ b/tests/baselines/reference/tupleLengthCheck.js @@ -0,0 +1,22 @@ +//// [tupleLengthCheck.ts] +declare const a: [number, string] +declare const rest: [number, string, ...boolean[]] + +const a1 = a[1] +const a2 = a[2] +const a3 = a[1000] + +const a4 = rest[1] +const a5 = rest[2] +const a6 = rest[3] +const a7 = rest[1000] + + +//// [tupleLengthCheck.js] +var a1 = a[1]; +var a2 = a[2]; +var a3 = a[1000]; +var a4 = rest[1]; +var a5 = rest[2]; +var a6 = rest[3]; +var a7 = rest[1000]; diff --git a/tests/baselines/reference/tupleLengthCheck.symbols b/tests/baselines/reference/tupleLengthCheck.symbols new file mode 100644 index 00000000000..ffa524e3ca4 --- /dev/null +++ b/tests/baselines/reference/tupleLengthCheck.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/types/tuple/tupleLengthCheck.ts === +declare const a: [number, string] +>a : Symbol(a, Decl(tupleLengthCheck.ts, 0, 13)) + +declare const rest: [number, string, ...boolean[]] +>rest : Symbol(rest, Decl(tupleLengthCheck.ts, 1, 13)) + +const a1 = a[1] +>a1 : Symbol(a1, Decl(tupleLengthCheck.ts, 3, 5)) +>a : Symbol(a, Decl(tupleLengthCheck.ts, 0, 13)) +>1 : Symbol(1) + +const a2 = a[2] +>a2 : Symbol(a2, Decl(tupleLengthCheck.ts, 4, 5)) +>a : Symbol(a, Decl(tupleLengthCheck.ts, 0, 13)) + +const a3 = a[1000] +>a3 : Symbol(a3, Decl(tupleLengthCheck.ts, 5, 5)) +>a : Symbol(a, Decl(tupleLengthCheck.ts, 0, 13)) + +const a4 = rest[1] +>a4 : Symbol(a4, Decl(tupleLengthCheck.ts, 7, 5)) +>rest : Symbol(rest, Decl(tupleLengthCheck.ts, 1, 13)) +>1 : Symbol(1) + +const a5 = rest[2] +>a5 : Symbol(a5, Decl(tupleLengthCheck.ts, 8, 5)) +>rest : Symbol(rest, Decl(tupleLengthCheck.ts, 1, 13)) + +const a6 = rest[3] +>a6 : Symbol(a6, Decl(tupleLengthCheck.ts, 9, 5)) +>rest : Symbol(rest, Decl(tupleLengthCheck.ts, 1, 13)) + +const a7 = rest[1000] +>a7 : Symbol(a7, Decl(tupleLengthCheck.ts, 10, 5)) +>rest : Symbol(rest, Decl(tupleLengthCheck.ts, 1, 13)) + diff --git a/tests/baselines/reference/tupleLengthCheck.types b/tests/baselines/reference/tupleLengthCheck.types new file mode 100644 index 00000000000..be4372c669c --- /dev/null +++ b/tests/baselines/reference/tupleLengthCheck.types @@ -0,0 +1,49 @@ +=== tests/cases/conformance/types/tuple/tupleLengthCheck.ts === +declare const a: [number, string] +>a : [number, string] + +declare const rest: [number, string, ...boolean[]] +>rest : [number, string, ...boolean[]] + +const a1 = a[1] +>a1 : string +>a[1] : string +>a : [number, string] +>1 : 1 + +const a2 = a[2] +>a2 : string | number +>a[2] : string | number +>a : [number, string] +>2 : 2 + +const a3 = a[1000] +>a3 : string | number +>a[1000] : string | number +>a : [number, string] +>1000 : 1000 + +const a4 = rest[1] +>a4 : string +>rest[1] : string +>rest : [number, string, ...boolean[]] +>1 : 1 + +const a5 = rest[2] +>a5 : boolean +>rest[2] : boolean +>rest : [number, string, ...boolean[]] +>2 : 2 + +const a6 = rest[3] +>a6 : boolean +>rest[3] : boolean +>rest : [number, string, ...boolean[]] +>3 : 3 + +const a7 = rest[1000] +>a7 : boolean +>rest[1000] : boolean +>rest : [number, string, ...boolean[]] +>1000 : 1000 + diff --git a/tests/baselines/reference/tupleTypes.errors.txt b/tests/baselines/reference/tupleTypes.errors.txt index 87e17e14d3c..7e4e926492d 100644 --- a/tests/baselines/reference/tupleTypes.errors.txt +++ b/tests/baselines/reference/tupleTypes.errors.txt @@ -1,3 +1,4 @@ +tests/cases/compiler/tupleTypes.ts(11,12): error TS2733: Index '2' is out-of-bounds in tuple of length 2. tests/cases/compiler/tupleTypes.ts(14,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. Property '0' is missing in type '[]'. tests/cases/compiler/tupleTypes.ts(15,1): error TS2322: Type '[number]' is not assignable to type '[number, string]'. @@ -7,6 +8,7 @@ tests/cases/compiler/tupleTypes.ts(17,15): error TS2322: Type 'number' is not as tests/cases/compiler/tupleTypes.ts(18,1): error TS2322: Type '[number, string, number]' is not assignable to type '[number, string]'. Types of property 'length' are incompatible. Type '3' is not assignable to type '2'. +tests/cases/compiler/tupleTypes.ts(35,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. tests/cases/compiler/tupleTypes.ts(41,1): error TS2322: Type '[]' is not assignable to type '[number, string]'. tests/cases/compiler/tupleTypes.ts(47,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. Types of property 'pop' are incompatible. @@ -24,7 +26,7 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n Type '{}' is not assignable to type 'string'. -==== tests/cases/compiler/tupleTypes.ts (10 errors) ==== +==== tests/cases/compiler/tupleTypes.ts (12 errors) ==== var v1: []; // Error var v2: [number]; var v3: [number, string]; @@ -36,6 +38,8 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var t1 = t[1]; // string var t1: string; var t2 = t[2]; // number|string + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. var t2: number|string; t = []; // Error @@ -74,6 +78,8 @@ tests/cases/compiler/tupleTypes.ts(51,1): error TS2322: Type '[number, {}]' is n var tt1 = tt[1]; var tt1: string; var tt2 = tt[2]; + ~ +!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. var tt2: number | string; tt = tuple2(1, undefined); diff --git a/tests/cases/conformance/types/tuple/tupleLengthCheck.ts b/tests/cases/conformance/types/tuple/tupleLengthCheck.ts new file mode 100644 index 00000000000..593c47ee3b2 --- /dev/null +++ b/tests/cases/conformance/types/tuple/tupleLengthCheck.ts @@ -0,0 +1,11 @@ +declare const a: [number, string] +declare const rest: [number, string, ...boolean[]] + +const a1 = a[1] +const a2 = a[2] +const a3 = a[1000] + +const a4 = rest[1] +const a5 = rest[2] +const a6 = rest[3] +const a7 = rest[1000] From beed179f58a9557b194f1975accab9b21ba4fd7a Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 14 Aug 2018 22:38:03 +0200 Subject: [PATCH 016/146] disallow abstract property access in property initializer Fixes: #26407 --- src/compiler/checker.ts | 8 ++--- .../abstractPropertyInConstructor.errors.txt | 8 ++++- .../abstractPropertyInConstructor.js | 5 ++++ .../abstractPropertyInConstructor.symbols | 30 +++++++++++++------ .../abstractPropertyInConstructor.types | 13 ++++++++ .../compiler/abstractPropertyInConstructor.ts | 3 ++ 6 files changed, 53 insertions(+), 14 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f2c1c71eb6c..118963df145 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -17779,7 +17779,7 @@ namespace ts { // Referencing abstract properties within their own constructors is not allowed if ((flags & ModifierFlags.Abstract) && isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) { const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)!); - if (declaringClassDeclaration && isNodeWithinConstructorOfClass(node, declaringClassDeclaration)) { + if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node, declaringClassDeclaration)) { error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name!)); // TODO: GH#18217 return false; } @@ -27146,9 +27146,9 @@ namespace ts { return result; } - function isNodeWithinConstructorOfClass(node: Node, classDeclaration: ClassLikeDeclaration) { - return findAncestor(node, element => { - if (isConstructorDeclaration(element) && nodeIsPresent(element.body) && element.parent === classDeclaration) { + function isNodeUsedDuringClassInitialization(node: Node, classDeclaration: ClassLikeDeclaration) { + return !!findAncestor(node, element => { + if ((isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) && element.parent === classDeclaration) { return true; } else if (element === classDeclaration || isFunctionLikeDeclaration(element)) { diff --git a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt index 0798d91ce78..5337bfc538a 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt +++ b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt @@ -1,9 +1,10 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(4,24): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(7,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(9,14): error TS2715: Abstract property 'cb' in class 'AbstractClass' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(25,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. -==== tests/cases/compiler/abstractPropertyInConstructor.ts (3 errors) ==== +==== tests/cases/compiler/abstractPropertyInConstructor.ts (4 errors) ==== abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); @@ -34,6 +35,11 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(9,14): error TS2715: Abstr abstract method(num: number): void; + other = this.prop; + ~~~~ +!!! error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. + fn = () => this.prop; + method2() { this.prop = this.prop + "!"; } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.js b/tests/baselines/reference/abstractPropertyInConstructor.js index 5a4feda110f..782419ac67b 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.js +++ b/tests/baselines/reference/abstractPropertyInConstructor.js @@ -23,6 +23,9 @@ abstract class AbstractClass { abstract method(num: number): void; + other = this.prop; + fn = () => this.prop; + method2() { this.prop = this.prop + "!"; } @@ -42,6 +45,8 @@ class User { var AbstractClass = /** @class */ (function () { function AbstractClass(str, other) { var _this = this; + this.other = this.prop; + this.fn = function () { return _this.prop; }; this.method(parseInt(str)); var val = this.prop.toLowerCase(); if (!str) { diff --git a/tests/baselines/reference/abstractPropertyInConstructor.symbols b/tests/baselines/reference/abstractPropertyInConstructor.symbols index f1baa962072..71f897118c8 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.symbols +++ b/tests/baselines/reference/abstractPropertyInConstructor.symbols @@ -67,8 +67,20 @@ abstract class AbstractClass { >method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) >num : Symbol(num, Decl(abstractPropertyInConstructor.ts, 22, 20)) + other = this.prop; +>other : Symbol(AbstractClass.other, Decl(abstractPropertyInConstructor.ts, 22, 39)) +>this.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>this : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + + fn = () => this.prop; +>fn : Symbol(AbstractClass.fn, Decl(abstractPropertyInConstructor.ts, 24, 22)) +>this.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>this : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + method2() { ->method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 22, 39)) +>method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) this.prop = this.prop + "!"; >this.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) @@ -81,31 +93,31 @@ abstract class AbstractClass { } class User { ->User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 27, 1)) +>User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 30, 1)) constructor(a: AbstractClass) { ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 30, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) >AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) a.prop; >a.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 30, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) >prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) a.cb("hi"); >a.cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 30, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) >cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) a.method(12); >a.method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 30, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) >method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) a.method2(); ->a.method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 22, 39)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 30, 16)) ->method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 22, 39)) +>a.method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) } } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.types b/tests/baselines/reference/abstractPropertyInConstructor.types index 23e1aac50f7..465e0fb2f04 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.types +++ b/tests/baselines/reference/abstractPropertyInConstructor.types @@ -75,6 +75,19 @@ abstract class AbstractClass { >method : (num: number) => void >num : number + other = this.prop; +>other : string +>this.prop : string +>this : this +>prop : string + + fn = () => this.prop; +>fn : () => string +>() => this.prop : () => string +>this.prop : string +>this : this +>prop : string + method2() { >method2 : () => void diff --git a/tests/cases/compiler/abstractPropertyInConstructor.ts b/tests/cases/compiler/abstractPropertyInConstructor.ts index b8386f56e1e..5ea3569e20d 100644 --- a/tests/cases/compiler/abstractPropertyInConstructor.ts +++ b/tests/cases/compiler/abstractPropertyInConstructor.ts @@ -22,6 +22,9 @@ abstract class AbstractClass { abstract method(num: number): void; + other = this.prop; + fn = () => this.prop; + method2() { this.prop = this.prop + "!"; } From 015babb6f7d8d6904bd31ff4da887d8f3ecd3855 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 17 Aug 2018 18:27:45 -0700 Subject: [PATCH 017/146] Initial support for 'typesVersions' --- src/compiler/checker.ts | 2 +- src/compiler/diagnosticMessages.json | 2 +- src/compiler/moduleNameResolver.ts | 152 +++++++++++------ src/compiler/moduleSpecifiers.ts | 2 +- src/compiler/semver.ts | 156 ++++++++++++++++++ src/compiler/tsconfig.json | 1 + src/compiler/utilities.ts | 21 +++ src/services/codefixes/fixCannotFindModule.ts | 2 +- src/services/pathCompletions.ts | 4 +- ...age_relativeImportWithinPackage.trace.json | 3 + ...ativeImportWithinPackage_scoped.trace.json | 3 + .../reference/library-reference-10.trace.json | 2 + .../reference/library-reference-11.trace.json | 1 + .../reference/library-reference-12.trace.json | 1 + .../reference/library-reference-2.trace.json | 2 + ...lutionWithExtensions_unexpected.trace.json | 2 + ...utionWithExtensions_unexpected2.trace.json | 2 + ...on_packageJson_notAtPackageRoot.trace.json | 1 + ...AtPackageRoot_fakeScopedPackage.trace.json | 1 + ...ution_packageJson_scopedPackage.trace.json | 1 + ...on_packageJson_yesAtPackageRoot.trace.json | 2 + ...AtPackageRoot_fakeScopedPackage.trace.json | 2 + ...ageRoot_mainFieldInSubDirectory.trace.json | 1 + .../reference/packageJsonMain.trace.json | 6 + .../packageJsonMain_isNonRecursive.trace.json | 2 + .../reference/typesVersions.ambientModules.js | 43 +++++ .../typesVersions.ambientModules.symbols | 29 ++++ .../typesVersions.ambientModules.trace.json | 46 ++++++ .../typesVersions.ambientModules.types | 31 ++++ .../reference/typesVersions.multiFile.js | 39 +++++ .../reference/typesVersions.multiFile.symbols | 31 ++++ .../typesVersions.multiFile.trace.json | 31 ++++ .../reference/typesVersions.multiFile.types | 35 ++++ .../reference/typingsLookup4.trace.json | 8 + .../typesVersions.ambientModules.ts | 39 +++++ .../typesVersions.multiFile.ts | 34 ++++ 36 files changed, 687 insertions(+), 53 deletions(-) create mode 100644 src/compiler/semver.ts create mode 100644 tests/baselines/reference/typesVersions.ambientModules.js create mode 100644 tests/baselines/reference/typesVersions.ambientModules.symbols create mode 100644 tests/baselines/reference/typesVersions.ambientModules.trace.json create mode 100644 tests/baselines/reference/typesVersions.ambientModules.types create mode 100644 tests/baselines/reference/typesVersions.multiFile.js create mode 100644 tests/baselines/reference/typesVersions.multiFile.symbols create mode 100644 tests/baselines/reference/typesVersions.multiFile.trace.json create mode 100644 tests/baselines/reference/typesVersions.multiFile.types create mode 100644 tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts create mode 100644 tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 26b93b19335..f2f6ad93562 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2255,7 +2255,7 @@ namespace ts { ? Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 : Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, packageId.name, - getMangledNameForScopedPackage(packageId.name)) + mangleScopedPackageName(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 6000c48de4d..ed528e5b87e 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3273,7 +3273,7 @@ "category": "Message", "code": 6104 }, - "Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": { + "Expected type of '{0}' field in 'package.json' to be '{1}', got '{2}'.": { "category": "Message", "code": 6105 }, diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 7fb308912c3..d1054579e84 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -88,6 +88,7 @@ namespace ts { interface PackageJsonPathFields { typings?: string; types?: string; + typesVersions?: MapLike; main?: string; } @@ -111,7 +112,7 @@ namespace ts { const fileName = jsonContent[fieldName]; if (!isString(fileName)) { if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, "string", typeof fileName); } return; } @@ -124,21 +125,65 @@ namespace ts { } } - /* @internal */ - export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { - try { - const jsonText = host.readFile(path); - if (!jsonText) return {}; - const result = parseConfigFileTextToJson(path, jsonText); - if (result.error) { - return {}; + function tryReadPackageJsonTypesVersion(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState): string | undefined { + if (!hasProperty(jsonContent, "typesVersions")) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, "typesVersions"); } - return result.config; + return; } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; + + const typesVersions = jsonContent.typesVersions; + if (typeof typesVersions !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions", "object", typeof typesVersions); + } + return; } + + const typeScriptVersion = Version.parse(version); + let bestVersion: Version | undefined; + let bestVersionKey: string | undefined; + for (const key in typesVersions) { + if (!hasProperty(typesVersions, key)) continue; + + const keyVersion = Version.tryParse(key); + if (keyVersion === undefined) { + if (state.traceEnabled) { + // TODO(rbuckton): log + } + continue; + } + + // match the greatest version less than the current TypeScript version + if (keyVersion.compareTo(typeScriptVersion) <= 0 + && (bestVersion === undefined || keyVersion.compareTo(bestVersion) > 0)) { + bestVersion = keyVersion; + bestVersionKey = key; + } + } + + if (!bestVersionKey) { + if (state.traceEnabled) { + // TODO(rbuckton): log + } + return; + } + + const bestVersionPath = typesVersions[bestVersionKey]; + if (!isString(bestVersionPath)) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersion['${bestVersionKey}']`, "string", typeof bestVersionPath); + } + return; + } + + if (state.traceEnabled) { + const path = normalizePath(combinePaths(baseDirectory, bestVersionPath)); + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, `typesVersion['${bestVersionKey}']`, bestVersionPath, path); + } + + return bestVersionPath; } export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined { @@ -720,7 +765,6 @@ namespace ts { } else { const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); } @@ -892,12 +936,6 @@ namespace ts { return path + "/index.d.ts"; } - /* @internal */ - export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); } @@ -977,9 +1015,12 @@ namespace ts { } function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { - const { packageJsonContent, packageId } = considerPackageJson + const { packageJsonContent, packageId, versionPath } = considerPackageJson ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined }; + : { packageJsonContent: undefined, packageId: undefined, versionPath: undefined }; + if (versionPath) { + candidate = normalizePath(combinePaths(candidate, versionPath)); + } return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); } @@ -998,16 +1039,18 @@ namespace ts { failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, - ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined } { + ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined, versionPath: string | undefined } { const { host, traceEnabled } = state; const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); const packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host) as PackageJson; + const versionPath = tryReadPackageJsonTypesVersion(packageJsonContent, nodeModuleDirectory, state); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, nodeModuleDirectory, state); + const versionDirectory = versionPath ? normalizePath(combinePaths(nodeModuleDirectory, versionPath)) : nodeModuleDirectory; + const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, versionDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(nodeModuleDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(versionDirectory.length + 1)); } else { const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); @@ -1021,6 +1064,11 @@ namespace ts { } } } + + // if (versionPath) { + // subModuleName = combinePaths(versionPath, subModuleName); + // } + if (!endsWith(subModuleName, Extension.Dts)) { subModuleName = addExtensionAndIndex(subModuleName); } @@ -1035,15 +1083,16 @@ namespace ts { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent, packageId }; + return { found: true, packageJsonContent, packageId, versionPath }; } else { if (directoryExists && traceEnabled) { trace(host, Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined }; + return { found: false, packageJsonContent: undefined, packageId: undefined, versionPath: undefined }; } } @@ -1110,20 +1159,30 @@ namespace ts { } function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, nodeModulesFolder: string, nodeModulesFolderExists: boolean, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); + let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. let packageJsonContent: PackageJsonPathFields | undefined; + let versionPath: string | undefined; let packageId: PackageId | undefined; const packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); if (packageInfo.found) { - ({ packageJsonContent, packageId } = packageInfo); + ({ packageJsonContent, packageId, versionPath } = packageInfo); + + // If package.json supplied a typescript-version prefix path, apply it to the candidate. + if (versionPath) { + candidate = normalizePath(combinePaths(candidate, versionPath)); + } } else { - const { packageName, rest } = getPackageName(moduleName); + const { packageName, rest } = parsePackageName(moduleName); if (rest !== "") { // If "rest" is empty, we just did this search above. const packageRootPath = combinePaths(nodeModulesFolder, packageName); // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - packageId = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state).packageId; + ({ packageId, versionPath } = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state)); + // If package.json supplied a typescript-version prefix path, apply it to the candidate. + if (versionPath) { + candidate = normalizePath(combinePaths(packageRootPath, versionPath, rest)); + } } } const pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || @@ -1132,7 +1191,7 @@ namespace ts { } /* @internal */ - export function getPackageName(moduleName: string): { packageName: string, rest: string } { + export function parsePackageName(moduleName: string): { packageName: string, rest: string } { let idx = moduleName.indexOf(directorySeparator); if (moduleName[0] === "@") { idx = moduleName.indexOf(directorySeparator, idx + 1); @@ -1141,14 +1200,14 @@ namespace ts { } function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNodeModulesWorker(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); + return loadModuleFromNearestNodeModules(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); } function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): SearchResult { // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNodeModulesWorker(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + return loadModuleFromNearestNodeModules(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); } - function loadModuleFromNodeModulesWorker(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { + function loadModuleFromNearestNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { @@ -1156,13 +1215,12 @@ namespace ts { if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromNodeModulesOneLevel(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModules(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); } }); } - /** Load a module from a single node_modules directory, but not from any ancestors' node_modules directories. */ - function loadModuleFromNodeModulesOneLevel(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly = false): Resolved | undefined { + function loadModuleFromImmediateNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean): Resolved | undefined { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { @@ -1182,7 +1240,7 @@ namespace ts { } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackage(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state); } } @@ -1190,8 +1248,8 @@ namespace ts { const mangledScopedPackageSeparator = "__"; /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */ - function mangleScopedPackage(packageName: string, state: ModuleResolutionState): string { - const mangled = getMangledNameForScopedPackage(packageName); + function mangleScopedPackageNameWithTrace(packageName: string, state: ModuleResolutionState): string { + const mangled = mangleScopedPackageName(packageName); if (state.traceEnabled && mangled !== packageName) { trace(state.host, Diagnostics.Scoped_package_detected_looking_in_0, mangled); } @@ -1200,11 +1258,11 @@ namespace ts { /* @internal */ export function getTypesPackageName(packageName: string): string { - return `@types/${getMangledNameForScopedPackage(packageName)}`; + return `@types/${mangleScopedPackageName(packageName)}`; } /* @internal */ - export function getMangledNameForScopedPackage(packageName: string): string { + export function mangleScopedPackageName(packageName: string): string { if (startsWith(packageName, "@")) { const replaceSlash = packageName.replace(directorySeparator, mangledScopedPackageSeparator); if (replaceSlash !== packageName) { @@ -1215,16 +1273,16 @@ namespace ts { } /* @internal */ - export function getPackageNameFromAtTypesDirectory(mangledName: string): string { + export function getPackageNameFromTypesPackageName(mangledName: string): string { const withoutAtTypePrefix = removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return getUnmangledNameForScopedPackage(withoutAtTypePrefix); + return unmangleScopedPackageName(withoutAtTypePrefix); } return mangledName; } /* @internal */ - export function getUnmangledNameForScopedPackage(typesPackageName: string): string { + export function unmangleScopedPackageName(typesPackageName: string): string { return stringContains(typesPackageName, mangledScopedPackageSeparator) ? "@" + typesPackageName.replace(mangledScopedPackageSeparator, directorySeparator) : typesPackageName; @@ -1295,7 +1353,7 @@ namespace ts { } const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; - const resolved = loadModuleFromNodeModulesOneLevel(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state); + const resolved = loadModuleFromImmediateNodeModules(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state, /*typesOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index 8c695e10be2..696736048b1 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -326,7 +326,7 @@ namespace ts.moduleSpecifiers { // if node_modules folder is in this folder or any of its parent folders, no need to keep it. if (!startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; // If the module was found in @types, get the actual Node package name - return getPackageNameFromAtTypesDirectory(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); + return getPackageNameFromTypesPackageName(moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1)); function getDirectoryOrExtensionlessFileName(path: string): string { // If the file is the main module, it can be imported by the package name diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts new file mode 100644 index 00000000000..a3c4e90d37a --- /dev/null +++ b/src/compiler/semver.ts @@ -0,0 +1,156 @@ +/* @internal */ +namespace ts { + // Per https://semver.org/#spec-item-2: + // + // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative + // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor + // > version, and Z is the patch version. Each element MUST increase numerically. + // + // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default + // value of `0`. + const versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:(\+[a-z0-9-.]+))?)?)?$/i; + + // Per https://semver.org/#spec-item-9: + // + // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated + // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII + // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers + // > MUST NOT include leading zeroes. + const prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; + + // Per https://semver.org/#spec-item-10: + // + // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated + // > identifiers immediately following the patch or pre-release version. Identifiers MUST + // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. + const buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; + + // Per https://semver.org/#spec-item-9: + // + // > Numeric identifiers MUST NOT include leading zeroes. + const numericIdentifierRegExp = /^(0|[1-9]\d*)$/; + + /** + * Describes a precise semantic version number, per https://semver.org + */ + export class Version { + static readonly zero = new Version(0); + + readonly major: number; + readonly minor: number; + readonly patch: number; + readonly prerelease: ReadonlyArray; + readonly build: ReadonlyArray; + + constructor(major: number, minor = 0, patch = 0, prerelease = "", build = "") { + Debug.assert(major >= 0, "Invalid argument: major"); + Debug.assert(minor >= 0, "Invalid argument: minor"); + Debug.assert(patch >= 0, "Invalid argument: patch"); + Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease"); + Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build"); + this.major = major; + this.minor = minor; + this.patch = patch; + this.prerelease = prerelease === "" ? emptyArray : prerelease.split("."); + this.build = build === "" ? emptyArray : build.split("."); + } + + static parse(text: string) { + return Debug.assertDefined(this.tryParse(text)); + } + + static tryParse(text: string) { + const match = versionRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = 0, patch = 0, prerelease, build] = match; + if (prerelease && !prereleaseRegExp.test(prerelease)) return undefined; + if (build && !buildRegExp.test(build)) return undefined; + return new Version(+major, +minor, +patch, prerelease, build); + } + + static compare(left: Version | undefined, right: Version | undefined, compareBuildMetadata?: boolean) { + // Per https://semver.org/#spec-item-11: + // + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + // + // > When major, minor, and patch are equal, a pre-release version has lower + // > precedence than a normal version. + // + // Per https://semver.org/#spec-item-10: + // + // > Build metadata SHOULD be ignored when determining version precedence. + if (left === right) return Comparison.EqualTo; + if (left === undefined) return Comparison.LessThan; + if (right === undefined) return Comparison.GreaterThan; + return compareValues(left.major, right.major) + || compareValues(left.minor, right.minor) + || compareValues(left.patch, right.patch) + || compareVersionFragments(left.prerelease, right.prerelease, /*compareNumericIdentifiers*/ true) + || (compareBuildMetadata ? compareVersionFragments(left.build, right.build, /*compareNumericIdentifiers*/ false) : Comparison.EqualTo); + } + + compareTo(other: Version, compareBuildMetadata?: boolean) { + return Version.compare(this, other, compareBuildMetadata); + } + + toString() { + let result = `${this.major}.${this.minor}.${this.patch}`; + if (this.prerelease) result += `-${this.prerelease.join(".")}`; + if (this.build) result += `+${this.build.join(".")}`; + return result; + } + } + + function compareVersionFragments(left: ReadonlyArray, right: ReadonlyArray, compareNumericIdentifiers: boolean) { + // Per https://semver.org/#spec-item-11: + // + // > When major, minor, and patch are equal, a pre-release version has lower precedence + // > than a normal version. + if (left === right) return Comparison.EqualTo; + if (left.length === 0) return right.length === 0 ? Comparison.EqualTo : Comparison.GreaterThan; + if (right.length === 0) return Comparison.LessThan; + + // Per https://semver.org/#spec-item-11: + // + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftIdentifier = left[i]; + const rightIdentifier = right[i]; + if (leftIdentifier === rightIdentifier) continue; + + const leftIsNumeric = compareNumericIdentifiers && numericIdentifierRegExp.test(leftIdentifier); + const rightIsNumeric = compareNumericIdentifiers && numericIdentifierRegExp.test(rightIdentifier); + if (leftIsNumeric || rightIsNumeric) { + // Per https://semver.org/#spec-item-11: + // + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? Comparison.LessThan : Comparison.GreaterThan; + + // Per https://semver.org/#spec-item-11: + // + // > identifiers consisting of only digits are compared numerically + const result = compareValues(+leftIdentifier, +rightIdentifier); + if (result) return result; + } + else { + // Per https://semver.org/#spec-item-11: + // + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); + if (result) return result; + } + } + + // Per https://semver.org/#spec-item-11: + // + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + return compareValues(left.length, right.length); + } +} \ No newline at end of file diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 20b97c1b778..2d3cbcf54fe 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -9,6 +9,7 @@ "files": [ "core.ts", "performance.ts", + "semver.ts", "types.ts", "sys.ts", diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 33dfd2617c9..e7eb352da84 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3940,6 +3940,27 @@ namespace ts { return getStringFromExpandedCharCodes(expandedCharCodes); } + export function readJson(path: string, host: { readFile(fileName: string): string | undefined }): object { + try { + const jsonText = host.readFile(path); + if (!jsonText) return {}; + const result = parseConfigFileTextToJson(path, jsonText); + if (result.error) { + return {}; + } + return result.config; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + + export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + const carriageReturnLineFeed = "\r\n"; const lineFeed = "\n"; export function getNewLineCharacter(options: CompilerOptions | PrinterOptions, getNewLine?: () => string): string { diff --git a/src/services/codefixes/fixCannotFindModule.ts b/src/services/codefixes/fixCannotFindModule.ts index 68fa3a5c030..6822cae7911 100644 --- a/src/services/codefixes/fixCannotFindModule.ts +++ b/src/services/codefixes/fixCannotFindModule.ts @@ -29,7 +29,7 @@ namespace ts.codefix { function getTypesPackageNameToInstall(host: LanguageServiceHost, sourceFile: SourceFile, pos: number, diagCode: number): string | undefined { const moduleName = cast(getTokenAtPosition(sourceFile, pos), isStringLiteral).text; - const { packageName } = getPackageName(moduleName); + const { packageName } = parsePackageName(moduleName); return diagCode === errorCodeCannotFindModule ? (JsTyping.nodeCoreModules.has(packageName) ? "@types/node" : undefined) : (host.isKnownTypesPackageName!(packageName) ? getTypesPackageName(packageName) : undefined); // TODO: GH#18217 diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 8ab7cc315ad..3a546573db7 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -329,7 +329,7 @@ namespace ts.Completions.PathCompletions { const seen = createMap(); if (options.types) { for (const typesName of options.types) { - const moduleName = getUnmangledNameForScopedPackage(typesName); + const moduleName = unmangleScopedPackageName(typesName); pushResult(moduleName); } } @@ -363,7 +363,7 @@ namespace ts.Completions.PathCompletions { for (let typeDirectory of directories) { typeDirectory = normalizePath(typeDirectory); const directoryName = getBaseFileName(typeDirectory); - const moduleName = getUnmangledNameForScopedPackage(directoryName); + const moduleName = unmangleScopedPackageName(directoryName); pushResult(moduleName); } } diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json index d75683d210f..dbf67e3802c 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo/use' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/use' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/use/index.d.ts@1.2.3'.", "File '/node_modules/foo/use.ts' does not exist.", "File '/node_modules/foo/use.tsx' does not exist.", @@ -26,11 +27,13 @@ "File '/node_modules/foo/index.ts' does not exist.", "File '/node_modules/foo/index.tsx' does not exist.", "File '/node_modules/foo/index.d.ts' exist - use it as a name resolution result.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.", "======== Module name './index' was successfully resolved to '/node_modules/foo/index.d.ts'. ========", "======== Resolving module 'foo' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' does not have a 'main' field.", diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json index 7b07ecd66e4..d3d3dfac064 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json @@ -2,6 +2,7 @@ "======== Resolving module '@foo/bar/use' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar/use' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/use/index.d.ts@1.2.3'.", "File '/node_modules/@foo/bar/use.ts' does not exist.", "File '/node_modules/@foo/bar/use.tsx' does not exist.", @@ -26,11 +27,13 @@ "File '/node_modules/@foo/bar/index.ts' does not exist.", "File '/node_modules/@foo/bar/index.tsx' does not exist.", "File '/node_modules/@foo/bar/index.d.ts' exist - use it as a name resolution result.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.", "======== Module name './index' was successfully resolved to '/node_modules/@foo/bar/index.d.ts'. ========", "======== Resolving module '@foo/bar' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' does not have a 'main' field.", diff --git a/tests/baselines/reference/library-reference-10.trace.json b/tests/baselines/reference/library-reference-10.trace.json index ad34c0b1dc3..d24bc21f283 100644 --- a/tests/baselines/reference/library-reference-10.trace.json +++ b/tests/baselines/reference/library-reference-10.trace.json @@ -1,6 +1,7 @@ [ "======== Resolving type reference directive 'jquery', containing file '/foo/consumer.ts', root directory './types'. ========", "Resolving with primary search path './types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", @@ -9,6 +10,7 @@ "======== Type reference directive 'jquery' was successfully resolved to '/foo/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/foo/__inferred type names__.ts', root directory './types'. ========", "Resolving with primary search path './types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "Found 'package.json' at './types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", diff --git a/tests/baselines/reference/library-reference-11.trace.json b/tests/baselines/reference/library-reference-11.trace.json index be260b6bc6e..5b2d6695356 100644 --- a/tests/baselines/reference/library-reference-11.trace.json +++ b/tests/baselines/reference/library-reference-11.trace.json @@ -3,6 +3,7 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "File '/a/node_modules/jquery.d.ts' does not exist.", diff --git a/tests/baselines/reference/library-reference-12.trace.json b/tests/baselines/reference/library-reference-12.trace.json index 26361703708..f6c1aef4811 100644 --- a/tests/baselines/reference/library-reference-12.trace.json +++ b/tests/baselines/reference/library-reference-12.trace.json @@ -3,6 +3,7 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'dist/jquery.d.ts' that references '/a/node_modules/jquery/dist/jquery.d.ts'.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", diff --git a/tests/baselines/reference/library-reference-2.trace.json b/tests/baselines/reference/library-reference-2.trace.json index 649189fbbdd..baef46d8995 100644 --- a/tests/baselines/reference/library-reference-2.trace.json +++ b/tests/baselines/reference/library-reference-2.trace.json @@ -1,6 +1,7 @@ [ "======== Resolving type reference directive 'jquery', containing file '/consumer.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "Found 'package.json' at '/types/jquery/package.json'.", @@ -11,6 +12,7 @@ "======== Type reference directive 'jquery' was successfully resolved to '/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/test/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "Found 'package.json' at '/types/jquery/package.json'.", diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json index 60cdab44a29..2f743d9e200 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'normalize.css' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", @@ -24,6 +25,7 @@ "File '/node_modules/normalize.css/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json index bab6be18d39..06610253558 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", "Found 'package.json' at '/node_modules/foo/package.json'.", @@ -26,6 +27,7 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", "Found 'package.json' at '/node_modules/foo/package.json'.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json index 3473f33c1f2..2a4a1e71a4a 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/bar/types.d.ts'.", "Found 'package.json' at '/node_modules/foo/bar/package.json'.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json index 07dc908b745..b54519397ab 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo/@bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/@bar/types.d.ts'.", "Found 'package.json' at '/node_modules/foo/@bar/package.json'.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json index 77ea6a244c1..389bd892d2f 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json @@ -2,6 +2,7 @@ "======== Resolving module '@foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/@foo/bar/types.d.ts'.", "Found 'package.json' at '/node_modules/@foo/bar/package.json'.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json index 453f5c088a3..873805b8b57 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot.trace.json @@ -3,6 +3,7 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", "File '/node_modules/foo/bar/package.json' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/bar.ts' does not exist.", "File '/node_modules/foo/bar.tsx' does not exist.", @@ -13,6 +14,7 @@ "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'JavaScript'.", "File '/node_modules/foo/bar/package.json' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/bar.js' does not exist.", "File '/node_modules/foo/bar.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json index b84bac8993a..95beae1393e 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_fakeScopedPackage.trace.json @@ -3,6 +3,7 @@ "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'TypeScript'.", "File '/node_modules/foo/@bar/package.json' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/@bar.ts' does not exist.", "File '/node_modules/foo/@bar.tsx' does not exist.", @@ -13,6 +14,7 @@ "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'JavaScript'.", "File '/node_modules/foo/@bar/package.json' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/@bar/index.d.ts@1.2.3'.", "File '/node_modules/foo/@bar.js' does not exist.", "File '/node_modules/foo/@bar.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json index 849b65ee59f..84b7a4873c0 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'src/index.js' that references '/node_modules/foo/src/index.js'.", diff --git a/tests/baselines/reference/packageJsonMain.trace.json b/tests/baselines/reference/packageJsonMain.trace.json index 06c8cff6643..583fc96774e 100644 --- a/tests/baselines/reference/packageJsonMain.trace.json +++ b/tests/baselines/reference/packageJsonMain.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", @@ -23,6 +24,7 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", @@ -38,6 +40,7 @@ "======== Resolving module 'bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'bar' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", @@ -64,6 +67,7 @@ "File '/node_modules/bar/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'bar' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", @@ -77,6 +81,7 @@ "======== Resolving module 'baz' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'baz' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", @@ -100,6 +105,7 @@ "File '/node_modules/baz/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'baz' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", diff --git a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json index a2878a2a4fe..b7d26d0f852 100644 --- a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json +++ b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json @@ -2,6 +2,7 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", @@ -25,6 +26,7 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", diff --git a/tests/baselines/reference/typesVersions.ambientModules.js b/tests/baselines/reference/typesVersions.ambientModules.js new file mode 100644 index 00000000000..c7f198b8467 --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.js @@ -0,0 +1,43 @@ +//// [tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": "ts3.0" + } +} + +//// [index.d.ts] +declare module "ext" { + export const a = "default a"; +} +declare module "ext/other" { + export const b = "default b"; +} + +//// [index.d.ts] +declare module "ext" { + export const a = "ts3.0 a"; +} +declare module "ext/other" { + export const b = "ts3.0 b"; +} + +//// [main.ts] +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.0 a" = a; +const bb: "ts3.0 b" = b; + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +const aa = ext_1.a; +const bb = other_1.b; diff --git a/tests/baselines/reference/typesVersions.ambientModules.symbols b/tests/baselines/reference/typesVersions.ambientModules.symbols new file mode 100644 index 00000000000..d8a0ab0f2ca --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : Symbol(a, Decl(main.ts, 0, 8)) + +import { b } from "ext/other"; +>b : Symbol(b, Decl(main.ts, 1, 8)) + +const aa: "ts3.0 a" = a; +>aa : Symbol(aa, Decl(main.ts, 3, 5)) +>a : Symbol(a, Decl(main.ts, 0, 8)) + +const bb: "ts3.0 b" = b; +>bb : Symbol(bb, Decl(main.ts, 4, 5)) +>b : Symbol(b, Decl(main.ts, 1, 8)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +declare module "ext" { +>"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) + + export const a = "ts3.0 a"; +>a : Symbol(a, Decl(index.d.ts, 1, 16)) +} +declare module "ext/other" { +>"ext/other" : Symbol("ext/other", Decl(index.d.ts, 2, 1)) + + export const b = "ts3.0 b"; +>b : Symbol(b, Decl(index.d.ts, 4, 16)) +} + diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json new file mode 100644 index 00000000000..990834accc2 --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -0,0 +1,46 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' does not exist.", + "Directory 'tests/cases/conformance/moduleResolution/node_modules/@types' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.js' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.jsx' does not exist.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name 'ext/other' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.ambientModules.types b/tests/baselines/reference/typesVersions.ambientModules.types new file mode 100644 index 00000000000..20cd4112ebe --- /dev/null +++ b/tests/baselines/reference/typesVersions.ambientModules.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : "ts3.0 a" + +import { b } from "ext/other"; +>b : "ts3.0 b" + +const aa: "ts3.0 a" = a; +>aa : "ts3.0 a" +>a : "ts3.0 a" + +const bb: "ts3.0 b" = b; +>bb : "ts3.0 b" +>b : "ts3.0 b" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +declare module "ext" { +>"ext" : typeof import("ext") + + export const a = "ts3.0 a"; +>a : "ts3.0 a" +>"ts3.0 a" : "ts3.0 a" +} +declare module "ext/other" { +>"ext/other" : typeof import("ext/other") + + export const b = "ts3.0 b"; +>b : "ts3.0 b" +>"ts3.0 b" : "ts3.0 b" +} + diff --git a/tests/baselines/reference/typesVersions.multiFile.js b/tests/baselines/reference/typesVersions.multiFile.js new file mode 100644 index 00000000000..98a1331500b --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.js @@ -0,0 +1,39 @@ +//// [tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": "ts3.0" + } +} + +//// [index.d.ts] +export const a = "default a"; + +//// [other.d.ts] +export const b = "default b"; + +//// [index.d.ts] +export const a = "ts3.0 a"; + +//// [other.d.ts] +export const b = "ts3.0 b"; + +//// [main.ts] +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.0 a" = a; +const bb: "ts3.0 b" = b; + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +const aa = ext_1.a; +const bb = other_1.b; diff --git a/tests/baselines/reference/typesVersions.multiFile.symbols b/tests/baselines/reference/typesVersions.multiFile.symbols new file mode 100644 index 00000000000..c79bb054609 --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/moduleResolution/node_modules/ext/index.d.ts === +export const a = "default a"; +>a : Symbol(a, Decl(index.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/other.d.ts === +export const b = "default b"; +>b : Symbol(b, Decl(other.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +export const a = "ts3.0 a"; +>a : Symbol(a, Decl(index.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts === +export const b = "ts3.0 b"; +>b : Symbol(b, Decl(other.d.ts, 0, 12)) + +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : Symbol(a, Decl(main.ts, 0, 8)) + +import { b } from "ext/other"; +>b : Symbol(b, Decl(main.ts, 1, 8)) + +const aa: "ts3.0 a" = a; +>aa : Symbol(aa, Decl(main.ts, 3, 5)) +>a : Symbol(a, Decl(main.ts, 0, 8)) + +const bb: "ts3.0 b" = b; +>bb : Symbol(bb, Decl(main.ts, 4, 5)) +>b : Symbol(b, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json new file mode 100644 index 00000000000..0ef02bb8a02 --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -0,0 +1,31 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.multiFile.types b/tests/baselines/reference/typesVersions.multiFile.types new file mode 100644 index 00000000000..c0634803d29 --- /dev/null +++ b/tests/baselines/reference/typesVersions.multiFile.types @@ -0,0 +1,35 @@ +=== tests/cases/conformance/moduleResolution/node_modules/ext/index.d.ts === +export const a = "default a"; +>a : "default a" +>"default a" : "default a" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/other.d.ts === +export const b = "default b"; +>b : "default b" +>"default b" : "default b" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +export const a = "ts3.0 a"; +>a : "ts3.0 a" +>"ts3.0 a" : "ts3.0 a" + +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts === +export const b = "ts3.0 b"; +>b : "ts3.0 b" +>"ts3.0 b" : "ts3.0 b" + +=== tests/cases/conformance/moduleResolution/main.ts === +import { a } from "ext"; +>a : "ts3.0 a" + +import { b } from "ext/other"; +>b : "ts3.0 b" + +const aa: "ts3.0 a" = a; +>aa : "ts3.0 a" +>a : "ts3.0 a" + +const bb: "ts3.0 b" = b; +>bb : "ts3.0 b" +>b : "ts3.0 b" + diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json index 6cd025d099a..30d0122b8fd 100644 --- a/tests/baselines/reference/typingsLookup4.trace.json +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -5,6 +5,7 @@ "File '/node_modules/jquery.ts' does not exist.", "File '/node_modules/jquery.tsx' does not exist.", "File '/node_modules/jquery.d.ts' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "File '/node_modules/@types/jquery.d.ts' does not exist.", @@ -18,6 +19,7 @@ "File '/node_modules/kquery.ts' does not exist.", "File '/node_modules/kquery.tsx' does not exist.", "File '/node_modules/kquery.d.ts' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "File '/node_modules/@types/kquery.d.ts' does not exist.", @@ -35,6 +37,7 @@ "File '/node_modules/lquery.ts' does not exist.", "File '/node_modules/lquery.tsx' does not exist.", "File '/node_modules/lquery.d.ts' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "File '/node_modules/@types/lquery.d.ts' does not exist.", @@ -50,6 +53,7 @@ "File '/node_modules/mquery.ts' does not exist.", "File '/node_modules/mquery.tsx' does not exist.", "File '/node_modules/mquery.d.ts' does not exist.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "File '/node_modules/@types/mquery.d.ts' does not exist.", @@ -65,6 +69,7 @@ "======== Module name 'mquery' was successfully resolved to '/node_modules/@types/mquery/mquery/index.tsx'. ========", "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", @@ -73,6 +78,7 @@ "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", @@ -85,6 +91,7 @@ "======== Type reference directive 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", @@ -95,6 +102,7 @@ "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: true. ========", "======== Resolving type reference directive 'mquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", diff --git a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts new file mode 100644 index 00000000000..781740d96d2 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts @@ -0,0 +1,39 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @noImplicitReferences: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": "ts3.0" + } +} + +// @filename: node_modules/ext/index.d.ts +declare module "ext" { + export const a = "default a"; +} +declare module "ext/other" { + export const b = "default b"; +} + +// @filename: node_modules/ext/ts3.0/index.d.ts +declare module "ext" { + export const a = "ts3.0 a"; +} +declare module "ext/other" { + export const b = "ts3.0 b"; +} + +// @filename: main.ts +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.0 a" = a; +const bb: "ts3.0 b" = b; + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts new file mode 100644 index 00000000000..44cf98e45c6 --- /dev/null +++ b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts @@ -0,0 +1,34 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": "ts3.0" + } +} + +// @filename: node_modules/ext/index.d.ts +export const a = "default a"; + +// @filename: node_modules/ext/other.d.ts +export const b = "default b"; + +// @filename: node_modules/ext/ts3.0/index.d.ts +export const a = "ts3.0 a"; + +// @filename: node_modules/ext/ts3.0/other.d.ts +export const b = "ts3.0 b"; + +// @filename: main.ts +import { a } from "ext"; +import { b } from "ext/other"; + +const aa: "ts3.0 a" = a; +const bb: "ts3.0 b" = b; + +// @filename: tsconfig.json +{} \ No newline at end of file From 6f7a37c99aa43267f2aae4ade4db840fc344035d Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 20 Aug 2018 17:44:34 -0700 Subject: [PATCH 018/146] Added fourslash test --- src/compiler/moduleNameResolver.ts | 60 ++++++++++--------- src/services/pathCompletions.ts | 28 ++++++++- ...tionForStringLiteralNonrelativeImport13.ts | 36 +++++++++++ 3 files changed, 95 insertions(+), 29 deletions(-) create mode 100644 tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index d1054579e84..c474226217e 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -125,6 +125,34 @@ namespace ts { } } + /* @internal */ + export function getPackageJsonTypesVersionsOverride(typesVersions: MapLike) { + const typeScriptVersion = Version.parse(version); + let bestVersion: Version | undefined; + let bestVersionKey: string | undefined; + for (const key in typesVersions) { + if (!hasProperty(typesVersions, key)) continue; + + const keyVersion = Version.tryParse(key); + if (keyVersion === undefined) { + continue; + } + + // match the greatest version less than the current TypeScript version + if (keyVersion.compareTo(typeScriptVersion) <= 0 + && (bestVersion === undefined || keyVersion.compareTo(bestVersion) > 0)) { + bestVersion = keyVersion; + bestVersionKey = key; + } + } + + if (!bestVersionKey) { + return; + } + + return { version: bestVersionKey, directory: typesVersions[bestVersionKey] }; + } + function tryReadPackageJsonTypesVersion(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState): string | undefined { if (!hasProperty(jsonContent, "typesVersions")) { if (state.traceEnabled) { @@ -141,36 +169,12 @@ namespace ts { return; } - const typeScriptVersion = Version.parse(version); - let bestVersion: Version | undefined; - let bestVersionKey: string | undefined; - for (const key in typesVersions) { - if (!hasProperty(typesVersions, key)) continue; - - const keyVersion = Version.tryParse(key); - if (keyVersion === undefined) { - if (state.traceEnabled) { - // TODO(rbuckton): log - } - continue; - } - - // match the greatest version less than the current TypeScript version - if (keyVersion.compareTo(typeScriptVersion) <= 0 - && (bestVersion === undefined || keyVersion.compareTo(bestVersion) > 0)) { - bestVersion = keyVersion; - bestVersionKey = key; - } + const result = getPackageJsonTypesVersionsOverride(typesVersions); + if (!result) { + return undefined; } - if (!bestVersionKey) { - if (state.traceEnabled) { - // TODO(rbuckton): log - } - return; - } - - const bestVersionPath = typesVersions[bestVersionKey]; + const { version: bestVersionKey, directory: bestVersionPath } = result; if (!isString(bestVersionPath)) { if (state.traceEnabled) { trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersion['${bestVersionKey}']`, "string", typeof bestVersionPath); diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index 3a546573db7..f958163bb14 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -107,10 +107,24 @@ namespace ts.Completions.PathCompletions { // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths const absolutePath = resolvePath(scriptPath, fragment); - const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); + let baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { + // check for a version redirect + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const typesVersions = (packageJson as any).typesVersions; + if (typeof typesVersions === "object") { + const result = getPackageJsonTypesVersionsOverride(typesVersions); + const versionPath = result && result.directory; + if (versionPath) { + baseDirectory = resolvePath(baseDirectory, versionPath); + } + } + } + // Enumerate the available files if possible const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -390,6 +404,18 @@ namespace ts.Completions.PathCompletions { return paths; } + function findPackageJson(directory: string, host: LanguageServiceHost): string | undefined { + let packageJson: string | undefined; + forEachAncestorDirectory(directory, ancestor => { + if (ancestor === "node_modules") return true; + packageJson = findConfigFile(ancestor, (f) => tryFileExists(host, f), "package.json"); + if (packageJson) { + return true; // break out + } + }); + return packageJson; + } + function enumerateNodeModulesVisibleToScript(host: LanguageServiceHost, scriptPath: string): ReadonlyArray { if (!host.readFile || !host.fileExists) return emptyArray; diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts new file mode 100644 index 00000000000..db88a272ad5 --- /dev/null +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts @@ -0,0 +1,36 @@ +/// + +// Should give completions based on typesVersions + +// @Filename: node_modules/ext/package.json +//// { +//// "name": "ext", +//// "version": "1.0.0", +//// "types": "index", +//// "typesVersions": { +//// "3.0": "ts3.0" +//// } +//// } + +// @Filename: node_modules/ext/index.d.ts +//// export {}; + +// @Filename: node_modules/ext/aaa.d.ts +//// export {}; + +// @Filename: node_modules/ext/ts3.0/index.d.ts +//// export {}; + +// @Filename: node_modules/ext/ts3.0/zzz.d.ts +//// export {}; + +// @Filename: main.ts +//// import * as ext1 from "ext//*import_as0*/ +//// import ext2 = require("ext//*import_equals0*/ +//// var ext2 = require("ext//*require0*/ + +verify.completions({ + marker: test.markerNames(), + exact: ["index", "zzz"], + isNewIdentifierLocation: true, +}); From 8398a87da77e3cd7aaf5e4dfbac5167cf69d51fc Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 20 Aug 2018 17:50:28 -0700 Subject: [PATCH 019/146] Base version test on 'versionMajorMinor' --- src/compiler/moduleNameResolver.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index c474226217e..bd532e6dd01 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -127,7 +127,7 @@ namespace ts { /* @internal */ export function getPackageJsonTypesVersionsOverride(typesVersions: MapLike) { - const typeScriptVersion = Version.parse(version); + const typeScriptVersion = Version.parse(versionMajorMinor); let bestVersion: Version | undefined; let bestVersionKey: string | undefined; for (const key in typesVersions) { From aa04ef5ce7580c7d16167ca7cc9023ae370ef4e9 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 20 Aug 2018 20:49:52 -0700 Subject: [PATCH 020/146] Adjust subModuleName --- src/compiler/moduleNameResolver.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index bd532e6dd01..21ff919872b 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -934,7 +934,7 @@ namespace ts { if (endsWith(path, ".d.ts")) { return path; } - if (endsWith(path, "/index")) { + if (path === "index" || endsWith(path, "/index")) { return path + ".d.ts"; } return path + "/index.d.ts"; @@ -1069,9 +1069,9 @@ namespace ts { } } - // if (versionPath) { - // subModuleName = combinePaths(versionPath, subModuleName); - // } + if (versionPath) { + subModuleName = combinePaths(versionPath, subModuleName); + } if (!endsWith(subModuleName, Extension.Dts)) { subModuleName = addExtensionAndIndex(subModuleName); From 6835a489173ca19c6fa0186c40f9f0dfc41486e8 Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Tue, 21 Aug 2018 12:19:05 -0400 Subject: [PATCH 021/146] Fixes to the advice for untyped module imports from unknown packages: - For a sub-module, the `declare module` statement needs to refer to the sub-module. - For an import of "./node_modules/foo", don't show advice to install "@types/foo" or `declare module "foo"` because it won't help. Fixes #26581. --- src/compiler/checker.ts | 19 +++++++++++-------- ...port_noImplicitAny_relativePath.errors.txt | 2 -- ...mplicitAny_typesForPackageExist.errors.txt | 8 ++++---- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0b357bd771d..db717c107a9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2248,14 +2248,17 @@ namespace ts { } function errorOnImplicitAnyModule(isError: boolean, errorNode: Node, { packageId, resolvedFileName }: ResolvedModuleFull, moduleReference: string): void { - const errorInfo = packageId - ? chainDiagnosticMessages( - /*details*/ undefined, - typesPackageExists(packageId.name) - ? Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1 - : Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, - packageId.name, - getMangledNameForScopedPackage(packageId.name)) + const errorInfo = !isExternalModuleNameRelative(moduleReference) && packageId + ? typesPackageExists(packageId.name) + ? chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.If_the_0_package_actually_exposes_this_module_consider_sending_a_pull_request_to_amend_https_Colon_Slash_Slashgithub_com_SlashDefinitelyTyped_SlashDefinitelyTyped_Slashtree_Slashmaster_Slashtypes_Slash_1, + packageId.name, getMangledNameForScopedPackage(packageId.name)) + : chainDiagnosticMessages( + /*details*/ undefined, + Diagnostics.Try_npm_install_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, + moduleReference, + getMangledNameForScopedPackage(packageId.name)) : undefined; errorOrSuggestion(isError, errorNode, chainDiagnosticMessages( errorInfo, diff --git a/tests/baselines/reference/untypedModuleImport_noImplicitAny_relativePath.errors.txt b/tests/baselines/reference/untypedModuleImport_noImplicitAny_relativePath.errors.txt index 1aeb8489b8d..6047cfa6a69 100644 --- a/tests/baselines/reference/untypedModuleImport_noImplicitAny_relativePath.errors.txt +++ b/tests/baselines/reference/untypedModuleImport_noImplicitAny_relativePath.errors.txt @@ -1,12 +1,10 @@ /a.ts(1,22): error TS7016: Could not find a declaration file for module './node_modules/foo'. '/node_modules/foo/index.js' implicitly has an 'any' type. - Try `npm install @types/foo` if it exists or add a new declaration (.d.ts) file containing `declare module 'foo';` ==== /a.ts (1 errors) ==== import * as foo from "./node_modules/foo"; ~~~~~~~~~~~~~~~~~~~~ !!! error TS7016: Could not find a declaration file for module './node_modules/foo'. '/node_modules/foo/index.js' implicitly has an 'any' type. -!!! error TS7016: Try `npm install @types/foo` if it exists or add a new declaration (.d.ts) file containing `declare module 'foo';` ==== /node_modules/foo/package.json (0 errors) ==== { "name": "foo", "version": "1.2.3" } diff --git a/tests/baselines/reference/untypedModuleImport_noImplicitAny_typesForPackageExist.errors.txt b/tests/baselines/reference/untypedModuleImport_noImplicitAny_typesForPackageExist.errors.txt index db93cf044c8..1881345fc2d 100644 --- a/tests/baselines/reference/untypedModuleImport_noImplicitAny_typesForPackageExist.errors.txt +++ b/tests/baselines/reference/untypedModuleImport_noImplicitAny_typesForPackageExist.errors.txt @@ -1,11 +1,11 @@ /a.ts(2,25): error TS7016: Could not find a declaration file for module 'foo/sub'. '/node_modules/foo/sub.js' implicitly has an 'any' type. If the 'foo' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/foo` /a.ts(3,25): error TS7016: Could not find a declaration file for module 'bar/sub'. '/node_modules/bar/sub.js' implicitly has an 'any' type. - Try `npm install @types/bar` if it exists or add a new declaration (.d.ts) file containing `declare module 'bar';` + Try `npm install @types/bar` if it exists or add a new declaration (.d.ts) file containing `declare module 'bar/sub';` /a.ts(5,30): error TS7016: Could not find a declaration file for module '@scope/foo/sub'. '/node_modules/@scope/foo/sub.js' implicitly has an 'any' type. If the '@scope/foo' package actually exposes this module, consider sending a pull request to amend 'https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/scope__foo` /a.ts(6,30): error TS7016: Could not find a declaration file for module '@scope/bar/sub'. '/node_modules/@scope/bar/sub.js' implicitly has an 'any' type. - Try `npm install @types/scope__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@scope/bar';` + Try `npm install @types/scope__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@scope/bar/sub';` ==== /a.ts (4 errors) ==== @@ -17,7 +17,7 @@ import * as barSub from "bar/sub"; ~~~~~~~~~ !!! error TS7016: Could not find a declaration file for module 'bar/sub'. '/node_modules/bar/sub.js' implicitly has an 'any' type. -!!! error TS7016: Try `npm install @types/bar` if it exists or add a new declaration (.d.ts) file containing `declare module 'bar';` +!!! error TS7016: Try `npm install @types/bar` if it exists or add a new declaration (.d.ts) file containing `declare module 'bar/sub';` import * as scopeFoo from "@scope/foo"; import * as scopeFooSub from "@scope/foo/sub"; ~~~~~~~~~~~~~~~~ @@ -26,7 +26,7 @@ import * as scopeBarSub from "@scope/bar/sub"; ~~~~~~~~~~~~~~~~ !!! error TS7016: Could not find a declaration file for module '@scope/bar/sub'. '/node_modules/@scope/bar/sub.js' implicitly has an 'any' type. -!!! error TS7016: Try `npm install @types/scope__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@scope/bar';` +!!! error TS7016: Try `npm install @types/scope__bar` if it exists or add a new declaration (.d.ts) file containing `declare module '@scope/bar/sub';` ==== /node_modules/@types/foo/index.d.ts (0 errors) ==== export const foo: number; From ac7c2ba9e2f71edc03fdf3fd2f753d145584cc83 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Tue, 21 Aug 2018 16:18:51 -0700 Subject: [PATCH 022/146] Remove unused overloads of 'deduplicate' and 'deduplicateSorted' --- src/compiler/core.ts | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 1eaab5b1b59..3cd8e1fd115 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -775,7 +775,7 @@ namespace ts { return deduplicated.map(i => array[i]); } - function deduplicateEquality(array: ReadonlyArray, equalityComparer: EqualityComparer) { + function deduplicateEquality(array: ReadonlyArray, equalityComparer?: EqualityComparer) { const result: T[] = []; for (const item of array) { pushIfUnique(result, item, equalityComparer); @@ -789,23 +789,17 @@ namespace ts { * @param comparer An optional `Comparer` used to sort entries before comparison, though the * result will remain in the original order in `array`. */ - export function deduplicate(array: ReadonlyArray, equalityComparer?: EqualityComparer, comparer?: Comparer): T[]; - export function deduplicate(array: ReadonlyArray | undefined, equalityComparer?: EqualityComparer, comparer?: Comparer): T[] | undefined; - export function deduplicate(array: ReadonlyArray | undefined, equalityComparer: EqualityComparer, comparer?: Comparer): T[] | undefined { - return !array ? undefined : - array.length === 0 ? [] : + export function deduplicate(array: ReadonlyArray, equalityComparer?: EqualityComparer, comparer?: Comparer): T[] { + return array.length === 0 ? [] : array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer, comparer) : + comparer ? deduplicateRelational(array, equalityComparer!, comparer) : deduplicateEquality(array, equalityComparer); } /** * Deduplicates an array that has already been sorted. */ - function deduplicateSorted(array: ReadonlyArray, comparer: EqualityComparer | Comparer): T[]; - function deduplicateSorted(array: ReadonlyArray | undefined, comparer: EqualityComparer | Comparer): T[] | undefined; - function deduplicateSorted(array: ReadonlyArray | undefined, comparer: EqualityComparer | Comparer): T[] | undefined { - if (!array) return undefined; + function deduplicateSorted(array: ReadonlyArray, comparer: EqualityComparer | Comparer): T[] { if (array.length === 0) return []; let last = array[0]; From b9afdadf71d76512183c7470159f34c49e545702 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 22 Aug 2018 11:22:09 -0700 Subject: [PATCH 023/146] Remove jsTypings/semver.ts, add unit tests and logging --- src/compiler/diagnosticMessages.json | 8 ++ src/compiler/moduleNameResolver.ts | 27 +++- src/compiler/semver.ts | 125 +++++++++--------- src/jsTyping/jsTyping.ts | 6 +- src/jsTyping/semver.ts | 61 --------- src/jsTyping/tsconfig.json | 3 +- src/testRunner/tsconfig.json | 1 + src/testRunner/unittests/semver.ts | 94 +++++++++++++ src/testRunner/unittests/typingsInstaller.ts | 14 +- src/typingsInstallerCore/typingsInstaller.ts | 9 +- .../typesVersions.ambientModules.trace.json | 6 +- .../typesVersions.multiFile.trace.json | 4 +- 12 files changed, 207 insertions(+), 151 deletions(-) delete mode 100644 src/jsTyping/semver.ts create mode 100644 src/testRunner/unittests/semver.ts diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ed528e5b87e..ebe5c3efbcd 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3671,6 +3671,14 @@ "category": "Error", "code": 6205 }, + "'package.json' has invalid version '{0}' in 'typesVersions' field.": { + "category": "Message", + "code": 6206 + }, + "'package.json' does not have a 'typesVersions' entry that matches version '{0}'.": { + "category": "Message", + "code": 6207 + }, "Projects to reference": { "category": "Message", diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 21ff919872b..3b61c2cd83b 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -127,7 +127,14 @@ namespace ts { /* @internal */ export function getPackageJsonTypesVersionsOverride(typesVersions: MapLike) { - const typeScriptVersion = Version.parse(versionMajorMinor); + return getPackageJsonTypesVersionsOverrideWithTrace(typesVersions, /*state*/ undefined); + } + + let typeScriptVersion: Version | undefined; + + function getPackageJsonTypesVersionsOverrideWithTrace(typesVersions: MapLike, state: ModuleResolutionState | undefined) { + if (!typeScriptVersion) typeScriptVersion = new Version(versionMajorMinor); + let bestVersion: Version | undefined; let bestVersionKey: string | undefined; for (const key in typesVersions) { @@ -135,12 +142,15 @@ namespace ts { const keyVersion = Version.tryParse(key); if (keyVersion === undefined) { + if (state && state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_invalid_version_0_in_typesVersions_field, key); + } continue; } // match the greatest version less than the current TypeScript version - if (keyVersion.compareTo(typeScriptVersion) <= 0 - && (bestVersion === undefined || keyVersion.compareTo(bestVersion) > 0)) { + if (keyVersion.compareTo(bestVersion) > 0 && + keyVersion.compareTo(typeScriptVersion) <= 0) { bestVersion = keyVersion; bestVersionKey = key; } @@ -169,22 +179,25 @@ namespace ts { return; } - const result = getPackageJsonTypesVersionsOverride(typesVersions); + const result = getPackageJsonTypesVersionsOverrideWithTrace(typesVersions, state); if (!result) { - return undefined; + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); + } + return; } const { version: bestVersionKey, directory: bestVersionPath } = result; if (!isString(bestVersionPath)) { if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersion['${bestVersionKey}']`, "string", typeof bestVersionPath); + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "string", typeof bestVersionPath); } return; } if (state.traceEnabled) { const path = normalizePath(combinePaths(baseDirectory, bestVersionPath)); - trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, `typesVersion['${bestVersionKey}']`, bestVersionPath, path); + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, `typesVersions['${bestVersionKey}']`, bestVersionPath, path); } return bestVersionPath; diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index a3c4e90d37a..203739f7c95 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -1,48 +1,49 @@ /* @internal */ namespace ts { - // Per https://semver.org/#spec-item-2: - // + // https://semver.org/#spec-item-2 // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor // > version, and Z is the patch version. Each element MUST increase numerically. // // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default // value of `0`. - const versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:(\+[a-z0-9-.]+))?)?)?$/i; + const versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; - // Per https://semver.org/#spec-item-9: - // + // https://semver.org/#spec-item-9 // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers // > MUST NOT include leading zeroes. const prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i; - // Per https://semver.org/#spec-item-10: - // + // https://semver.org/#spec-item-10 // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated // > identifiers immediately following the patch or pre-release version. Identifiers MUST // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. const buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i; - // Per https://semver.org/#spec-item-9: - // + // https://semver.org/#spec-item-9 // > Numeric identifiers MUST NOT include leading zeroes. const numericIdentifierRegExp = /^(0|[1-9]\d*)$/; /** - * Describes a precise semantic version number, per https://semver.org + * Describes a precise semantic version number, https://semver.org */ export class Version { - static readonly zero = new Version(0); - readonly major: number; readonly minor: number; readonly patch: number; readonly prerelease: ReadonlyArray; readonly build: ReadonlyArray; - constructor(major: number, minor = 0, patch = 0, prerelease = "", build = "") { + constructor(text: string); + constructor(major: number, minor?: number, patch?: number, prerelease?: string, build?: string); + constructor(major: number | string, minor = 0, patch = 0, prerelease = "", build = "") { + if (typeof major === "string") { + const result = Debug.assertDefined(tryParseComponents(major), "Invalid version"); + ({ major, minor, patch, prerelease, build } = result); + } + Debug.assert(major >= 0, "Invalid argument: major"); Debug.assert(minor >= 0, "Invalid argument: minor"); Debug.assert(patch >= 0, "Invalid argument: patch"); @@ -51,104 +52,102 @@ namespace ts { this.major = major; this.minor = minor; this.patch = patch; - this.prerelease = prerelease === "" ? emptyArray : prerelease.split("."); - this.build = build === "" ? emptyArray : build.split("."); - } - - static parse(text: string) { - return Debug.assertDefined(this.tryParse(text)); + this.prerelease = prerelease ? prerelease.split(".") : emptyArray; + this.build = build ? build.split(".") : emptyArray; } static tryParse(text: string) { - const match = versionRegExp.exec(text); - if (!match) return undefined; + const result = tryParseComponents(text); + if (!result) return undefined; - const [, major, minor = 0, patch = 0, prerelease, build] = match; - if (prerelease && !prereleaseRegExp.test(prerelease)) return undefined; - if (build && !buildRegExp.test(build)) return undefined; - return new Version(+major, +minor, +patch, prerelease, build); + const { major, minor, patch, prerelease, build } = result; + return new Version(major, minor, patch, prerelease, build); } - static compare(left: Version | undefined, right: Version | undefined, compareBuildMetadata?: boolean) { - // Per https://semver.org/#spec-item-11: - // + compareTo(other: Version | undefined) { + // https://semver.org/#spec-item-11 // > Precedence is determined by the first difference when comparing each of these // > identifiers from left to right as follows: Major, minor, and patch versions are // > always compared numerically. // - // > When major, minor, and patch are equal, a pre-release version has lower - // > precedence than a normal version. + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] // - // Per https://semver.org/#spec-item-10: - // - // > Build metadata SHOULD be ignored when determining version precedence. - if (left === right) return Comparison.EqualTo; - if (left === undefined) return Comparison.LessThan; - if (right === undefined) return Comparison.GreaterThan; - return compareValues(left.major, right.major) - || compareValues(left.minor, right.minor) - || compareValues(left.patch, right.patch) - || compareVersionFragments(left.prerelease, right.prerelease, /*compareNumericIdentifiers*/ true) - || (compareBuildMetadata ? compareVersionFragments(left.build, right.build, /*compareNumericIdentifiers*/ false) : Comparison.EqualTo); - } - - compareTo(other: Version, compareBuildMetadata?: boolean) { - return Version.compare(this, other, compareBuildMetadata); + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + if (this === other) return Comparison.EqualTo; + if (other === undefined) return Comparison.GreaterThan; + return compareValues(this.major, other.major) + || compareValues(this.minor, other.minor) + || compareValues(this.patch, other.patch) + || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); } toString() { let result = `${this.major}.${this.minor}.${this.patch}`; - if (this.prerelease) result += `-${this.prerelease.join(".")}`; - if (this.build) result += `+${this.build.join(".")}`; + if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; + if (some(this.build)) result += `+${this.build.join(".")}`; return result; } } - function compareVersionFragments(left: ReadonlyArray, right: ReadonlyArray, compareNumericIdentifiers: boolean) { - // Per https://semver.org/#spec-item-11: - // + function tryParseComponents(text: string) { + const match = versionRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "0", patch = "0", prerelease = "", build = ""] = match; + if (prerelease && !prereleaseRegExp.test(prerelease)) return undefined; + if (build && !buildRegExp.test(build)) return undefined; + return { + major: parseInt(major, 10), + minor: parseInt(minor, 10), + patch: parseInt(patch, 10), + prerelease, + build + }; + } + + function comparePrerelaseIdentifiers(left: ReadonlyArray, right: ReadonlyArray) { + // https://semver.org/#spec-item-11 // > When major, minor, and patch are equal, a pre-release version has lower precedence // > than a normal version. if (left === right) return Comparison.EqualTo; if (left.length === 0) return right.length === 0 ? Comparison.EqualTo : Comparison.GreaterThan; if (right.length === 0) return Comparison.LessThan; - // Per https://semver.org/#spec-item-11: - // + // https://semver.org/#spec-item-11 // > Precedence for two pre-release versions with the same major, minor, and patch version // > MUST be determined by comparing each dot separated identifier from left to right until - // > a difference is found + // > a difference is found [...] const length = Math.min(left.length, right.length); for (let i = 0; i < length; i++) { const leftIdentifier = left[i]; const rightIdentifier = right[i]; if (leftIdentifier === rightIdentifier) continue; - const leftIsNumeric = compareNumericIdentifiers && numericIdentifierRegExp.test(leftIdentifier); - const rightIsNumeric = compareNumericIdentifiers && numericIdentifierRegExp.test(rightIdentifier); + const leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier); + const rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier); if (leftIsNumeric || rightIsNumeric) { - // Per https://semver.org/#spec-item-11: - // + // https://semver.org/#spec-item-11 // > Numeric identifiers always have lower precedence than non-numeric identifiers. if (leftIsNumeric !== rightIsNumeric) return leftIsNumeric ? Comparison.LessThan : Comparison.GreaterThan; - // Per https://semver.org/#spec-item-11: - // + // https://semver.org/#spec-item-11 // > identifiers consisting of only digits are compared numerically const result = compareValues(+leftIdentifier, +rightIdentifier); if (result) return result; } else { - // Per https://semver.org/#spec-item-11: - // + // https://semver.org/#spec-item-11 // > identifiers with letters or hyphens are compared lexically in ASCII sort order. const result = compareStringsCaseSensitive(leftIdentifier, rightIdentifier); if (result) return result; } } - // Per https://semver.org/#spec-item-11: - // + // https://semver.org/#spec-item-11 // > A larger set of pre-release fields has a higher precedence than a smaller set, if all // > of the preceding identifiers are equal. return compareValues(left.length, right.length); diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index e9c96ba2bf6..db55ce4993b 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -21,13 +21,13 @@ namespace ts.JsTyping { export interface CachedTyping { typingLocation: string; - version: Semver; + version: Version; } /* @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { - const availableVersion = Semver.parse(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); - return !availableVersion.greaterThan(cachedTyping.version); + const availableVersion = new Version(getProperty(availableTypingVersions, `ts${versionMajorMinor}`) || getProperty(availableTypingVersions, "latest")!); + return availableVersion.compareTo(cachedTyping.version) <= 0; } /* @internal */ diff --git a/src/jsTyping/semver.ts b/src/jsTyping/semver.ts deleted file mode 100644 index 1c58da8c8f7..00000000000 --- a/src/jsTyping/semver.ts +++ /dev/null @@ -1,61 +0,0 @@ -/* @internal */ -namespace ts { - function stringToInt(str: string): number { - const n = parseInt(str, 10); - if (isNaN(n)) { - throw new Error(`Error in parseInt(${JSON.stringify(str)})`); - } - return n; - } - - const isPrereleaseRegex = /^(.*)-next.\d+/; - const prereleaseSemverRegex = /^(\d+)\.(\d+)\.0-next.(\d+)$/; - const semverRegex = /^(\d+)\.(\d+)\.(\d+)$/; - - export class Semver { - static parse(semver: string): Semver { - const isPrerelease = isPrereleaseRegex.test(semver); - const result = Semver.tryParse(semver, isPrerelease); - if (!result) { - throw new Error(`Unexpected semver: ${semver} (isPrerelease: ${isPrerelease})`); - } - return result; - } - - static fromRaw({ major, minor, patch, isPrerelease }: Semver): Semver { - return new Semver(major, minor, patch, isPrerelease); - } - - // This must parse the output of `versionString`. - private static tryParse(semver: string, isPrerelease: boolean): Semver | undefined { - // Per the semver spec : - // "A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes." - const rgx = isPrerelease ? prereleaseSemverRegex : semverRegex; - const match = rgx.exec(semver); - return match ? new Semver(stringToInt(match[1]), stringToInt(match[2]), stringToInt(match[3]), isPrerelease) : undefined; - } - - private constructor( - readonly major: number, readonly minor: number, readonly patch: number, - /** - * If true, this is `major.minor.0-next.patch`. - * If false, this is `major.minor.patch`. - */ - readonly isPrerelease: boolean) { } - - get versionString(): string { - return this.isPrerelease ? `${this.major}.${this.minor}.0-next.${this.patch}` : `${this.major}.${this.minor}.${this.patch}`; - } - - equals(sem: Semver): boolean { - return this.major === sem.major && this.minor === sem.minor && this.patch === sem.patch && this.isPrerelease === sem.isPrerelease; - } - - greaterThan(sem: Semver): boolean { - return this.major > sem.major || this.major === sem.major - && (this.minor > sem.minor || this.minor === sem.minor - && (!this.isPrerelease && sem.isPrerelease || this.isPrerelease === sem.isPrerelease - && this.patch > sem.patch)); - } - } -} \ No newline at end of file diff --git a/src/jsTyping/tsconfig.json b/src/jsTyping/tsconfig.json index 4886463e163..ac5b8b19c29 100644 --- a/src/jsTyping/tsconfig.json +++ b/src/jsTyping/tsconfig.json @@ -16,7 +16,6 @@ "files": [ "shared.ts", "types.ts", - "jsTyping.ts", - "semver.ts" + "jsTyping.ts" ] } diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 12c671f9cf0..744a62811e5 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -73,6 +73,7 @@ "unittests/publicApi.ts", "unittests/reuseProgramStructure.ts", "unittests/session.ts", + "unittests/semver.ts", "unittests/symbolWalker.ts", "unittests/telemetry.ts", "unittests/textChanges.ts", diff --git a/src/testRunner/unittests/semver.ts b/src/testRunner/unittests/semver.ts new file mode 100644 index 00000000000..edc888e1075 --- /dev/null +++ b/src/testRunner/unittests/semver.ts @@ -0,0 +1,94 @@ +namespace ts { + describe("semver", () => { + describe("Version", () => { + function assertVersion(version: Version, [major, minor, patch, prerelease, build]: [number, number, number, string[]?, string[]?]) { + assert.strictEqual(version.major, major); + assert.strictEqual(version.minor, minor); + assert.strictEqual(version.patch, patch); + assert.deepEqual(version.prerelease, prerelease || emptyArray); + assert.deepEqual(version.build, build || emptyArray); + } + describe("new", () => { + it("text", () => { + assertVersion(new Version("1.2.3-pre.4+build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + }); + it("parts", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5"), [1, 2, 3, ["pre", "4"], ["build", "5"]]); + assertVersion(new Version(1, 2, 3), [1, 2, 3]); + assertVersion(new Version(1, 2), [1, 2, 0]); + assertVersion(new Version(1), [1, 0, 0]); + }); + }); + it("toString", () => { + assert.strictEqual(new Version(1, 2, 3, "pre.4", "build.5").toString(), "1.2.3-pre.4+build.5"); + assert.strictEqual(new Version(1, 2, 3, "pre.4").toString(), "1.2.3-pre.4"); + assert.strictEqual(new Version(1, 2, 3, /*prerelease*/ undefined, "build.5").toString(), "1.2.3+build.5"); + assert.strictEqual(new Version(1, 2, 3).toString(), "1.2.3"); + assert.strictEqual(new Version(1, 2).toString(), "1.2.0"); + assert.strictEqual(new Version(1).toString(), "1.0.0"); + }); + it("compareTo", () => { + // https://semver.org/#spec-item-11 + // > Precedence is determined by the first difference when comparing each of these + // > identifiers from left to right as follows: Major, minor, and patch versions are + // > always compared numerically. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("2.0.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.1.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.1")), Comparison.LessThan); + assert.strictEqual(new Version("2.0.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.1.0").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > When major, minor, and patch are equal, a pre-release version has lower + // > precedence than a normal version. + assert.strictEqual(new Version("1.0.0").compareTo(new Version("1.0.0-pre")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.1-pre").compareTo(new Version("1.0.0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-pre").compareTo(new Version("1.0.0")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > identifiers consisting of only digits are compared numerically + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-1").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-2").compareTo(new Version("1.0.0-10")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-10").compareTo(new Version("1.0.0-2")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > identifiers with letters or hyphens are compared lexically in ASCII sort order. + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-b")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a-2").compareTo(new Version("1.0.0-a-10")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b").compareTo(new Version("1.0.0-a")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-a").compareTo(new Version("1.0.0-a")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-A").compareTo(new Version("1.0.0-a")), Comparison.LessThan); + + // https://semver.org/#spec-item-11 + // > Numeric identifiers always have lower precedence than non-numeric identifiers. + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-alpha")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-0")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-0").compareTo(new Version("1.0.0-0")), Comparison.EqualTo); + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha")), Comparison.EqualTo); + + // https://semver.org/#spec-item-11 + // > A larger set of pre-release fields has a higher precedence than a smaller set, if all + // > of the preceding identifiers are equal. + assert.strictEqual(new Version("1.0.0-alpha").compareTo(new Version("1.0.0-alpha.0")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-alpha.0").compareTo(new Version("1.0.0-alpha")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Precedence for two pre-release versions with the same major, minor, and patch version + // > MUST be determined by comparing each dot separated identifier from left to right until + // > a difference is found [...] + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-a.0.b.2")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.1").compareTo(new Version("1.0.0-b.0.a.1")), Comparison.LessThan); + assert.strictEqual(new Version("1.0.0-a.0.b.2").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + assert.strictEqual(new Version("1.0.0-b.0.a.1").compareTo(new Version("1.0.0-a.0.b.1")), Comparison.GreaterThan); + + // https://semver.org/#spec-item-11 + // > Build metadata does not figure into precedence + assert.strictEqual(new Version("1.0.0+build").compareTo(new Version("1.0.0")), Comparison.EqualTo); + }); + }); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/typingsInstaller.ts b/src/testRunner/unittests/typingsInstaller.ts index 6a7e76e15de..a718a12f548 100644 --- a/src/testRunner/unittests/typingsInstaller.ts +++ b/src/testRunner/unittests/typingsInstaller.ts @@ -1322,7 +1322,7 @@ namespace ts.projectSystem { content: "" }; const host = createServerHost([f, node]); - const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: Semver.parse("1.3.0") } }); + const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: new Version("1.3.0") } }); const registry = createTypesRegistry("node"); const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, ["fs", "bar"], registry); @@ -1344,7 +1344,7 @@ namespace ts.projectSystem { content: "" }; const host = createServerHost([f, node]); - const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: Semver.parse("1.3.0") } }); + const cache = createMapFromTemplate({ node: { typingLocation: node.path, version: new Version("1.3.0") } }); const logger = trackingLogger(); const result = JsTyping.discoverTypings(host, logger.log, [f.path], getDirectoryPath(f.path), emptySafeList, cache, { enable: true }, ["fs", "bar"], emptyMap); assert.deepEqual(logger.finish(), [ @@ -1401,8 +1401,8 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.3.0") }, - commander: { typingLocation: commander.path, version: Semver.parse("1.0.0") } + node: { typingLocation: node.path, version: new Version("1.3.0") }, + commander: { typingLocation: commander.path, version: new Version("1.0.0") } }); const registry = createTypesRegistry("node", "commander"); const logger = trackingLogger(); @@ -1427,7 +1427,7 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.0.0") } + node: { typingLocation: node.path, version: new Version("1.0.0") } }); const registry = createTypesRegistry("node"); registry.delete(`ts${versionMajorMinor}`); @@ -1458,8 +1458,8 @@ namespace ts.projectSystem { }; const host = createServerHost([app]); const cache = createMapFromTemplate({ - node: { typingLocation: node.path, version: Semver.parse("1.3.0-next.0") }, - commander: { typingLocation: commander.path, version: Semver.parse("1.3.0-next.0") } + node: { typingLocation: node.path, version: new Version("1.3.0-next.0") }, + commander: { typingLocation: commander.path, version: new Version("1.3.0-next.0") } }); const registry = createTypesRegistry("node", "commander"); registry.get("node")![`ts${versionMajorMinor}`] = "1.3.0-next.1"; diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index 44a51a01779..df83f1a677c 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -252,8 +252,11 @@ namespace ts.server.typingsInstaller { } const info = getProperty(npmLock.dependencies, key); const version = info && info.version; - const semver = Semver.parse(version!); // TODO: GH#18217 - const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: semver }; + if (!version) { + continue; + } + + const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: new Version(version) }; this.packageNameToTypingLocation.set(packageName, newTyping); } } @@ -356,7 +359,7 @@ namespace ts.server.typingsInstaller { // packageName is guaranteed to exist in typesRegistry by filterTypings const distTags = this.typesRegistry.get(packageName)!; - const newVersion = Semver.parse(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); + const newVersion = new Version(distTags[`ts${versionMajorMinor}`] || distTags[this.latestDistTag]); const newTyping: JsTyping.CachedTyping = { typingLocation: typingFile, version: newVersion }; this.packageNameToTypingLocation.set(packageName, newTyping); installedTypingFiles.push(typingFile); diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json index 990834accc2..0bf8bc16c5d 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.trace.json +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -2,7 +2,7 @@ "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", @@ -21,7 +21,7 @@ "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", @@ -33,7 +33,7 @@ "Directory 'node_modules' does not exist, skipping all lookups in it.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.js' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.jsx' does not exist.", diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json index 0ef02bb8a02..2508681421b 100644 --- a/tests/baselines/reference/typesVersions.multiFile.trace.json +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -2,7 +2,7 @@ "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", @@ -21,7 +21,7 @@ "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersion['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", + "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", From 213d374e13b1b6916598d28c1373e050547def20 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 22 Aug 2018 15:27:03 -0700 Subject: [PATCH 024/146] Make equalityComparer non-optional --- src/compiler/core.ts | 6 +++--- src/server/session.ts | 7 +------ 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 3cd8e1fd115..722b42975ee 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -775,7 +775,7 @@ namespace ts { return deduplicated.map(i => array[i]); } - function deduplicateEquality(array: ReadonlyArray, equalityComparer?: EqualityComparer) { + function deduplicateEquality(array: ReadonlyArray, equalityComparer: EqualityComparer) { const result: T[] = []; for (const item of array) { pushIfUnique(result, item, equalityComparer); @@ -789,10 +789,10 @@ namespace ts { * @param comparer An optional `Comparer` used to sort entries before comparison, though the * result will remain in the original order in `array`. */ - export function deduplicate(array: ReadonlyArray, equalityComparer?: EqualityComparer, comparer?: Comparer): T[] { + export function deduplicate(array: ReadonlyArray, equalityComparer: EqualityComparer, comparer?: Comparer): T[] { return array.length === 0 ? [] : array.length === 1 ? array.slice() : - comparer ? deduplicateRelational(array, equalityComparer!, comparer) : + comparer ? deduplicateRelational(array, equalityComparer, comparer) : deduplicateEquality(array, equalityComparer); } diff --git a/src/server/session.ts b/src/server/session.ts index 8d2fbe9e190..43f2e4f76b3 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -266,8 +266,6 @@ namespace ts.server { getValue: (path: Path) => T, projects: Projects, action: (project: Project, value: T) => ReadonlyArray | U | undefined, - comparer?: (a: U, b: U) => number, - areEqual?: (a: U, b: U) => boolean, ): U[] { const outputs = flatMap(isArray(projects) ? projects : projects.projects, project => action(project, defaultValue)); if (!isArray(projects) && projects.symLinkedProjects) { @@ -276,10 +274,7 @@ namespace ts.server { outputs.push(...flatMap(projects, project => action(project, value))); }); } - - return comparer - ? sortAndDeduplicate(outputs, comparer, areEqual) - : deduplicate(outputs, areEqual); + return deduplicate(outputs, equateValues); } function combineProjectOutputFromEveryProject(projectService: ProjectService, action: (project: Project) => ReadonlyArray, areEqual: (a: T, b: T) => boolean) { From 3ec2c45f5fa68ed53b723bb9d20bd3e2bd607d95 Mon Sep 17 00:00:00 2001 From: Nathan Day Date: Wed, 15 Aug 2018 01:08:13 -0400 Subject: [PATCH 025/146] include leading non-ASCII horizontal whitespace in SyntaxKind.WhitespaceTrivia token --- src/compiler/scanner.ts | 18 ++++++++++++++++++ .../scannerNonAsciiHorizontalWhitespace.js | 14 ++++++++++++++ ...scannerNonAsciiHorizontalWhitespace.symbols | 9 +++++++++ .../scannerNonAsciiHorizontalWhitespace.types | 10 ++++++++++ .../scannerNonAsciiHorizontalWhitespace.ts | 6 ++++++ 5 files changed, 57 insertions(+) create mode 100644 tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.js create mode 100644 tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.symbols create mode 100644 tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.types create mode 100644 tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index af74d69ceef..376c18b7205 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1390,6 +1390,24 @@ namespace ts { case CharacterCodes.verticalTab: case CharacterCodes.formFeed: case CharacterCodes.space: + case CharacterCodes.nonBreakingSpace: + case CharacterCodes.ogham: + case CharacterCodes.enQuad: + case CharacterCodes.emQuad: + case CharacterCodes.enSpace: + case CharacterCodes.emSpace: + case CharacterCodes.threePerEmSpace: + case CharacterCodes.fourPerEmSpace: + case CharacterCodes.sixPerEmSpace: + case CharacterCodes.figureSpace: + case CharacterCodes.punctuationSpace: + case CharacterCodes.thinSpace: + case CharacterCodes.hairSpace: + case CharacterCodes.zeroWidthSpace: + case CharacterCodes.narrowNoBreakSpace: + case CharacterCodes.mathematicalSpace: + case CharacterCodes.ideographicSpace: + case CharacterCodes.byteOrderMark: if (skipTrivia) { pos++; continue; diff --git a/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.js b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.js new file mode 100644 index 00000000000..b9ae124f1ef --- /dev/null +++ b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.js @@ -0,0 +1,14 @@ +//// [scannerNonAsciiHorizontalWhitespace.ts] +//// [scannerNonAsciiHorizontalWhitespace.ts] +"  function f() {}" + +//// [scannerNonAsciiHorizontalWhitespace.js] +"  function f() {}" + + + +//// [scannerNonAsciiHorizontalWhitespace.js] +//// [scannerNonAsciiHorizontalWhitespace.ts] +"  function f() {}"; +//// [scannerNonAsciiHorizontalWhitespace.js] +"  function f() {}"; diff --git a/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.symbols b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.symbols new file mode 100644 index 00000000000..8a7fdec1d33 --- /dev/null +++ b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.symbols @@ -0,0 +1,9 @@ +=== tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts === +//// [scannerNonAsciiHorizontalWhitespace.ts] +No type information for this code."  function f() {}" +No type information for this code. +No type information for this code.//// [scannerNonAsciiHorizontalWhitespace.js] +No type information for this code."  function f() {}" +No type information for this code. +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.types b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.types new file mode 100644 index 00000000000..5d68e59d73b --- /dev/null +++ b/tests/baselines/reference/scannerNonAsciiHorizontalWhitespace.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts === +//// [scannerNonAsciiHorizontalWhitespace.ts] +"  function f() {}" +>"  function f() {}" : "  function f() {}" + +//// [scannerNonAsciiHorizontalWhitespace.js] +"  function f() {}" +>"  function f() {}" : "  function f() {}" + + diff --git a/tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts b/tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts new file mode 100644 index 00000000000..447cad65684 --- /dev/null +++ b/tests/cases/conformance/scanner/ecmascript5/scannerNonAsciiHorizontalWhitespace.ts @@ -0,0 +1,6 @@ +//// [scannerNonAsciiHorizontalWhitespace.ts] +"  function f() {}" + +//// [scannerNonAsciiHorizontalWhitespace.js] +"  function f() {}" + From dc5cd9676bfe36cf2e68cb7ce63f3662acc5dc06 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Mon, 27 Aug 2018 12:06:45 -0700 Subject: [PATCH 026/146] Switch to paths-like pattern matching --- src/compiler/diagnosticMessages.json | 6 +- src/compiler/moduleNameResolver.ts | 553 ++++++++++-------- src/compiler/moduleSpecifiers.ts | 40 +- src/compiler/transformers/declarations.ts | 7 + src/services/pathCompletions.ts | 63 +- ...age_relativeImportWithinPackage.trace.json | 2 +- ...ativeImportWithinPackage_scoped.trace.json | 2 +- .../reference/library-reference-10.trace.json | 6 +- .../reference/library-reference-11.trace.json | 2 +- .../reference/library-reference-12.trace.json | 2 +- .../reference/library-reference-2.trace.json | 6 +- ...lutionWithExtensions_unexpected.trace.json | 4 +- ...utionWithExtensions_unexpected2.trace.json | 4 +- ...on_packageJson_notAtPackageRoot.trace.json | 2 +- ...AtPackageRoot_fakeScopedPackage.trace.json | 2 +- ...ution_packageJson_scopedPackage.trace.json | 2 +- ...ageRoot_mainFieldInSubDirectory.trace.json | 2 +- .../reference/packageJsonMain.trace.json | 12 +- .../packageJsonMain_isNonRecursive.trace.json | 4 +- ...eactTransitiveImportHasValidDeclaration.js | 1 - .../reference/typesVersions.ambientModules.js | 2 +- .../typesVersions.ambientModules.trace.json | 31 +- .../reference/typesVersions.multiFile.js | 2 +- .../typesVersions.multiFile.trace.json | 24 +- .../typesVersionsDeclarationEmit.ambient.js | 51 ++ ...pesVersionsDeclarationEmit.ambient.symbols | 37 ++ ...VersionsDeclarationEmit.ambient.trace.json | 55 ++ ...typesVersionsDeclarationEmit.ambient.types | 33 ++ .../typesVersionsDeclarationEmit.multiFile.js | 48 ++ ...sVersionsDeclarationEmit.multiFile.symbols | 47 ++ ...rsionsDeclarationEmit.multiFile.trace.json | 37 ++ ...pesVersionsDeclarationEmit.multiFile.types | 37 ++ .../reference/typingsLookup4.trace.json | 20 +- .../typesVersionsDeclarationEmit.ambient.ts | 43 ++ .../typesVersionsDeclarationEmit.multiFile.ts | 39 ++ .../typesVersions.ambientModules.ts | 2 +- .../typesVersions.multiFile.ts | 2 +- ...tionForStringLiteralNonrelativeImport13.ts | 4 +- 38 files changed, 877 insertions(+), 359 deletions(-) create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types create mode 100644 tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts create mode 100644 tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index ebe5c3efbcd..69cc7c018f4 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3671,7 +3671,7 @@ "category": "Error", "code": 6205 }, - "'package.json' has invalid version '{0}' in 'typesVersions' field.": { + "'package.json' has a 'typesVersions' field with version-specific path mappings.": { "category": "Message", "code": 6206 }, @@ -3679,6 +3679,10 @@ "category": "Message", "code": 6207 }, + "'package.json' has a 'typesVersions' entry '{0}' that matches compiler version '{1}', looking for a pattern to match module name '{2}'.": { + "category": "Message", + "code": 6208 + }, "Projects to reference": { "category": "Message", diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 3b61c2cd83b..6545ce353e6 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -24,6 +24,13 @@ namespace ts { return withPackageId(/*packageId*/ undefined, r); } + function removeIgnoredPackageId(r: Resolved | undefined): PathAndExtension | undefined { + if (r) { + Debug.assert(r.packageId === undefined); + return { path: r.path, ext: r.extension }; + } + } + /** Result of trying to resolve a module. */ interface Resolved { path: string; @@ -82,13 +89,14 @@ namespace ts { host: ModuleResolutionHost; compilerOptions: CompilerOptions; traceEnabled: boolean; + failedLookupLocations: Push; } /** Just the fields that we use for module resolution. */ interface PackageJsonPathFields { typings?: string; types?: string; - typesVersions?: MapLike; + typesVersions?: MapLike>; main?: string; } @@ -97,42 +105,89 @@ namespace ts { version?: string; } - /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonFields(readTypes: boolean, jsonContent: PackageJsonPathFields, baseDirectory: string, state: ModuleResolutionState): string | undefined { - return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); + type MatchingKeys = K extends (TRecord[K] extends TMatch ? K : never) ? K : never; - function tryReadFromField(fieldName: "typings" | "types" | "main"): string | undefined { - if (!hasProperty(jsonContent, fieldName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); - } - return; - } - - const fileName = jsonContent[fieldName]; - if (!isString(fileName)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, "string", typeof fileName); - } - return; - } - - const path = normalizePath(combinePaths(baseDirectory, fileName)); + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "string", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField>(jsonContent: PackageJson, fieldName: K, typeOfTag: "object", state: ModuleResolutionState): PackageJson[K] | undefined; + function readPackageJsonField(jsonContent: PackageJson, fieldName: K, typeOfTag: "string" | "object", state: ModuleResolutionState): PackageJson[K] | undefined { + if (!hasProperty(jsonContent, fieldName)) { if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, fieldName); } - return path; + return; } + const value = jsonContent[fieldName]; + if (typeof value !== typeOfTag || value === null) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, fieldName, typeOfTag, value === null ? "null" : typeof value); + } + return; + } + return value; } - /* @internal */ - export function getPackageJsonTypesVersionsOverride(typesVersions: MapLike) { - return getPackageJsonTypesVersionsOverrideWithTrace(typesVersions, /*state*/ undefined); + function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { + const fileName = readPackageJsonField(jsonContent, fieldName, "string", state); + if (fileName === undefined) return; + const path = normalizePath(combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; + } + + function readPackageJsonTypesFields(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state) + || readPackageJsonPathField(jsonContent, "types", baseDirectory, state); + } + + function readPackageJsonMainField(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState) { + return readPackageJsonPathField(jsonContent, "main", baseDirectory, state); + } + + function readPackageJsonTypesVersionsField(jsonContent: PackageJson, state: ModuleResolutionState) { + const typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state); + if (typesVersions === undefined) return; + + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings); + } + + return typesVersions; + } + + interface VersionPaths { + version: string; + paths: MapLike; + } + + function readPackageJsonTypesVersionPaths(jsonContent: PackageJson, state: ModuleResolutionState): VersionPaths | undefined { + const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); + if (typesVersions === undefined) return; + + const result = getPackageJsonTypesVersionsPaths(typesVersions); + if (!result) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); + } + return; + } + + const { version: bestVersionKey, paths: bestVersionPaths } = result; + if (typeof bestVersionPaths !== "object") { + if (state.traceEnabled) { + trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "object", typeof bestVersionPaths); + } + return; + } + + return result; } let typeScriptVersion: Version | undefined; - function getPackageJsonTypesVersionsOverrideWithTrace(typesVersions: MapLike, state: ModuleResolutionState | undefined) { + /* @internal */ + export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>) { if (!typeScriptVersion) typeScriptVersion = new Version(versionMajorMinor); let bestVersion: Version | undefined; @@ -142,9 +197,6 @@ namespace ts { const keyVersion = Version.tryParse(key); if (keyVersion === undefined) { - if (state && state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_invalid_version_0_in_typesVersions_field, key); - } continue; } @@ -160,47 +212,7 @@ namespace ts { return; } - return { version: bestVersionKey, directory: typesVersions[bestVersionKey] }; - } - - function tryReadPackageJsonTypesVersion(jsonContent: PackageJson, baseDirectory: string, state: ModuleResolutionState): string | undefined { - if (!hasProperty(jsonContent, "typesVersions")) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_a_0_field, "typesVersions"); - } - return; - } - - const typesVersions = jsonContent.typesVersions; - if (typeof typesVersions !== "object") { - if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions", "object", typeof typesVersions); - } - return; - } - - const result = getPackageJsonTypesVersionsOverrideWithTrace(typesVersions, state); - if (!result) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, versionMajorMinor); - } - return; - } - - const { version: bestVersionKey, directory: bestVersionPath } = result; - if (!isString(bestVersionPath)) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, `typesVersions['${bestVersionKey}']`, "string", typeof bestVersionPath); - } - return; - } - - if (state.traceEnabled) { - const path = normalizePath(combinePaths(baseDirectory, bestVersionPath)); - trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, `typesVersions['${bestVersionKey}']`, bestVersionPath, path); - } - - return bestVersionPath; + return { version: bestVersionKey, paths: typesVersions[bestVersionKey] }; } export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined { @@ -250,7 +262,8 @@ namespace ts { */ export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations { const traceEnabled = isTraceEnabled(options, host); - const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled }; + const failedLookupLocations: string[] = []; + const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; const typeRoots = getEffectiveTypeRoots(options, host); if (traceEnabled) { @@ -272,8 +285,6 @@ namespace ts { } } - const failedLookupLocations: string[] = []; - let resolved = primaryLookup(); let primary = true; if (!resolved) { @@ -309,7 +320,7 @@ namespace ts { trace(host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory); } return resolvedTypeScriptOnly( - loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, failedLookupLocations, + loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState)); }); } @@ -328,7 +339,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - const result = loadModuleFromNodeModules(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*cache*/ undefined); + const result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined); const resolvedFile = resolvedTypeScriptOnly(result && result.value); if (!resolvedFile && traceEnabled) { trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); @@ -366,7 +377,7 @@ namespace ts { if (host.directoryExists(root)) { for (const typeDirectivePath of host.getDirectories(root)) { const normalized = normalizePath(typeDirectivePath); - const packageJsonPath = pathToPackageJson(combinePaths(root, normalized)); + const packageJsonPath = combinePaths(root, normalized, "package.json"); // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types. // See `createNotNeededPackageJSON` in the types-publisher` repo. // tslint:disable-next-line:no-null-keyword @@ -589,7 +600,7 @@ namespace ts { * 'typings' entry or file 'index' with some supported extension * - Classic loader will only try to interpret '/a/b/c' as file. */ - type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; + type ResolutionKindSpecificLoader = (extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState) => Resolved | undefined; /** * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to @@ -652,18 +663,18 @@ namespace ts { * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. */ function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { if (!isExternalModuleNameRelative(moduleName)) { - return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, failedLookupLocations, state); + return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } else { - return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state); } } function tryLoadModuleUsingRootDirs(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, - failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { + state: ModuleResolutionState): Resolved | undefined { if (!state.compilerOptions.rootDirs) { return undefined; @@ -708,7 +719,7 @@ namespace ts { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); } - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(containingDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -727,7 +738,7 @@ namespace ts { trace(state.host, Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate); } const baseDirectory = getDirectoryPath(candidate); - const resolvedFileName = loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + const resolvedFileName = loader(extensions, candidate, !directoryProbablyExists(baseDirectory, state.host), state); if (resolvedFileName) { return resolvedFileName; } @@ -739,59 +750,28 @@ namespace ts { return undefined; } - function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - if (!state.compilerOptions.baseUrl) { + function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { + const { baseUrl, paths } = state.compilerOptions; + if (!baseUrl) { return undefined; } if (state.traceEnabled) { - trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + trace(state.host, Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName); } - - // string is for exact match - let matchedPattern: Pattern | string | undefined; - if (state.compilerOptions.paths) { + if (paths) { if (state.traceEnabled) { trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(getOwnKeys(state.compilerOptions.paths), moduleName); - } - - if (matchedPattern) { - const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); - const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + const resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); + if (resolved) { + return resolved.value; } - return forEach(state.compilerOptions.paths![matchedPatternText], subst => { - const path = matchedStar ? subst.replace("*", matchedStar) : subst; - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl!, path)); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - // A path mapping may have an extension, in contrast to an import, which should omit it. - const extension = tryGetExtensionFromPath(candidate); - if (extension !== undefined) { - const path = tryFile(candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (path !== undefined) { - return noPackageId({ path, ext: extension }); - } - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); - }); } - else { - const candidate = normalizePath(combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - - return loader(extensions, candidate, failedLookupLocations, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + const candidate = normalizePath(combinePaths(baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate); } - } - - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + return loader(extensions, candidate, !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); } /** @@ -809,11 +789,15 @@ namespace ts { return resolvedModule.resolvedFileName; } + export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { + return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + } + function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); const failedLookupLocations: string[] = []; - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; const result = jsOnly ? tryResolve(Extensions.JavaScript) : @@ -827,8 +811,8 @@ namespace ts { return { resolvedModule: undefined, failedLookupLocations }; function tryResolve(extensions: Extensions): SearchResult<{ resolved: Resolved, isExternalLibraryImport: boolean }> { - const loader: ResolutionKindSpecificLoader = (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); - const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); + const resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state); if (resolved) { return toSearchResult({ resolved, isExternalLibraryImport: stringContains(resolved.path, nodeModulesPathPart) }); } @@ -837,7 +821,7 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]); } - const resolved = loadModuleFromNodeModules(extensions, moduleName, containingDirectory, failedLookupLocations, state, cache); + const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); if (!resolved) return undefined; let resolvedValue = resolved.value; @@ -851,7 +835,7 @@ namespace ts { } else { const { path: candidate, parts } = normalizePathAndParts(combinePaths(containingDirectory, moduleName)); - const resolved = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); + const resolved = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); // Treat explicit "node_modules" import as an external library import. return resolved && toSearchResult({ resolved, isExternalLibraryImport: contains(parts, "node_modules") }); } @@ -871,7 +855,7 @@ namespace ts { return real; } - function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { + function nodeLoadModuleByRelativeName(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson: boolean): Resolved | undefined { if (state.traceEnabled) { trace(state.host, Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -885,10 +869,11 @@ namespace ts { onlyRecordFailures = true; } } - const resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + const resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state); if (resolvedFromFile) { const nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined; - const packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + const packageInfo = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, /*onlyRecordFailures*/ false, state); + const packageId = packageInfo && packageInfo.packageId; return withPackageId(packageId, resolvedFromFile); } } @@ -901,7 +886,7 @@ namespace ts { onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); + return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson); } /*@internal*/ @@ -953,22 +938,22 @@ namespace ts { return path + "/index.d.ts"; } - function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { - return noPackageId(loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state)); + function loadModuleFromFileNoPackageId(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): Resolved | undefined { + return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state)); } /** * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. */ - function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + function loadModuleFromFile(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { if (extensions === Extensions.Json) { const extensionLess = tryRemoveExtension(candidate, Extension.Json); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state); + return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, onlyRecordFailures, state); } // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state); + const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state); if (resolvedByAddingExtension) { return resolvedByAddingExtension; } @@ -981,12 +966,12 @@ namespace ts { const extension = candidate.substring(extensionless.length); trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); } - return tryAddingExtensions(extensionless, extensions, failedLookupLocations, onlyRecordFailures, state); + return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state); } } /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate: string, extensions: Extensions, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { + function tryAddingExtensions(candidate: string, extensions: Extensions, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { if (!onlyRecordFailures) { // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing const directory = getDirectoryPath(candidate); @@ -1007,13 +992,13 @@ namespace ts { } function tryExtension(ext: Extension): PathAndExtension | undefined { - const path = tryFile(candidate + ext, failedLookupLocations, onlyRecordFailures, state); + const path = tryFile(candidate + ext, onlyRecordFailures, state); return path === undefined ? undefined : { path, ext }; } } /** Return the file if it exists. */ - function tryFile(fileName: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { + function tryFile(fileName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined { if (!onlyRecordFailures) { if (state.host.fileExists(fileName)) { if (state.traceEnabled) { @@ -1027,52 +1012,48 @@ namespace ts { } } } - failedLookupLocations.push(fileName); + state.failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { - const { packageJsonContent, packageId, versionPath } = considerPackageJson - ? getPackageJsonInfo(candidate, "", failedLookupLocations, onlyRecordFailures, state) - : { packageJsonContent: undefined, packageId: undefined, versionPath: undefined }; - if (versionPath) { - candidate = normalizePath(combinePaths(candidate, versionPath)); - } - return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, packageJsonContent)); + function loadNodeModuleFromDirectory(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, considerPackageJson = true) { + const packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, "", onlyRecordFailures, state) : undefined; + const packageId = packageInfo && packageInfo.packageId; + const packageJsonContent = packageInfo && packageInfo.packageJsonContent; + const versionPaths = packageJsonContent && readPackageJsonTypesVersionPaths(packageJsonContent, state); + return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, failedLookupLocations: Push, onlyRecordFailures: boolean, state: ModuleResolutionState, packageJsonContent: PackageJsonPathFields | undefined): PathAndExtension | undefined { - const fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, extensions, candidate, failedLookupLocations, state); + function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, packageJsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined { + const fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); if (fromPackageJson) { return fromPackageJson; } const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); + return loadModuleFromFile(extensions, combinePaths(candidate, "index"), !directoryExists, state); } - function getPackageJsonInfo( - nodeModuleDirectory: string, - subModuleName: string, - failedLookupLocations: Push, - onlyRecordFailures: boolean, - state: ModuleResolutionState, - ): { found: boolean, packageJsonContent: PackageJsonPathFields | undefined, packageId: PackageId | undefined, versionPath: string | undefined } { + interface PackageJsonInfo { + packageJsonContent: PackageJsonPathFields | undefined; + packageId: PackageId | undefined; + versionPaths: VersionPaths | undefined; + } + + function getPackageJsonInfo(packageDirectory: string, subModuleName: string, onlyRecordFailures: boolean, state: ModuleResolutionState): PackageJsonInfo | undefined { const { host, traceEnabled } = state; - const directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); - const packageJsonPath = pathToPackageJson(nodeModuleDirectory); + const directoryExists = !onlyRecordFailures && directoryProbablyExists(packageDirectory, host); + const packageJsonPath = combinePaths(packageDirectory, "package.json"); if (directoryExists && host.fileExists(packageJsonPath)) { const packageJsonContent = readJson(packageJsonPath, host) as PackageJson; - const versionPath = tryReadPackageJsonTypesVersion(packageJsonContent, nodeModuleDirectory, state); if (subModuleName === "") { // looking up the root - need to handle types/typings/main redirects for subModuleName - const versionDirectory = versionPath ? normalizePath(combinePaths(nodeModuleDirectory, versionPath)) : nodeModuleDirectory; - const path = tryReadPackageJsonFields(/*readTypes*/ true, packageJsonContent, versionDirectory, state); + const path = readPackageJsonTypesFields(packageJsonContent, packageDirectory, state); if (typeof path === "string") { - subModuleName = addExtensionAndIndex(path.substring(versionDirectory.length + 1)); + subModuleName = addExtensionAndIndex(path.substring(packageDirectory.length + 1)); } else { - const jsPath = tryReadPackageJsonFields(/*readTypes*/ false, packageJsonContent, nodeModuleDirectory, state); - if (typeof jsPath === "string" && jsPath.length > nodeModuleDirectory.length) { - const potentialSubModule = jsPath.substring(nodeModuleDirectory.length + 1); + const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); + if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { + const potentialSubModule = jsPath.substring(packageDirectory.length + 1); subModuleName = (forEach(supportedJavascriptExtensions, extension => tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts; } @@ -1082,13 +1063,11 @@ namespace ts { } } - if (versionPath) { - subModuleName = combinePaths(versionPath, subModuleName); - } - if (!endsWith(subModuleName, Extension.Dts)) { subModuleName = addExtensionAndIndex(subModuleName); } + + const versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state); const packageId: PackageId | undefined = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName, version: packageJsonContent.version } : undefined; @@ -1100,7 +1079,8 @@ namespace ts { trace(host, Diagnostics.Found_package_json_at_0, packageJsonPath); } } - return { found: true, packageJsonContent, packageId, versionPath }; + + return { packageJsonContent, packageId, versionPaths }; } else { if (directoryExists && traceEnabled) { @@ -1108,17 +1088,18 @@ namespace ts { } // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - return { found: false, packageJsonContent: undefined, packageId: undefined, versionPath: undefined }; + state.failedLookupLocations.push(packageJsonPath); } } - function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, extensions: Extensions, candidate: string, failedLookupLocations: Push, state: ModuleResolutionState): PathAndExtension | undefined { - let file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state); + function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, versionPaths: VersionPaths | undefined, extensions: Extensions, candidate: string, state: ModuleResolutionState): PathAndExtension | undefined { + let file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json + ? readPackageJsonTypesFields(jsonContent, candidate, state) + : readPackageJsonMainField(jsonContent, candidate, state); if (!file) { if (extensions === Extensions.TypeScript) { // When resolving typescript modules, try resolving using main field as well - file = tryReadPackageJsonFields(/*readTypes*/ false, jsonContent, candidate, state); + file = readPackageJsonMainField(jsonContent, candidate, state); if (!file) { return undefined; } @@ -1128,27 +1109,39 @@ namespace ts { } } - const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host); - const fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); - if (fromFile) { - const resolved = resolvedIfExtensionMatches(extensions, fromFile); - if (resolved) { - return resolved; + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const fromFile = tryFile(candidate, onlyRecordFailures, state); + if (fromFile) { + const resolved = resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return noPackageId(resolved); + } + if (state.traceEnabled) { + trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } } + + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); + }; + + const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host); + + if (versionPaths && containsPath(candidate, file)) { + const moduleName = getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, versionMajorMinor, moduleName); + } + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + if (result) { + return removeIgnoredPackageId(result.value); } } - // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" - const nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; - // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. - const result = nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); - if (result) { - // It won't have a `packageId` set, because we disabled `considerPackageJson`. - Debug.assert(result.packageId === undefined); - return { path: result.path, ext: result.extension }; - } + // It won't have a `packageId` set, because we disabled `considerPackageJson`. + return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ @@ -1171,42 +1164,6 @@ namespace ts { } } - function pathToPackageJson(directory: string): string { - return combinePaths(directory, "package.json"); - } - - function loadModuleFromNodeModulesFolder(extensions: Extensions, moduleName: string, nodeModulesFolder: string, nodeModulesFolderExists: boolean, failedLookupLocations: Push, state: ModuleResolutionState): Resolved | undefined { - let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); - // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. - let packageJsonContent: PackageJsonPathFields | undefined; - let versionPath: string | undefined; - let packageId: PackageId | undefined; - const packageInfo = getPackageJsonInfo(candidate, "", failedLookupLocations, /*onlyRecordFailures*/ !nodeModulesFolderExists, state); - if (packageInfo.found) { - ({ packageJsonContent, packageId, versionPath } = packageInfo); - - // If package.json supplied a typescript-version prefix path, apply it to the candidate. - if (versionPath) { - candidate = normalizePath(combinePaths(candidate, versionPath)); - } - } - else { - const { packageName, rest } = parsePackageName(moduleName); - if (rest !== "") { // If "rest" is empty, we just did this search above. - const packageRootPath = combinePaths(nodeModulesFolder, packageName); - // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId. - ({ packageId, versionPath } = getPackageJsonInfo(packageRootPath, rest, failedLookupLocations, !nodeModulesFolderExists, state)); - // If package.json supplied a typescript-version prefix path, apply it to the candidate. - if (versionPath) { - candidate = normalizePath(combinePaths(packageRootPath, versionPath, rest)); - } - } - } - const pathAndExtension = loadModuleFromFile(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state) || - loadNodeModuleFromDirectoryWorker(extensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state, packageJsonContent); - return withPackageId(packageId, pathAndExtension); - } - /* @internal */ export function parsePackageName(moduleName: string): { packageName: string, rest: string } { let idx = moduleName.indexOf(directorySeparator); @@ -1216,35 +1173,36 @@ namespace ts { return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - function loadModuleFromNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNearestNodeModules(extensions, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ false, cache); - } - function loadModuleFromNodeModulesAtTypes(moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState): SearchResult { - // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. - return loadModuleFromNearestNodeModules(Extensions.DtsOnly, moduleName, directory, failedLookupLocations, state, /*typesOnly*/ true, /*cache*/ undefined); + function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { + return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); } - function loadModuleFromNearestNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { + function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName: string, directory: string, state: ModuleResolutionState): SearchResult { + // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly. + return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined); + } + + function loadModuleFromNearestNodeModulesDirectoryWorker(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); return forEachAncestorDirectory(normalizeSlashes(directory), ancestorDirectory => { if (getBaseFileName(ancestorDirectory) !== "node_modules") { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state.traceEnabled, state.host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state); if (resolutionFromCache) { return resolutionFromCache; } - return toSearchResult(loadModuleFromImmediateNodeModules(extensions, moduleName, ancestorDirectory, failedLookupLocations, state, typesOnly)); + return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly)); } }); } - function loadModuleFromImmediateNodeModules(extensions: Extensions, moduleName: string, directory: string, failedLookupLocations: Push, state: ModuleResolutionState, typesOnly: boolean): Resolved | undefined { + function loadModuleFromImmediateNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, typesScopeOnly: boolean): Resolved | undefined { const nodeModulesFolder = combinePaths(directory, "node_modules"); const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); if (!nodeModulesFolderExists && state.traceEnabled) { trace(state.host, Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder); } - const packageResult = typesOnly ? undefined : loadModuleFromNodeModulesFolder(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, failedLookupLocations, state); + const packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state); if (packageResult) { return packageResult; } @@ -1257,7 +1215,84 @@ namespace ts { } nodeModulesAtTypesExists = false; } - return loadModuleFromNodeModulesFolder(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, failedLookupLocations, state); + return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes, nodeModulesAtTypesExists, state); + } + } + + function loadModuleFromSpecificNodeModulesDirectory(extensions: Extensions, moduleName: string, nodeModulesDirectory: string, nodeModulesDirectoryExists: boolean, state: ModuleResolutionState): Resolved | undefined { + const candidate = normalizePath(combinePaths(nodeModulesDirectory, moduleName)); + + // First look for a nested package.json, as in `node_modules/foo/bar/package.json`. + let packageJsonContent: PackageJsonPathFields | undefined; + let packageId: PackageId | undefined; + let versionPaths: VersionPaths | undefined; + + const packageInfo = getPackageJsonInfo(candidate, "", !nodeModulesDirectoryExists, state); + if (packageInfo) { + ({ packageJsonContent, packageId, versionPaths } = packageInfo); + const fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state); + if (fromFile) { + return noPackageId(fromFile); + } + + const fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageJsonContent, versionPaths); + return withPackageId(packageId, fromDirectory); + } + + const loader: ResolutionKindSpecificLoader = (extensions, candidate, onlyRecordFailures, state) => { + const pathAndExtension = + loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) || + loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths); + return withPackageId(packageId, pathAndExtension); + }; + + const { packageName, rest } = parsePackageName(moduleName); + if (rest !== "") { // If "rest" is empty, we just did this search above. + const packageDirectory = combinePaths(nodeModulesDirectory, packageName); + + // Don't use a "types" or "main" from here because we're not loading the root, but a subdirectory -- just here for the packageId and path mappings. + const packageInfo = getPackageJsonInfo(packageDirectory, rest, !nodeModulesDirectoryExists, state); + if (packageInfo) ({ packageId, versionPaths } = packageInfo); + if (versionPaths) { + if (state.traceEnabled) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, versionMajorMinor, rest); + } + const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); + const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); + if (fromPaths) { + return fromPaths.value; + } + } + } + + return loader(extensions, candidate, !nodeModulesDirectoryExists, state); + } + + function tryLoadModuleUsingPaths(extensions: Extensions, moduleName: string, baseDirectory: string, paths: MapLike, loader: ResolutionKindSpecificLoader, onlyRecordFailures: boolean, state: ModuleResolutionState): SearchResult { + const matchedPattern = matchPatternOrExact(getOwnKeys(paths), moduleName); + if (matchedPattern) { + const matchedStar = isString(matchedPattern) ? undefined : matchedText(matchedPattern, moduleName); + const matchedPatternText = isString(matchedPattern) ? matchedPattern : patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + const resolved = forEach(paths[matchedPatternText], subst => { + const path = matchedStar ? subst.replace("*", matchedStar) : subst; + const candidate = normalizePath(combinePaths(baseDirectory, path)); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + // A path mapping may have an extension, in contrast to an import, which should omit it. + const extension = tryGetExtensionFromPath(candidate); + if (extension !== undefined) { + const path = tryFile(candidate, onlyRecordFailures, state); + if (path !== undefined) { + return noPackageId({ path, ext: extension }); + } + } + return loader(extensions, candidate, onlyRecordFailures || !directoryProbablyExists(getDirectoryPath(candidate), state.host), state); + }); + return { value: resolved }; } } @@ -1305,21 +1340,21 @@ namespace ts { typesPackageName; } - function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, traceEnabled: boolean, host: ModuleResolutionHost, failedLookupLocations: Push): SearchResult { + function tryFindNonRelativeModuleNameInCache(cache: PerModuleNameCache | undefined, moduleName: string, containingDirectory: string, state: ModuleResolutionState): SearchResult { const result = cache && cache.get(containingDirectory); if (result) { - if (traceEnabled) { - trace(host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); + if (state.traceEnabled) { + trace(state.host, Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory); } - failedLookupLocations.push(...result.failedLookupLocations); + state.failedLookupLocations.push(...result.failedLookupLocations); return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } }; } } export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: NonRelativeModuleNameResolutionCache): ResolvedModuleWithFailedLookupLocations { const traceEnabled = isTraceEnabled(compilerOptions, host); - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; const containingDirectory = getDirectoryPath(containingFile); const resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript); @@ -1327,7 +1362,7 @@ namespace ts { return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations); function tryResolve(extensions: Extensions): SearchResult { - const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, failedLookupLocations, state); + const resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state); if (resolvedUsingSettings) { return { value: resolvedUsingSettings }; } @@ -1336,24 +1371,24 @@ namespace ts { const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); // Climb up parent directories looking for a module. const resolved = forEachAncestorDirectory(containingDirectory, directory => { - const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host, failedLookupLocations); + const resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, state); if (resolutionFromCache) { return resolutionFromCache; } const searchName = normalizePath(combinePaths(directory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state)); }); if (resolved) { return resolved; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. - return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state); } } else { const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); - return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state)); + return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state)); } } } @@ -1368,9 +1403,9 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, projectName, moduleName, globalCache); } - const state: ModuleResolutionState = { compilerOptions, host, traceEnabled }; const failedLookupLocations: string[] = []; - const resolved = loadModuleFromImmediateNodeModules(Extensions.DtsOnly, moduleName, globalCache, failedLookupLocations, state, /*typesOnly*/ false); + const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; + const resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false); return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations); } diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index 696736048b1..5035fd52ec9 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -260,7 +260,8 @@ namespace ts.moduleSpecifiers { const suffix = pattern.substr(indexOfStar + 1); if (relativeToBaseUrl.length >= prefix.length + suffix.length && startsWith(relativeToBaseUrl, prefix) && - endsWith(relativeToBaseUrl, suffix)) { + endsWith(relativeToBaseUrl, suffix) || + !suffix && relativeToBaseUrl === removeTrailingDirectorySeparator(prefix)) { const matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); return key.replace("*", matchedStar); } @@ -318,6 +319,26 @@ namespace ts.moduleSpecifiers { return undefined; } + const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); + const packageJsonPath = combinePaths(packageRootPath, "package.json"); + const packageJsonContent = host.fileExists!(packageJsonPath) + ? JSON.parse(host.readFile!(packageJsonPath)!) + : undefined; + const versionPaths = packageJsonContent && packageJsonContent.typesVersions + ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) + : undefined; + if (versionPaths) { + const subModuleName = moduleFileName.slice(parts.packageRootIndex + 1); + const fromPaths = tryGetModuleNameFromPaths( + removeFileExtension(subModuleName), + removeExtensionAndIndexPostFix(subModuleName, ModuleResolutionKind.NodeJs, /*addJsExtension*/ false), + versionPaths.paths + ); + if (fromPaths !== undefined) { + moduleFileName = combinePaths(moduleFileName.slice(0, parts.packageRootIndex), fromPaths); + } + } + // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name @@ -330,17 +351,12 @@ namespace ts.moduleSpecifiers { function getDirectoryOrExtensionlessFileName(path: string): string { // If the file is the main module, it can be imported by the package name - const packageRootPath = path.substring(0, parts.packageRootIndex); - const packageJsonPath = combinePaths(packageRootPath, "package.json"); - if (host.fileExists!(packageJsonPath)) { // TODO: GH#18217 - const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!); - if (packageJsonContent) { - const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; - if (mainFileRelative) { - const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); - if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { - return packageRootPath; - } + if (packageJsonContent) { + const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main; + if (mainFileRelative) { + const mainExportFile = toPath(mainFileRelative, packageRootPath, getCanonicalFileName); + if (removeFileExtension(mainExportFile) === removeFileExtension(getCanonicalFileName(path))) { + return packageRootPath; } } } diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 063b5f1cd1d..e33d9eec292 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -289,6 +289,13 @@ namespace ts { if (startsWith(fileName, "./") && hasExtension(fileName)) { fileName = fileName.substring(2); } + + // omit references to files from node_modules (npm may disambiguate module + // references when installing this package, making the path is unreliable). + if (startsWith(fileName, "node_modules/") || fileName.indexOf("/node_modules/") !== -1) { + return; + } + references.push({ pos: -1, end: -1, fileName }); } }; diff --git a/src/services/pathCompletions.ts b/src/services/pathCompletions.ts index f958163bb14..22cc56903c0 100644 --- a/src/services/pathCompletions.ts +++ b/src/services/pathCompletions.ts @@ -107,24 +107,10 @@ namespace ts.Completions.PathCompletions { // const absolutePath = normalizeAndPreserveTrailingSlash(isRootedDiskPath(fragment) ? fragment : combinePaths(scriptPath, fragment)); // TODO(rbuckton): should use resolvePaths const absolutePath = resolvePath(scriptPath, fragment); - let baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); + const baseDirectory = hasTrailingDirectorySeparator(absolutePath) ? absolutePath : getDirectoryPath(absolutePath); const ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); if (tryDirectoryExists(host, baseDirectory)) { - // check for a version redirect - const packageJsonPath = findPackageJson(baseDirectory, host); - if (packageJsonPath) { - const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); - const typesVersions = (packageJson as any).typesVersions; - if (typeof typesVersions === "object") { - const result = getPackageJsonTypesVersionsOverride(typesVersions); - const versionPath = result && result.directory; - if (versionPath) { - baseDirectory = resolvePath(baseDirectory, versionPath); - } - } - } - // Enumerate the available files if possible const files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); @@ -165,11 +151,41 @@ namespace ts.Completions.PathCompletions { } } } + + // check for a version redirect + const packageJsonPath = findPackageJson(baseDirectory, host); + if (packageJsonPath) { + const packageJson = readJson(packageJsonPath, host as { readFile: (filename: string) => string | undefined }); + const typesVersions = (packageJson as any).typesVersions; + if (typeof typesVersions === "object") { + const versionResult = getPackageJsonTypesVersionsPaths(typesVersions); + const versionPaths = versionResult && versionResult.paths; + const rest = absolutePath.slice(ensureTrailingDirectorySeparator(baseDirectory).length); + if (versionPaths) { + addCompletionEntriesFromPaths(result, rest, baseDirectory, extensions, versionPaths, host); + } + } + } } return result; } + function addCompletionEntriesFromPaths(result: NameAndKind[], fragment: string, baseDirectory: string, fileExtensions: ReadonlyArray, paths: MapLike, host: LanguageServiceHost) { + for (const path in paths) { + if (!hasProperty(paths, path)) continue; + const patterns = paths[path]; + if (patterns) { + for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host)) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(entry => entry.name === name)) { + result.push(nameAndKind(name, kind)); + } + } + } + } + } + /** * Check all of the declared modules and those in node modules. Possible sources of modules: * Modules that are found by the type checker @@ -185,19 +201,10 @@ namespace ts.Completions.PathCompletions { const fileExtensions = getSupportedExtensionsForModuleResolution(compilerOptions); if (baseUrl) { const projectDir = compilerOptions.project || host.getCurrentDirectory(); - const absolute = isRootedDiskPath(baseUrl) ? baseUrl : combinePaths(projectDir, baseUrl); - getCompletionEntriesForDirectoryFragment(fragment, normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - - for (const path in paths!) { - const patterns = paths![path]; - if (paths!.hasOwnProperty(path) && patterns) { - for (const { name, kind } of getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host)) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (!result.some(entry => entry.name === name)) { - result.push(nameAndKind(name, kind)); - } - } - } + const absolute = normalizePath(combinePaths(projectDir, baseUrl)); + getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); + if (paths) { + addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); } } diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json index dbf67e3802c..c4421e45579 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage.trace.json @@ -33,10 +33,10 @@ "======== Resolving module 'foo' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' does not have a 'main' field.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/a/node_modules/foo/package.json'. Package ID is 'foo/index.d.ts@1.2.3'.", "File '/node_modules/a/node_modules/foo.ts' does not exist.", "File '/node_modules/a/node_modules/foo.tsx' does not exist.", diff --git a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json index d3d3dfac064..97340de57ca 100644 --- a/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json +++ b/tests/baselines/reference/duplicatePackage_relativeImportWithinPackage_scoped.trace.json @@ -33,10 +33,10 @@ "======== Resolving module '@foo/bar' from '/node_modules/a/index.d.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' does not have a 'main' field.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/a/node_modules/@foo/bar/package.json'. Package ID is '@foo/bar/index.d.ts@1.2.3'.", "File '/node_modules/a/node_modules/@foo/bar.ts' does not exist.", "File '/node_modules/a/node_modules/@foo/bar.tsx' does not exist.", diff --git a/tests/baselines/reference/library-reference-10.trace.json b/tests/baselines/reference/library-reference-10.trace.json index d24bc21f283..3e6cf4432ea 100644 --- a/tests/baselines/reference/library-reference-10.trace.json +++ b/tests/baselines/reference/library-reference-10.trace.json @@ -1,18 +1,20 @@ [ "======== Resolving type reference directive 'jquery', containing file '/foo/consumer.ts', root directory './types'. ========", "Resolving with primary search path './types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at './types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", "Resolving real path for 'types/jquery/jquery.d.ts', result '/foo/types/jquery/jquery.d.ts'.", "======== Type reference directive 'jquery' was successfully resolved to '/foo/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/foo/__inferred type names__.ts', root directory './types'. ========", "Resolving with primary search path './types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at './types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references 'types/jquery/jquery.d.ts'.", "File 'types/jquery/jquery.d.ts' exist - use it as a name resolution result.", "Resolving real path for 'types/jquery/jquery.d.ts', result '/foo/types/jquery/jquery.d.ts'.", diff --git a/tests/baselines/reference/library-reference-11.trace.json b/tests/baselines/reference/library-reference-11.trace.json index 5b2d6695356..b5e324d8c36 100644 --- a/tests/baselines/reference/library-reference-11.trace.json +++ b/tests/baselines/reference/library-reference-11.trace.json @@ -3,8 +3,8 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "File '/a/node_modules/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/a/node_modules/jquery/jquery.d.ts'.", diff --git a/tests/baselines/reference/library-reference-12.trace.json b/tests/baselines/reference/library-reference-12.trace.json index f6c1aef4811..1421f1501d9 100644 --- a/tests/baselines/reference/library-reference-12.trace.json +++ b/tests/baselines/reference/library-reference-12.trace.json @@ -3,9 +3,9 @@ "Root directory cannot be determined, skipping primary search paths.", "Looking up in 'node_modules' folder, initial location '/a/b'.", "Directory '/a/b/node_modules' does not exist, skipping all lookups in it.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'dist/jquery.d.ts' that references '/a/node_modules/jquery/dist/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/a/node_modules/jquery/package.json'.", "File '/a/node_modules/jquery.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", diff --git a/tests/baselines/reference/library-reference-2.trace.json b/tests/baselines/reference/library-reference-2.trace.json index baef46d8995..8a13d1e6f54 100644 --- a/tests/baselines/reference/library-reference-2.trace.json +++ b/tests/baselines/reference/library-reference-2.trace.json @@ -1,10 +1,11 @@ [ "======== Resolving type reference directive 'jquery', containing file '/consumer.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "File '/types/jquery/jquery.d.ts' exist - use it as a name resolution result.", @@ -12,10 +13,11 @@ "======== Type reference directive 'jquery' was successfully resolved to '/types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'jquery', containing file '/test/__inferred type names__.ts', root directory '/types'. ========", "Resolving with primary search path '/types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'jquery.d.ts' that references '/types/jquery/jquery.d.ts'.", "File '/types/jquery/jquery.d.ts' exist - use it as a name resolution result.", diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json index 2f743d9e200..d386774db15 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected.trace.json @@ -2,10 +2,10 @@ "======== Resolving module 'normalize.css' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/normalize.css/package.json'.", "File '/node_modules/normalize.css.ts' does not exist.", "File '/node_modules/normalize.css.tsx' does not exist.", @@ -25,10 +25,10 @@ "File '/node_modules/normalize.css/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'normalize.css' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'normalize.css' that references '/node_modules/normalize.css/normalize.css'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/normalize.css/package.json'.", "File '/node_modules/normalize.css.js' does not exist.", "File '/node_modules/normalize.css.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json index 06610253558..09a7bf81c98 100644 --- a/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json +++ b/tests/baselines/reference/moduleResolutionWithExtensions_unexpected2.trace.json @@ -2,9 +2,9 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -27,9 +27,9 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'foo.js' that references '/node_modules/foo/foo.js'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json index 2a4a1e71a4a..dbd645d9d65 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot.trace.json @@ -2,9 +2,9 @@ "======== Resolving module 'foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/bar/types.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/bar/package.json'.", "File '/node_modules/foo/bar.ts' does not exist.", "File '/node_modules/foo/bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json index b54519397ab..e47dcc86b12 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_notAtPackageRoot_fakeScopedPackage.trace.json @@ -2,9 +2,9 @@ "======== Resolving module 'foo/@bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo/@bar' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/foo/@bar/types.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/@bar/package.json'.", "File '/node_modules/foo/@bar.ts' does not exist.", "File '/node_modules/foo/@bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json index 389bd892d2f..a8e509ff6e8 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_scopedPackage.trace.json @@ -2,9 +2,9 @@ "======== Resolving module '@foo/bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module '@foo/bar' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'types.d.ts' that references '/node_modules/@foo/bar/types.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@foo/bar/package.json'.", "File '/node_modules/@foo/bar.ts' does not exist.", "File '/node_modules/@foo/bar.tsx' does not exist.", diff --git a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json index 84b7a4873c0..4d7ae487813 100644 --- a/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json +++ b/tests/baselines/reference/moduleResolution_packageJson_yesAtPackageRoot_mainFieldInSubDirectory.trace.json @@ -2,10 +2,10 @@ "======== Resolving module 'foo' from '/index.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'src/index.js' that references '/node_modules/foo/src/index.js'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'. Package ID is 'foo/src/index.d.ts@1.2.3'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", diff --git a/tests/baselines/reference/packageJsonMain.trace.json b/tests/baselines/reference/packageJsonMain.trace.json index 583fc96774e..1f722312e1d 100644 --- a/tests/baselines/reference/packageJsonMain.trace.json +++ b/tests/baselines/reference/packageJsonMain.trace.json @@ -2,10 +2,10 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -24,10 +24,10 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", @@ -40,10 +40,10 @@ "======== Resolving module 'bar' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'bar' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/bar/package.json'.", "File '/node_modules/bar.ts' does not exist.", "File '/node_modules/bar.tsx' does not exist.", @@ -67,10 +67,10 @@ "File '/node_modules/bar/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'bar' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'rab.js' that references '/node_modules/bar/rab.js'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/bar/package.json'.", "File '/node_modules/bar.js' does not exist.", "File '/node_modules/bar.jsx' does not exist.", @@ -81,10 +81,10 @@ "======== Resolving module 'baz' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'baz' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/baz/package.json'.", "File '/node_modules/baz.ts' does not exist.", "File '/node_modules/baz.tsx' does not exist.", @@ -105,10 +105,10 @@ "File '/node_modules/baz/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'baz' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'zab' that references '/node_modules/baz/zab'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/baz/package.json'.", "File '/node_modules/baz.js' does not exist.", "File '/node_modules/baz.jsx' does not exist.", diff --git a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json index b7d26d0f852..f2f16ec6aeb 100644 --- a/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json +++ b/tests/baselines/reference/packageJsonMain_isNonRecursive.trace.json @@ -2,10 +2,10 @@ "======== Resolving module 'foo' from '/a.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'foo' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.ts' does not exist.", "File '/node_modules/foo.tsx' does not exist.", @@ -26,10 +26,10 @@ "File '/node_modules/foo/index.d.ts' does not exist.", "Directory '/node_modules/@types' does not exist, skipping all lookups in it.", "Loading module 'foo' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' does not have a 'typings' field.", "'package.json' does not have a 'types' field.", "'package.json' has 'main' field 'oof' that references '/node_modules/foo/oof'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/foo/package.json'.", "File '/node_modules/foo.js' does not exist.", "File '/node_modules/foo.jsx' does not exist.", diff --git a/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.js b/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.js index 75086611695..4cd606eae0e 100644 --- a/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.js +++ b/tests/baselines/reference/reactTransitiveImportHasValidDeclaration.js @@ -43,7 +43,6 @@ exports["default"] = Form; //// [index.d.ts] -/// /// declare const Form: import("create-emotion-styled/types/react").StyledOtherComponent<{}, import("react").DetailedHTMLProps, HTMLDivElement>, any>; export default Form; diff --git a/tests/baselines/reference/typesVersions.ambientModules.js b/tests/baselines/reference/typesVersions.ambientModules.js index c7f198b8467..5dc00d8b376 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.js +++ b/tests/baselines/reference/typesVersions.ambientModules.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": "ts3.0" + "3.0": { "*" : ["ts3.0/*"] } } } diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json index 0bf8bc16c5d..f40d37bd7c3 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.trace.json +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -2,15 +2,18 @@ "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "'package.json' does not have a 'typings' field.", - "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", - "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.d.ts' does not exist.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", - "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", @@ -21,8 +24,11 @@ "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", - "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' does not exist.", @@ -33,8 +39,11 @@ "Directory 'node_modules' does not exist, skipping all lookups in it.", "Directory '/node_modules' does not exist, skipping all lookups in it.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", - "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", - "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.js' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.jsx' does not exist.", "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", diff --git a/tests/baselines/reference/typesVersions.multiFile.js b/tests/baselines/reference/typesVersions.multiFile.js index 98a1331500b..0d3b91f7b13 100644 --- a/tests/baselines/reference/typesVersions.multiFile.js +++ b/tests/baselines/reference/typesVersions.multiFile.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": "ts3.0" + "3.0": { "*" : ["ts3.0/*"] } } } diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json index 2508681421b..6884322c301 100644 --- a/tests/baselines/reference/typesVersions.multiFile.trace.json +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -2,15 +2,18 @@ "======== Resolving module 'ext' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", "'package.json' does not have a 'typings' field.", - "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", - "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/index.d.ts@1.0.0'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0.d.ts' does not exist.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", - "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index'.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", @@ -21,8 +24,11 @@ "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", - "'package.json' has 'typesVersions['3.0']' field 'ts3.0' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0'.", - "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/ts3.0/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' exist - use it as a name resolution result.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js new file mode 100644 index 00000000000..a226df8e873 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js @@ -0,0 +1,51 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": { "*" : ["ts3.0/*"] } + } +} + +//// [index.d.ts] +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} +//// [index.d.ts] +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: import("ext").A; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols new file mode 100644 index 00000000000..15d1718cce7 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +declare module "ext" { +>"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) + + export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 22)) + + export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 1, 25)) +>A : Symbol(A, Decl(index.d.ts, 0, 22)) +} +declare module "ext/other" { +>"ext/other" : Symbol("ext/other", Decl(index.d.ts, 3, 1)) + + export interface B {} +>B : Symbol(B, Decl(index.d.ts, 4, 28)) + + export function fb(): B; +>fb : Symbol(fb, Decl(index.d.ts, 5, 25)) +>B : Symbol(B, Decl(index.d.ts, 4, 28)) +} + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json new file mode 100644 index 00000000000..f973d37cd58 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json @@ -0,0 +1,55 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts' does not exist.", + "Directory 'tests/cases/conformance/declarationEmit/node_modules/@types' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.js' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.jsx' does not exist.", + "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", + "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", + "Directory 'node_modules' does not exist, skipping all lookups in it.", + "Directory '/node_modules' does not exist, skipping all lookups in it.", + "======== Module name 'ext/other' was not resolved. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types new file mode 100644 index 00000000000..9f47ca9750c --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("ext").A + +import { fb } from "ext/other"; +>fb : () => import("ext/other").B + +export const va = fa(); +>va : import("ext").A +>fa() : import("ext").A +>fa : () => import("ext").A + +export const vb = fb(); +>vb : import("ext/other").B +>fb() : import("ext/other").B +>fb : () => import("ext/other").B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +declare module "ext" { +>"ext" : typeof import("ext") + + export interface A {} + export function fa(): A; +>fa : () => A +} +declare module "ext/other" { +>"ext/other" : typeof import("ext/other") + + export interface B {} + export function fb(): B; +>fb : () => B +} + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js new file mode 100644 index 00000000000..4a1edf5c97e --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js @@ -0,0 +1,48 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": { "*" : ["ts3.0/*"] } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: import("ext").A; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols new file mode 100644 index 00000000000..e5db0491541 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols @@ -0,0 +1,47 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json new file mode 100644 index 00000000000..0296a58b896 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json @@ -0,0 +1,37 @@ +[ + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types new file mode 100644 index 00000000000..73721bafec1 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A + +import { fb } from "ext/other"; +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B + +export const va = fa(); +>va : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A +>fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A + +export const vb = fb(); +>vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B +>fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B + diff --git a/tests/baselines/reference/typingsLookup4.trace.json b/tests/baselines/reference/typingsLookup4.trace.json index 30d0122b8fd..86b386670d6 100644 --- a/tests/baselines/reference/typingsLookup4.trace.json +++ b/tests/baselines/reference/typingsLookup4.trace.json @@ -5,8 +5,8 @@ "File '/node_modules/jquery.ts' does not exist.", "File '/node_modules/jquery.tsx' does not exist.", "File '/node_modules/jquery.d.ts' does not exist.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", "File '/node_modules/@types/jquery.d.ts' does not exist.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", @@ -19,8 +19,8 @@ "File '/node_modules/kquery.ts' does not exist.", "File '/node_modules/kquery.tsx' does not exist.", "File '/node_modules/kquery.d.ts' does not exist.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", "File '/node_modules/@types/kquery.d.ts' does not exist.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", @@ -37,8 +37,8 @@ "File '/node_modules/lquery.ts' does not exist.", "File '/node_modules/lquery.tsx' does not exist.", "File '/node_modules/lquery.d.ts' does not exist.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", "File '/node_modules/@types/lquery.d.ts' does not exist.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", @@ -53,8 +53,8 @@ "File '/node_modules/mquery.ts' does not exist.", "File '/node_modules/mquery.tsx' does not exist.", "File '/node_modules/mquery.d.ts' does not exist.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", "File '/node_modules/@types/mquery.d.ts' does not exist.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", @@ -69,18 +69,20 @@ "======== Module name 'mquery' was successfully resolved to '/node_modules/@types/mquery/mquery/index.tsx'. ========", "======== Resolving type reference directive 'jquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/jquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'jquery.d.ts' that references '/node_modules/@types/jquery/jquery.d.ts'.", "File '/node_modules/@types/jquery/jquery.d.ts' exist - use it as a name resolution result.", "Resolving real path for '/node_modules/@types/jquery/jquery.d.ts', result '/node_modules/@types/jquery/jquery.d.ts'.", "======== Type reference directive 'jquery' was successfully resolved to '/node_modules/@types/jquery/jquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'kquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/kquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'kquery' that references '/node_modules/@types/kquery/kquery'.", "File '/node_modules/@types/kquery/kquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/kquery/kquery', target file type 'TypeScript'.", @@ -91,9 +93,10 @@ "======== Type reference directive 'kquery' was successfully resolved to '/node_modules/@types/kquery/kquery.d.ts', primary: true. ========", "======== Resolving type reference directive 'lquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/lquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'lquery' that references '/node_modules/@types/lquery/lquery'.", "File '/node_modules/@types/lquery/lquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/lquery/lquery', target file type 'TypeScript'.", @@ -102,9 +105,10 @@ "======== Type reference directive 'lquery' was successfully resolved to '/node_modules/@types/lquery/lquery.ts', primary: true. ========", "======== Resolving type reference directive 'mquery', containing file '/__inferred type names__.ts', root directory '/node_modules/@types'. ========", "Resolving with primary search path '/node_modules/@types'.", - "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", + "'package.json' does not have a 'typesVersions' field.", "Found 'package.json' at '/node_modules/@types/mquery/package.json'.", + "'package.json' does not have a 'typesVersions' field.", "'package.json' has 'typings' field 'mquery' that references '/node_modules/@types/mquery/mquery'.", "File '/node_modules/@types/mquery/mquery' does not exist.", "Loading module as file / folder, candidate module location '/node_modules/@types/mquery/mquery', target file type 'TypeScript'.", diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts new file mode 100644 index 00000000000..27bba8e830e --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts @@ -0,0 +1,43 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @noImplicitReferences: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": { "*" : ["ts3.0/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} +// @filename: node_modules/ext/ts3.0/index.d.ts +declare module "ext" { + export interface A {} + export function fa(): A; +} +declare module "ext/other" { + export interface B {} + export function fb(): B; +} + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts new file mode 100644 index 00000000000..dd71b9b13e2 --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts @@ -0,0 +1,39 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.0": { "*" : ["ts3.0/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: node_modules/ext/ts3.0/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/ts3.0/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts index 781740d96d2..ac314e0c313 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": "ts3.0" + "3.0": { "*" : ["ts3.0/*"] } } } diff --git a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts index 44cf98e45c6..c9001ca2219 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts @@ -7,7 +7,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": "ts3.0" + "3.0": { "*" : ["ts3.0/*"] } } } diff --git a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts index db88a272ad5..d1e67ae9a90 100644 --- a/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts +++ b/tests/cases/fourslash/completionForStringLiteralNonrelativeImport13.ts @@ -8,7 +8,7 @@ //// "version": "1.0.0", //// "types": "index", //// "typesVersions": { -//// "3.0": "ts3.0" +//// "3.0": { "*" : ["ts3.0/*"] } //// } //// } @@ -31,6 +31,6 @@ verify.completions({ marker: test.markerNames(), - exact: ["index", "zzz"], + exact: ["aaa", "index", "ts3.0", "zzz"], isNewIdentifierLocation: true, }); From 37ec065d93b7a193f68952bbd7f182565ffb9278 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 28 Aug 2018 11:44:40 -0700 Subject: [PATCH 027/146] Add path back-reference tests --- src/compiler/checker.ts | 2 +- .../reference/typesVersions.ambientModules.js | 10 +-- .../typesVersions.ambientModules.symbols | 10 +-- .../typesVersions.ambientModules.trace.json | 36 +++++----- .../typesVersions.ambientModules.types | 30 ++++----- .../reference/typesVersions.multiFile.js | 10 +-- .../reference/typesVersions.multiFile.symbols | 12 ++-- .../typesVersions.multiFile.trace.json | 32 ++++----- .../reference/typesVersions.multiFile.types | 32 ++++----- .../typesVersionsDeclarationEmit.ambient.js | 2 +- ...pesVersionsDeclarationEmit.ambient.symbols | 2 +- ...VersionsDeclarationEmit.ambient.trace.json | 36 +++++----- ...typesVersionsDeclarationEmit.ambient.types | 2 +- .../typesVersionsDeclarationEmit.multiFile.js | 2 +- ...sVersionsDeclarationEmit.multiFile.symbols | 4 +- ...rsionsDeclarationEmit.multiFile.trace.json | 32 ++++----- ...pesVersionsDeclarationEmit.multiFile.types | 20 +++--- ...it.multiFileBackReferenceToSelf.errors.txt | 38 +++++++++++ ...rationEmit.multiFileBackReferenceToSelf.js | 46 +++++++++++++ ...nEmit.multiFileBackReferenceToSelf.symbols | 37 +++++++++++ ...it.multiFileBackReferenceToSelf.trace.json | 65 +++++++++++++++++++ ...ionEmit.multiFileBackReferenceToSelf.types | 33 ++++++++++ ...onEmit.multiFileBackReferenceToUnmapped.js | 45 +++++++++++++ ...t.multiFileBackReferenceToUnmapped.symbols | 35 ++++++++++ ...ultiFileBackReferenceToUnmapped.trace.json | 44 +++++++++++++ ...mit.multiFileBackReferenceToUnmapped.types | 31 +++++++++ .../typesVersionsDeclarationEmit.ambient.ts | 4 +- .../typesVersionsDeclarationEmit.multiFile.ts | 6 +- ...rationEmit.multiFileBackReferenceToSelf.ts | 37 +++++++++++ ...onEmit.multiFileBackReferenceToUnmapped.ts | 36 ++++++++++ .../typesVersions.ambientModules.ts | 12 ++-- .../typesVersions.multiFile.ts | 14 ++-- 32 files changed, 602 insertions(+), 155 deletions(-) create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json create mode 100644 tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types create mode 100644 tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts create mode 100644 tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index d3974da9930..1e495bf538e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22233,7 +22233,7 @@ namespace ts { for (const decl of indexSymbol.declarations) { const declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type.kind) { + switch (declaration.parameters[0].type!.kind) { case SyntaxKind.StringKeyword: if (!seenStringIndexer) { seenStringIndexer = true; diff --git a/tests/baselines/reference/typesVersions.ambientModules.js b/tests/baselines/reference/typesVersions.ambientModules.js index 5dc00d8b376..1d7e3f04ec3 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.js +++ b/tests/baselines/reference/typesVersions.ambientModules.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -20,18 +20,18 @@ declare module "ext/other" { //// [index.d.ts] declare module "ext" { - export const a = "ts3.0 a"; + export const a = "ts3.1 a"; } declare module "ext/other" { - export const b = "ts3.0 b"; + export const b = "ts3.1 b"; } //// [main.ts] import { a } from "ext"; import { b } from "ext/other"; -const aa: "ts3.0 a" = a; -const bb: "ts3.0 b" = b; +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; //// [main.js] diff --git a/tests/baselines/reference/typesVersions.ambientModules.symbols b/tests/baselines/reference/typesVersions.ambientModules.symbols index d8a0ab0f2ca..91d1adacd9c 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.symbols +++ b/tests/baselines/reference/typesVersions.ambientModules.symbols @@ -5,25 +5,25 @@ import { a } from "ext"; import { b } from "ext/other"; >b : Symbol(b, Decl(main.ts, 1, 8)) -const aa: "ts3.0 a" = a; +const aa: "ts3.1 a" = a; >aa : Symbol(aa, Decl(main.ts, 3, 5)) >a : Symbol(a, Decl(main.ts, 0, 8)) -const bb: "ts3.0 b" = b; +const bb: "ts3.1 b" = b; >bb : Symbol(bb, Decl(main.ts, 4, 5)) >b : Symbol(b, Decl(main.ts, 1, 8)) -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === declare module "ext" { >"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) - export const a = "ts3.0 a"; + export const a = "ts3.1 a"; >a : Symbol(a, Decl(index.d.ts, 1, 16)) } declare module "ext/other" { >"ext/other" : Symbol("ext/other", Decl(index.d.ts, 2, 1)) - export const b = "ts3.0 b"; + export const b = "ts3.1 b"; >b : Symbol(b, Decl(index.d.ts, 4, 16)) } diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json index f40d37bd7c3..7a442ce5048 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.trace.json +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -11,27 +11,27 @@ "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", - "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'.", - "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'. ========", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'. ========", "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' does not exist.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts' does not exist.", "Directory 'tests/cases/conformance/moduleResolution/node_modules/@types' does not exist, skipping all lookups in it.", "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", @@ -41,11 +41,11 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.js' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.jsx' does not exist.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.js' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.jsx' does not exist.", "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", diff --git a/tests/baselines/reference/typesVersions.ambientModules.types b/tests/baselines/reference/typesVersions.ambientModules.types index 20cd4112ebe..0e81bad67a0 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.types +++ b/tests/baselines/reference/typesVersions.ambientModules.types @@ -1,31 +1,31 @@ === tests/cases/conformance/moduleResolution/main.ts === import { a } from "ext"; ->a : "ts3.0 a" +>a : "ts3.1 a" import { b } from "ext/other"; ->b : "ts3.0 b" +>b : "ts3.1 b" -const aa: "ts3.0 a" = a; ->aa : "ts3.0 a" ->a : "ts3.0 a" +const aa: "ts3.1 a" = a; +>aa : "ts3.1 a" +>a : "ts3.1 a" -const bb: "ts3.0 b" = b; ->bb : "ts3.0 b" ->b : "ts3.0 b" +const bb: "ts3.1 b" = b; +>bb : "ts3.1 b" +>b : "ts3.1 b" -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === declare module "ext" { >"ext" : typeof import("ext") - export const a = "ts3.0 a"; ->a : "ts3.0 a" ->"ts3.0 a" : "ts3.0 a" + export const a = "ts3.1 a"; +>a : "ts3.1 a" +>"ts3.1 a" : "ts3.1 a" } declare module "ext/other" { >"ext/other" : typeof import("ext/other") - export const b = "ts3.0 b"; ->b : "ts3.0 b" ->"ts3.0 b" : "ts3.0 b" + export const b = "ts3.1 b"; +>b : "ts3.1 b" +>"ts3.1 b" : "ts3.1 b" } diff --git a/tests/baselines/reference/typesVersions.multiFile.js b/tests/baselines/reference/typesVersions.multiFile.js index 0d3b91f7b13..14f7fd8aaf4 100644 --- a/tests/baselines/reference/typesVersions.multiFile.js +++ b/tests/baselines/reference/typesVersions.multiFile.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -17,17 +17,17 @@ export const a = "default a"; export const b = "default b"; //// [index.d.ts] -export const a = "ts3.0 a"; +export const a = "ts3.1 a"; //// [other.d.ts] -export const b = "ts3.0 b"; +export const b = "ts3.1 b"; //// [main.ts] import { a } from "ext"; import { b } from "ext/other"; -const aa: "ts3.0 a" = a; -const bb: "ts3.0 b" = b; +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; //// [main.js] diff --git a/tests/baselines/reference/typesVersions.multiFile.symbols b/tests/baselines/reference/typesVersions.multiFile.symbols index c79bb054609..11ea8b7857a 100644 --- a/tests/baselines/reference/typesVersions.multiFile.symbols +++ b/tests/baselines/reference/typesVersions.multiFile.symbols @@ -6,12 +6,12 @@ export const a = "default a"; export const b = "default b"; >b : Symbol(b, Decl(other.d.ts, 0, 12)) -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === -export const a = "ts3.0 a"; +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +export const a = "ts3.1 a"; >a : Symbol(a, Decl(index.d.ts, 0, 12)) -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts === -export const b = "ts3.0 b"; +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts === +export const b = "ts3.1 b"; >b : Symbol(b, Decl(other.d.ts, 0, 12)) === tests/cases/conformance/moduleResolution/main.ts === @@ -21,11 +21,11 @@ import { a } from "ext"; import { b } from "ext/other"; >b : Symbol(b, Decl(main.ts, 1, 8)) -const aa: "ts3.0 a" = a; +const aa: "ts3.1 a" = a; >aa : Symbol(aa, Decl(main.ts, 3, 5)) >a : Symbol(a, Decl(main.ts, 0, 8)) -const bb: "ts3.0 b" = b; +const bb: "ts3.1 b" = b; >bb : Symbol(bb, Decl(main.ts, 4, 5)) >b : Symbol(b, Decl(main.ts, 1, 8)) diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json index 6884322c301..e7245fa5765 100644 --- a/tests/baselines/reference/typesVersions.multiFile.trace.json +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -11,27 +11,27 @@ "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index' does not exist.", - "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'.", - "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts'. ========", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts'. ========", "======== Resolving module 'ext/other' from 'tests/cases/conformance/moduleResolution/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.ts' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.tsx' does not exist.", - "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts'.", - "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts'. ========" + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersions.multiFile.types b/tests/baselines/reference/typesVersions.multiFile.types index c0634803d29..734a90067cb 100644 --- a/tests/baselines/reference/typesVersions.multiFile.types +++ b/tests/baselines/reference/typesVersions.multiFile.types @@ -8,28 +8,28 @@ export const b = "default b"; >b : "default b" >"default b" : "default b" -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/index.d.ts === -export const a = "ts3.0 a"; ->a : "ts3.0 a" ->"ts3.0 a" : "ts3.0 a" +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index.d.ts === +export const a = "ts3.1 a"; +>a : "ts3.1 a" +>"ts3.1 a" : "ts3.1 a" -=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.0/other.d.ts === -export const b = "ts3.0 b"; ->b : "ts3.0 b" ->"ts3.0 b" : "ts3.0 b" +=== tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.d.ts === +export const b = "ts3.1 b"; +>b : "ts3.1 b" +>"ts3.1 b" : "ts3.1 b" === tests/cases/conformance/moduleResolution/main.ts === import { a } from "ext"; ->a : "ts3.0 a" +>a : "ts3.1 a" import { b } from "ext/other"; ->b : "ts3.0 b" +>b : "ts3.1 b" -const aa: "ts3.0 a" = a; ->aa : "ts3.0 a" ->a : "ts3.0 a" +const aa: "ts3.1 a" = a; +>aa : "ts3.1 a" +>a : "ts3.1 a" -const bb: "ts3.0 b" = b; ->bb : "ts3.0 b" ->b : "ts3.0 b" +const bb: "ts3.1 b" = b; +>bb : "ts3.1 b" +>b : "ts3.1 b" diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js index a226df8e873..b1af852940b 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols index 15d1718cce7..2e4794ba56a 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.symbols @@ -13,7 +13,7 @@ export const vb = fb(); >vb : Symbol(vb, Decl(main.ts, 4, 12)) >fb : Symbol(fb, Decl(main.ts, 1, 8)) -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === declare module "ext" { >"ext" : Symbol("ext", Decl(index.d.ts, 0, 0)) diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json index f973d37cd58..c3b0e232748 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json @@ -11,27 +11,27 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index' does not exist.", - "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.ts' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.tsx' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'.", - "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'. ========", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.ts' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.tsx' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts' does not exist.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' does not exist.", "Directory 'tests/cases/conformance/declarationEmit/node_modules/@types' does not exist, skipping all lookups in it.", "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", @@ -41,11 +41,11 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.js' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.jsx' does not exist.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.js' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.jsx' does not exist.", "Directory 'tests/cases/conformance/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/cases/node_modules' does not exist, skipping all lookups in it.", "Directory 'tests/node_modules' does not exist, skipping all lookups in it.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types index 9f47ca9750c..3599ee312a3 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.types @@ -15,7 +15,7 @@ export const vb = fb(); >fb() : import("ext/other").B >fb : () => import("ext/other").B -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === declare module "ext" { >"ext" : typeof import("ext") diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js index 4a1edf5c97e..22cdb0087ef 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols index e5db0491541..4449de33ded 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.symbols @@ -14,7 +14,7 @@ export function fb(): B; >fb : Symbol(fb, Decl(other.d.ts, 0, 21)) >B : Symbol(B, Decl(other.d.ts, 0, 0)) -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === export interface A {} >A : Symbol(A, Decl(index.d.ts, 0, 0)) @@ -22,7 +22,7 @@ export function fa(): A; >fa : Symbol(fa, Decl(index.d.ts, 0, 21)) >A : Symbol(A, Decl(index.d.ts, 0, 0)) -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === export interface B {} >B : Symbol(B, Decl(other.d.ts, 0, 0)) diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json index 0296a58b896..532e80feac7 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json @@ -11,27 +11,27 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/index'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index' does not exist.", - "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index', target file type 'TypeScript'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.ts' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.tsx' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'.", - "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts'. ========", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.0' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", - "Trying substitution 'ts3.0/*', candidate module location: 'ts3.0/other'.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.ts' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.tsx' does not exist.", - "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts' exist - use it as a name resolution result.", - "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts'.", - "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts'. ========" + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========" ] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types index 73721bafec1..9f9dd015942 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.types @@ -8,30 +8,30 @@ export interface B {} export function fb(): B; >fb : () => B -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === export interface A {} export function fa(): A; >fa : () => A -=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other.d.ts === +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === export interface B {} export function fb(): B; >fb : () => B === tests/cases/conformance/declarationEmit/main.ts === import { fa } from "ext"; ->fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A import { fb } from "ext/other"; ->fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B export const va = fa(); ->va : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A ->fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A ->fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/index").A +>va : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A +>fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index").A export const vb = fb(); ->vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B ->fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B ->fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.0/other").B +>vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B +>fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other").B diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt new file mode 100644 index 00000000000..66624634d9f --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt @@ -0,0 +1,38 @@ +tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index"' has no exported member 'fa'. + + +==== tests/cases/conformance/declarationEmit/tsconfig.json (0 errors) ==== + {} +==== tests/cases/conformance/declarationEmit/node_modules/ext/package.json (0 errors) ==== + { + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.1": { "*" : ["ts3.1/*"] } + } + } + +==== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts (0 errors) ==== + export interface A {} + export function fa(): A; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts (0 errors) ==== + export interface B {} + export function fb(): B; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts (0 errors) ==== + export * from "../"; + +==== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts (0 errors) ==== + export * from "../other"; + +==== tests/cases/conformance/declarationEmit/main.ts (1 errors) ==== + import { fa } from "ext"; + ~~ +!!! error TS2305: Module '"tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index"' has no exported member 'fa'. + import { fb } from "ext/other"; + + export const va = fa(); + export const vb = fb(); + \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js new file mode 100644 index 00000000000..c7b885d5e9e --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js @@ -0,0 +1,46 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.1": { "*" : ["ts3.1/*"] } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface B {} +export function fb(): B; + +//// [index.d.ts] +export * from "../"; + +//// [other.d.ts] +export * from "../other"; + +//// [main.ts] +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.vb = other_1.fb(); + + +//// [main.d.ts] +export declare const va: any; +export declare const vb: import("ext/other").B; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols new file mode 100644 index 00000000000..a3367579265 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.symbols @@ -0,0 +1,37 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +export function fb(): B; +>fb : Symbol(fb, Decl(other.d.ts, 0, 21)) +>B : Symbol(B, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fb } from "ext/other"; +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const vb = fb(); +>vb : Symbol(vb, Decl(main.ts, 4, 12)) +>fb : Symbol(fb, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json new file mode 100644 index 00000000000..33d5a0e3177 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json @@ -0,0 +1,65 @@ +[ + "======== Resolving module '../' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/', target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/ndex/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "======== Module name '../' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module '../other' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/other', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other.d.ts@1.0.0'.", + "======== Module name '../other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========", + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "Module name 'other', matched pattern '*'.", + "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types new file mode 100644 index 00000000000..05800e1d35d --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface B {} +export function fb(): B; +>fb : () => B + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : any + +import { fb } from "ext/other"; +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B + +export const va = fa(); +>va : any +>fa() : any +>fa : any + +export const vb = fb(); +>vb : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B +>fb() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B +>fb : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").B + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js new file mode 100644 index 00000000000..86a621161f6 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js @@ -0,0 +1,45 @@ +//// [tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts] //// + +//// [package.json] +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.1": { + "index" : ["ts3.1/index"] + } + } +} + +//// [index.d.ts] +export interface A {} +export function fa(): A; + +//// [other.d.ts] +export interface A2 {} +export function fa(): A2; + +//// [index.d.ts] +export * from "../other"; + +//// [main.ts] +import { fa } from "ext"; +import { fa as fa2 } from "ext/other"; + +export const va = fa(); +export const va2 = fa2(); + + +//// [main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const ext_1 = require("ext"); +const other_1 = require("ext/other"); +exports.va = ext_1.fa(); +exports.va2 = other_1.fa(); + + +//// [main.d.ts] +export declare const va: import("ext/other").A2; +export declare const va2: import("ext/other").A2; diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols new file mode 100644 index 00000000000..892e521994b --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.symbols @@ -0,0 +1,35 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +export function fa(): A; +>fa : Symbol(fa, Decl(index.d.ts, 0, 21)) +>A : Symbol(A, Decl(index.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface A2 {} +>A2 : Symbol(A2, Decl(other.d.ts, 0, 0)) + +export function fa(): A2; +>fa : Symbol(fa, Decl(other.d.ts, 0, 22)) +>A2 : Symbol(A2, Decl(other.d.ts, 0, 0)) + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +import { fa as fa2 } from "ext/other"; +>fa : Symbol(fa2, Decl(main.ts, 1, 8)) +>fa2 : Symbol(fa2, Decl(main.ts, 1, 8)) + +export const va = fa(); +>va : Symbol(va, Decl(main.ts, 3, 12)) +>fa : Symbol(fa, Decl(main.ts, 0, 8)) + +export const va2 = fa2(); +>va2 : Symbol(va2, Decl(main.ts, 4, 12)) +>fa2 : Symbol(fa2, Decl(main.ts, 1, 8)) + diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json new file mode 100644 index 00000000000..d31c0730fd9 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json @@ -0,0 +1,44 @@ +[ + "======== Resolving module '../other' from 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/other', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other.d.ts@1.0.0'.", + "======== Module name '../other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========", + "======== Resolving module 'ext' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/index.d.ts@1.0.0'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", + "'package.json' does not have a 'typings' field.", + "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "Module name 'index', matched pattern 'index'.", + "Trying substitution 'ts3.1/index', candidate module location: 'ts3.1/index'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", + "Loading module as file / folder, candidate module location 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index', target file type 'TypeScript'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'.", + "======== Module name 'ext' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts'. ========", + "======== Resolving module 'ext/other' from 'tests/cases/conformance/declarationEmit/main.ts'. ========", + "Module resolution kind is not specified, using 'NodeJs'.", + "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", + "'package.json' has a 'typesVersions' field with version-specific path mappings.", + "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", + "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", + "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", + "Resolving real path for 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts', result 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'.", + "======== Module name 'ext/other' was successfully resolved to 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts'. ========" +] \ No newline at end of file diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types new file mode 100644 index 00000000000..d2918314133 --- /dev/null +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/declarationEmit/node_modules/ext/index.d.ts === +export interface A {} +export function fa(): A; +>fa : () => A + +=== tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts === +export interface A2 {} +export function fa(): A2; +>fa : () => A2 + +=== tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index.d.ts === +export * from "../other"; +No type information for this code. +No type information for this code.=== tests/cases/conformance/declarationEmit/main.ts === +import { fa } from "ext"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +import { fa as fa2 } from "ext/other"; +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2 : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +export const va = fa(); +>va : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + +export const va2 = fa2(); +>va2 : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2() : import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 +>fa2 : () => import("tests/cases/conformance/declarationEmit/node_modules/ext/other").A2 + diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts index 27bba8e830e..447f3aaa82a 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts @@ -9,7 +9,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -22,7 +22,7 @@ declare module "ext/other" { export interface B {} export function fb(): B; } -// @filename: node_modules/ext/ts3.0/index.d.ts +// @filename: node_modules/ext/ts3.1/index.d.ts declare module "ext" { export interface A {} export function fa(): A; diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts index dd71b9b13e2..57ae6c1d631 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -20,11 +20,11 @@ export function fa(): A; export interface B {} export function fb(): B; -// @filename: node_modules/ext/ts3.0/index.d.ts +// @filename: node_modules/ext/ts3.1/index.d.ts export interface A {} export function fa(): A; -// @filename: node_modules/ext/ts3.0/other.d.ts +// @filename: node_modules/ext/ts3.1/other.d.ts export interface B {} export function fb(): B; diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts new file mode 100644 index 00000000000..3391361225d --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts @@ -0,0 +1,37 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.1": { "*" : ["ts3.1/*"] } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface B {} +export function fb(): B; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export * from "../"; + +// @filename: node_modules/ext/ts3.1/other.d.ts +export * from "../other"; + +// @filename: main.ts +import { fa } from "ext"; +import { fb } from "ext/other"; + +export const va = fa(); +export const vb = fb(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts new file mode 100644 index 00000000000..15072d2a7ed --- /dev/null +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts @@ -0,0 +1,36 @@ +// @traceResolution: true +// @target: esnext +// @module: commonjs +// @declaration: true +// @filename: node_modules/ext/package.json +{ + "name": "ext", + "version": "1.0.0", + "types": "index", + "typesVersions": { + "3.1": { + "index" : ["ts3.1/index"] + } + } +} + +// @filename: node_modules/ext/index.d.ts +export interface A {} +export function fa(): A; + +// @filename: node_modules/ext/other.d.ts +export interface A2 {} +export function fa(): A2; + +// @filename: node_modules/ext/ts3.1/index.d.ts +export * from "../other"; + +// @filename: main.ts +import { fa } from "ext"; +import { fa as fa2 } from "ext/other"; + +export const va = fa(); +export const va2 = fa2(); + +// @filename: tsconfig.json +{} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts index ac314e0c313..2de5f470473 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -20,20 +20,20 @@ declare module "ext/other" { export const b = "default b"; } -// @filename: node_modules/ext/ts3.0/index.d.ts +// @filename: node_modules/ext/ts3.1/index.d.ts declare module "ext" { - export const a = "ts3.0 a"; + export const a = "ts3.1 a"; } declare module "ext/other" { - export const b = "ts3.0 b"; + export const b = "ts3.1 b"; } // @filename: main.ts import { a } from "ext"; import { b } from "ext/other"; -const aa: "ts3.0 a" = a; -const bb: "ts3.0 b" = b; +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; // @filename: tsconfig.json {} \ No newline at end of file diff --git a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts index c9001ca2219..8d57630af21 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts @@ -7,7 +7,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.0": { "*" : ["ts3.0/*"] } + "3.1": { "*" : ["ts3.1/*"] } } } @@ -17,18 +17,18 @@ export const a = "default a"; // @filename: node_modules/ext/other.d.ts export const b = "default b"; -// @filename: node_modules/ext/ts3.0/index.d.ts -export const a = "ts3.0 a"; +// @filename: node_modules/ext/ts3.1/index.d.ts +export const a = "ts3.1 a"; -// @filename: node_modules/ext/ts3.0/other.d.ts -export const b = "ts3.0 b"; +// @filename: node_modules/ext/ts3.1/other.d.ts +export const b = "ts3.1 b"; // @filename: main.ts import { a } from "ext"; import { b } from "ext/other"; -const aa: "ts3.0 a" = a; -const bb: "ts3.0 b" = b; +const aa: "ts3.1 a" = a; +const bb: "ts3.1 b" = b; // @filename: tsconfig.json {} \ No newline at end of file From 04a524511ebe5abc61445bf2dd6eb685099cb968 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 28 Aug 2018 14:11:01 -0700 Subject: [PATCH 028/146] Add semver range parsing support --- Gulpfile.js | 4 +- scripts/build/countdown.js | 62 ++++++++ scripts/build/exec.js | 2 + scripts/build/project.js | 48 ++++-- src/compiler/checker.ts | 2 +- src/compiler/core.ts | 1 + src/compiler/semver.ts | 236 +++++++++++++++++++++++++++++ src/compiler/utilities.ts | 1 - src/harness/utils.ts | 12 ++ src/testRunner/unittests/semver.ts | 134 ++++++++++++++++ 10 files changed, 483 insertions(+), 19 deletions(-) create mode 100644 scripts/build/countdown.js diff --git a/Gulpfile.js b/Gulpfile.js index b31462755ad..b2fb584d4a2 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -570,12 +570,12 @@ gulp.task( }); }, /*timeout*/ 100, { max: 500 }); - gulp.watch(watchPatterns, () => project.wait().then(fn)); + gulp.watch(watchPatterns, () => project.wait(runTestsSource && runTestsSource.token).then(fn)); // NOTE: gulp.watch is far too slow when watching tests/cases/**/* as it first enumerates *every* file const testFilePattern = /(\.ts|[\\/]tsconfig\.json)$/; fs.watch("tests/cases", { recursive: true }, (_, file) => { - if (testFilePattern.test(file)) project.wait().then(fn); + if (testFilePattern.test(file)) project.wait(runTestsSource && runTestsSource.token).then(fn); }); function runTests() { diff --git a/scripts/build/countdown.js b/scripts/build/countdown.js new file mode 100644 index 00000000000..dda05352d28 --- /dev/null +++ b/scripts/build/countdown.js @@ -0,0 +1,62 @@ +// @ts-check +const { CancelToken } = require("./cancellation"); + +class Countdown { + constructor(initialCount = 0) { + if (initialCount < 0) throw new Error(); + this._remainingCount = initialCount; + this._promise = undefined; + this._resolve = undefined; + } + + get remainingCount() { + return this._remainingCount; + } + + add(count = 1) { + if (count < 1 || !isFinite(count) || Math.trunc(count) !== count) throw new Error(); + if (this._remainingCount === 0) { + this._promise = undefined; + this._resolve = undefined; + } + + this._remainingCount += count; + } + + signal(count = 1) { + if (count < 1 || !isFinite(count) || Math.trunc(count) !== count) throw new Error(); + if (this._remainingCount - count < 0) throw new Error(); + this._remainingCount -= count; + if (this._remainingCount == 0) { + if (this._resolve) { + this._resolve(); + } + return true; + } + return false; + } + + /** @param {CancelToken} [token] */ + wait(token) { + if (!this._promise) { + this._promise = new Promise(resolve => { this._resolve = resolve; }); + } + if (this._remainingCount === 0) { + this._resolve(); + } + if (!token) return this._promise; + return new Promise((resolve, reject) => { + const subscription = token.subscribe(reject); + this._promise.then( + value => { + subscription.unsubscribe(); + resolve(value); + }, + error => { + subscription.unsubscribe(); + reject(error); + }); + }); + } +} +exports.Countdown = Countdown; \ No newline at end of file diff --git a/scripts/build/exec.js b/scripts/build/exec.js index 04336321dd4..068bf33b9e9 100644 --- a/scripts/build/exec.js +++ b/scripts/build/exec.js @@ -25,8 +25,10 @@ function exec(cmd, args, options = {}) { const command = isWin ? [possiblyQuote(cmd), ...args] : [`${cmd} ${args.join(" ")}`]; const ex = cp.spawn(isWin ? "cmd" : "/bin/sh", [subshellFlag, ...command], { stdio: "inherit", windowsVerbatimArguments: true }); const subscription = options.cancelToken && options.cancelToken.subscribe(() => { + log(`${chalk.red("killing")} '${chalk.green(cmd)} ${args.join(" ")}'...`); ex.kill("SIGINT"); ex.kill("SIGTERM"); + ex.kill(); reject(new CancelError()); }); ex.on("exit", exitCode => { diff --git a/scripts/build/project.js b/scripts/build/project.js index 933f7c44c65..8519e4c71ec 100644 --- a/scripts/build/project.js +++ b/scripts/build/project.js @@ -13,8 +13,27 @@ const del = require("del"); const needsUpdate = require("./needsUpdate"); const mkdirp = require("./mkdirp"); const { reportDiagnostics } = require("./diagnostics"); +const { Countdown } = require("./countdown"); +const { CancelToken } = require("./cancellation"); + +const countdown = new Countdown(); class CompilationGulp extends gulp.Gulp { + constructor() { + super(); + this.on("start", () => { + const onDone = () => { + this.removeListener("stop", onDone); + this.removeListener("err", onDone); + countdown.signal(); + }; + + this.on("stop", onDone); + this.on("err", onDone); + countdown.add(); + }); + } + /** * @param {boolean} [verbose] */ @@ -38,6 +57,17 @@ class ForkedGulp extends gulp.Gulp { constructor(tasks) { super(); this.tasks = tasks; + this.on("start", () => { + const onDone = () => { + this.removeListener("stop", onDone); + this.removeListener("err", onDone); + countdown.signal(); + }; + + this.on("stop", onDone); + this.on("err", onDone); + countdown.add(); + }); } // Do not reset tasks @@ -211,22 +241,10 @@ exports.flatten = flatten; /** * Returns a Promise that resolves when all pending build tasks have completed + * @param {CancelToken} [token] */ -function wait() { - return new Promise(resolve => { - if (compilationGulp.allDone()) { - resolve(); - } - else { - const onDone = () => { - compilationGulp.removeListener("onDone", onDone); - compilationGulp.removeListener("err", onDone); - resolve(); - }; - compilationGulp.on("stop", onDone); - compilationGulp.on("err", onDone); - } - }); +function wait(token) { + return countdown.wait(token); } exports.wait = wait; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 1e495bf538e..d3974da9930 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -22233,7 +22233,7 @@ namespace ts { for (const decl of indexSymbol.declarations) { const declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { - switch (declaration.parameters[0].type!.kind) { + switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: if (!seenStringIndexer) { seenStringIndexer = true; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 1eaab5b1b59..5e4d42a890e 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -65,6 +65,7 @@ namespace ts { /* @internal */ namespace ts { + export const emptyArray: never[] = [] as never[]; /** Create a MapLike with good performance. */ function createDictionaryObject(): MapLike { diff --git a/src/compiler/semver.ts b/src/compiler/semver.ts index 203739f7c95..33623f45542 100644 --- a/src/compiler/semver.ts +++ b/src/compiler/semver.ts @@ -30,6 +30,8 @@ namespace ts { * Describes a precise semantic version number, https://semver.org */ export class Version { + static readonly zero = new Version(0, 0, 0); + readonly major: number; readonly minor: number; readonly patch: number; @@ -85,6 +87,15 @@ namespace ts { || comparePrerelaseIdentifiers(this.prerelease, other.prerelease); } + increment(field: "major" | "minor" | "patch") { + switch (field) { + case "major": return new Version(this.major + 1, 0, 0); + case "minor": return new Version(this.major, this.minor + 1, 0); + case "patch": return new Version(this.major, this.minor, this.patch + 1); + default: return Debug.assertNever(field); + } + } + toString() { let result = `${this.major}.${this.minor}.${this.patch}`; if (some(this.prerelease)) result += `-${this.prerelease.join(".")}`; @@ -152,4 +163,229 @@ namespace ts { // > of the preceding identifiers are equal. return compareValues(left.length, right.length); } + + /** + * Describes a semantic version range, per https://github.com/npm/node-semver#ranges + */ + export class VersionRange { + private _alternatives: ReadonlyArray>; + + constructor(spec: string) { + this._alternatives = spec ? Debug.assertDefined(parseRange(spec), "Invalid range spec.") : emptyArray; + } + + static tryParse(text: string) { + const sets = parseRange(text); + if (sets) { + const range = new VersionRange(""); + range._alternatives = sets; + return range; + } + return undefined; + } + + test(version: Version | string) { + if (typeof version === "string") version = new Version(version); + return testDisjunction(version, this._alternatives); + } + + toString() { + return formatDisjunction(this._alternatives); + } + } + + interface Comparator { + readonly operator: "<" | "<=" | ">" | ">=" | "="; + readonly operand: Version; + } + + // https://github.com/npm/node-semver#range-grammar + // + // range-set ::= range ( logical-or range ) * + // range ::= hyphen | simple ( ' ' simple ) * | '' + // logical-or ::= ( ' ' ) * '||' ( ' ' ) * + const logicalOrRegExp = /\s*\|\|\s*/g; + const whitespaceRegExp = /\s+/g; + + // https://github.com/npm/node-semver#range-grammar + // + // partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? + // xr ::= 'x' | 'X' | '*' | nr + // nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * + // qualifier ::= ( '-' pre )? ( '+' build )? + // pre ::= parts + // build ::= parts + // parts ::= part ( '.' part ) * + // part ::= nr | [-0-9A-Za-z]+ + const partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // hyphen ::= partial ' - ' partial + const hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i; + + // https://github.com/npm/node-semver#range-grammar + // + // simple ::= primitive | partial | tilde | caret + // primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial + // tilde ::= '~' partial + // caret ::= '^' partial + const rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i; + + function parseRange(text: string) { + const alternatives: Comparator[][] = []; + for (const range of text.trim().split(logicalOrRegExp)) { + if (!range) continue; + const comparators: Comparator[] = []; + const match = hyphenRegExp.exec(range); + if (match) { + if (!parseHyphen(match[1], match[2], comparators)) return undefined; + } + else { + for (const simple of range.split(whitespaceRegExp)) { + const match = rangeRegExp.exec(simple); + if (!match || !parseComparator(match[1], match[2], comparators)) return undefined; + } + } + alternatives.push(comparators); + } + return alternatives; + } + + function parsePartial(text: string) { + const match = partialRegExp.exec(text); + if (!match) return undefined; + + const [, major, minor = "*", patch = "*", prerelease, build] = match; + const version = new Version( + isWildcard(major) ? 0 : parseInt(major, 10), + isWildcard(major) || isWildcard(minor) ? 0 : parseInt(minor, 10), + isWildcard(major) || isWildcard(minor) || isWildcard(patch) ? 0 : parseInt(patch, 10), + prerelease, + build); + + return { version, major, minor, patch }; + } + + function parseHyphen(left: string, right: string, comparators: Comparator[]) { + const leftResult = parsePartial(left); + if (!leftResult) return false; + + const rightResult = parsePartial(right); + if (!rightResult) return false; + + if (!isWildcard(leftResult.major)) { + comparators.push(createComparator(">=", leftResult.version)); + } + + if (!isWildcard(rightResult.major)) { + comparators.push( + isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) : + isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) : + createComparator("<=", rightResult.version)); + } + + return true; + } + + function parseComparator(operator: string, text: string, comparators: Comparator[]) { + const result = parsePartial(text); + if (!result) return false; + + const { version, major, minor, patch } = result; + if (!isWildcard(major)) { + switch (operator) { + case "~": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + isWildcard(minor) ? "major" : + "minor"))); + break; + case "^": + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment( + version.major > 0 || isWildcard(minor) ? "major" : + version.minor > 0 || isWildcard(patch) ? "minor" : + "patch"))); + break; + case "<": + case ">=": + comparators.push(createComparator(operator, version)); + break; + case "<=": + case ">": + comparators.push( + isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) : + isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) : + createComparator(operator, version)); + break; + case "=": + case undefined: + if (isWildcard(minor) || isWildcard(patch)) { + comparators.push(createComparator(">=", version)); + comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor"))); + } + else { + comparators.push(createComparator("=", version)); + } + break; + default: + // unrecognized + return false; + } + } + else if (operator === "<" || operator === ">") { + comparators.push(createComparator("<", Version.zero)); + } + + return true; + } + + function isWildcard(part: string) { + return part === "*" || part === "x" || part === "X"; + } + + function createComparator(operator: Comparator["operator"], operand: Version) { + return { operator, operand }; + } + + function testDisjunction(version: Version, alternatives: ReadonlyArray>) { + // an empty disjunction is treated as "*" (all versions) + if (alternatives.length === 0) return true; + for (const alternative of alternatives) { + if (testAlternative(version, alternative)) return true; + } + return false; + } + + function testAlternative(version: Version, comparators: ReadonlyArray) { + for (const comparator of comparators) { + if (!testComparator(version, comparator.operator, comparator.operand)) return false; + } + return true; + } + + function testComparator(version: Version, operator: Comparator["operator"], operand: Version) { + const cmp = version.compareTo(operand); + switch (operator) { + case "<": return cmp < 0; + case "<=": return cmp <= 0; + case ">": return cmp > 0; + case ">=": return cmp >= 0; + case "=": return cmp === 0; + default: return Debug.assertNever(operator); + } + } + + function formatDisjunction(alternatives: ReadonlyArray>) { + return map(alternatives, formatAlternative).join(" || ") || "*"; + } + + function formatAlternative(comparators: ReadonlyArray) { + return map(comparators, formatComparator).join(" "); + } + + function formatComparator(comparator: Comparator) { + return `${comparator.operator}${comparator.operand}`; + } } \ No newline at end of file diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index e7eb352da84..0192aa38270 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -14,7 +14,6 @@ namespace ts { /* @internal */ namespace ts { - export const emptyArray: never[] = [] as never[]; export const resolvingEmptyArray: never[] = [] as never[]; export const emptyMap: ReadonlyMap = createMap(); export const emptyUnderscoreEscapedMap: ReadonlyUnderscoreEscapedMap = emptyMap as ReadonlyUnderscoreEscapedMap; diff --git a/src/harness/utils.ts b/src/harness/utils.ts index 4650badadaf..14820f10529 100644 --- a/src/harness/utils.ts +++ b/src/harness/utils.ts @@ -82,4 +82,16 @@ namespace utils { export function addUTF8ByteOrderMark(text: string) { return getByteOrderMarkLength(text) === 0 ? "\u00EF\u00BB\u00BF" + text : text; } + + export function theory(name: string, cb: (...args: T) => void, data: T[]) { + for (const entry of data) { + it(`${name}(${entry.map(formatTheoryDatum).join(", ")})`, () => cb(...entry)); + } + } + + function formatTheoryDatum(value: any) { + return typeof value === "function" ? value.name || "" : + value === undefined ? "undefined" : + JSON.stringify(value); + } } \ No newline at end of file diff --git a/src/testRunner/unittests/semver.ts b/src/testRunner/unittests/semver.ts index edc888e1075..357a24307ca 100644 --- a/src/testRunner/unittests/semver.ts +++ b/src/testRunner/unittests/semver.ts @@ -1,4 +1,5 @@ namespace ts { + import theory = utils.theory; describe("semver", () => { describe("Version", () => { function assertVersion(version: Version, [major, minor, patch, prerelease, build]: [number, number, number, string[]?, string[]?]) { @@ -89,6 +90,139 @@ namespace ts { // > Build metadata does not figure into precedence assert.strictEqual(new Version("1.0.0+build").compareTo(new Version("1.0.0")), Comparison.EqualTo); }); + it("increment", () => { + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("major"), [2, 0, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("minor"), [1, 3, 0]); + assertVersion(new Version(1, 2, 3, "pre.4", "build.5").increment("patch"), [1, 2, 4]); + }); + }); + describe("VersionRange", () => { + function assertRange(rangeText: string, versionText: string, inRange = true) { + const range = new VersionRange(rangeText); + const version = new Version(versionText); + assert.strictEqual(range.test(version), inRange, `Expected version '${version}' ${inRange ? `to be` : `to not be`} in range '${rangeText}' (${range})`); + } + theory("comparators", assertRange, [ + ["", "1.0.0"], + ["*", "1.0.0"], + ["1", "1.0.0"], + ["1", "2.0.0", false], + ["1.0", "1.0.0"], + ["1.0", "1.1.0", false], + ["1.0.0", "1.0.0"], + ["1.0.0", "1.0.1", false], + ["1.*", "1.0.0"], + ["1.*", "2.0.0", false], + ["1.x", "1.0.0"], + ["1.x", "2.0.0", false], + ["=1", "1.0.0"], + ["=1", "1.1.0"], + ["=1", "1.0.1"], + ["=1.0", "1.0.0"], + ["=1.0", "1.0.1"], + ["=1.0.0", "1.0.0"], + ["=*", "0.0.0"], + ["=*", "1.0.0"], + [">1", "2"], + [">1.0", "1.1"], + [">1.0.0", "1.0.1"], + [">1.0.0", "1.0.1-pre"], + [">*", "0.0.0", false], + [">*", "1.0.0", false], + [">=1", "1.0.0"], + [">=1.0", "1.0.0"], + [">=1.0.0", "1.0.0"], + [">=1.0.0", "1.0.1-pre"], + [">=*", "0.0.0"], + [">=*", "1.0.0"], + ["<2", "1.0.0"], + ["<2.1", "2.0.0"], + ["<2.0.1", "2.0.0"], + ["<2.0.0", "2.0.0-pre"], + ["<*", "0.0.0", false], + ["<*", "1.0.0", false], + ["<=2", "2.0.0"], + ["<=2.1", "2.1.0"], + ["<=2.0.1", "2.0.1"], + ["<=*", "0.0.0"], + ["<=*", "1.0.0"], + ]); + theory("conjunctions", assertRange, [ + [">1.0.0 <2.0.0", "1.0.1"], + [">1.0.0 <2.0.0", "2.0.0", false], + [">1.0.0 <2.0.0", "1.0.0", false], + [">1 >2", "3.0.0"], + ]); + theory("disjunctions", assertRange, [ + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "1.0.0"], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "2.0.0", false], + [">=1.0.0 <2.0.0 || >=3.0.0 <4.0.0", "3.0.0"], + ]); + theory("hyphen", assertRange, [ + ["1.0.0 - 2.0.0", "1.0.0"], + ["1.0.0 - 2.0.0", "2.0.0"], + ["1.0.0 - 2.0.0", "3.0.0", false], + ]); + theory("tilde", assertRange, [ + ["~0", "0.0.0"], + ["~0", "0.1.0"], + ["~0", "0.1.2"], + ["~0", "0.1.9"], + ["~0", "1.0.0", false], + ["~0.1", "0.1.0"], + ["~0.1", "0.1.2"], + ["~0.1", "0.1.9"], + ["~0.1", "0.2.0", false], + ["~0.1.2", "0.1.2"], + ["~0.1.2", "0.1.9"], + ["~0.1.2", "0.2.0", false], + ["~1", "1.0.0"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "1.2.0"], + ["~1", "1.2.3"], + ["~1", "0.0.0", false], + ["~1", "2.0.0", false], + ["~1.2", "1.2.0"], + ["~1.2", "1.2.3"], + ["~1.2", "1.1.0", false], + ["~1.2", "1.3.0", false], + ["~1.2.3", "1.2.3"], + ["~1.2.3", "1.2.9"], + ["~1.2.3", "1.1.0", false], + ["~1.2.3", "1.3.0", false], + ]); + theory("caret", assertRange, [ + ["^0", "0.0.0"], + ["^0", "0.1.0"], + ["^0", "0.9.0"], + ["^0", "0.1.2"], + ["^0", "0.1.9"], + ["^0", "1.0.0", false], + ["^0.1", "0.1.0"], + ["^0.1", "0.1.2"], + ["^0.1", "0.1.9"], + ["^0.1.2", "0.1.2"], + ["^0.1.2", "0.1.9"], + ["^0.1.2", "0.0.0", false], + ["^0.1.2", "0.2.0", false], + ["^0.1.2", "1.0.0", false], + ["^1", "1.0.0"], + ["^1", "1.2.0"], + ["^1", "1.2.3"], + ["^1", "1.9.0"], + ["^1", "0.0.0", false], + ["^1", "2.0.0", false], + ["^1.2", "1.2.0"], + ["^1.2", "1.2.3"], + ["^1.2", "1.9.0"], + ["^1.2", "1.1.0", false], + ["^1.2", "2.0.0", false], + ["^1.2.3", "1.2.3"], + ["^1.2.3", "1.9.0"], + ["^1.2.3", "1.2.2", false], + ["^1.2.3", "2.0.0", false], + ]); }); }); } \ No newline at end of file From 37c33f43696526db33470825c3614c783db1bebb Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 28 Aug 2018 17:24:02 -0700 Subject: [PATCH 029/146] Use semver ranges --- Gulpfile.js | 65 +++++++++---- package.json | 1 + scripts/build/cancellation.js | 71 -------------- scripts/build/countdown.js | 62 ------------- scripts/build/exec.js | 14 ++- scripts/build/project.js | 92 +++++++++++-------- scripts/build/tests.js | 3 +- src/compiler/moduleNameResolver.ts | 26 ++---- .../reference/typesVersions.ambientModules.js | 2 +- .../typesVersions.ambientModules.trace.json | 6 +- .../reference/typesVersions.multiFile.js | 2 +- .../typesVersions.multiFile.trace.json | 4 +- .../typesVersionsDeclarationEmit.ambient.js | 2 +- ...VersionsDeclarationEmit.ambient.trace.json | 6 +- .../typesVersionsDeclarationEmit.multiFile.js | 2 +- ...rsionsDeclarationEmit.multiFile.trace.json | 4 +- ...it.multiFileBackReferenceToSelf.errors.txt | 2 +- ...rationEmit.multiFileBackReferenceToSelf.js | 2 +- ...it.multiFileBackReferenceToSelf.trace.json | 6 +- ...onEmit.multiFileBackReferenceToUnmapped.js | 2 +- ...ultiFileBackReferenceToUnmapped.trace.json | 4 +- .../typesVersionsDeclarationEmit.ambient.ts | 2 +- .../typesVersionsDeclarationEmit.multiFile.ts | 2 +- ...rationEmit.multiFileBackReferenceToSelf.ts | 2 +- ...onEmit.multiFileBackReferenceToUnmapped.ts | 2 +- .../typesVersions.ambientModules.ts | 2 +- .../typesVersions.multiFile.ts | 2 +- 27 files changed, 146 insertions(+), 244 deletions(-) delete mode 100644 scripts/build/cancellation.js delete mode 100644 scripts/build/countdown.js diff --git a/Gulpfile.js b/Gulpfile.js index b2fb584d4a2..6dc78d1e5ee 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -24,10 +24,9 @@ const baselineAccept = require("./scripts/build/baselineAccept"); const cmdLineOptions = require("./scripts/build/options"); const exec = require("./scripts/build/exec"); const browserify = require("./scripts/build/browserify"); -const debounce = require("./scripts/build/debounce"); const prepend = require("./scripts/build/prepend"); const { removeSourceMaps } = require("./scripts/build/sourcemaps"); -const { CancelSource, CancelError } = require("./scripts/build/cancellation"); +const { CancellationTokenSource, CancelError, delay, Semaphore } = require("prex"); const { libraryTargets, generateLibs } = require("./scripts/build/lib"); const { runConsoleTests, cleanTestDirs, writeTestConfigFile, refBaseline, localBaseline, refRwcBaseline, localRwcBaseline } = require("./scripts/build/tests"); @@ -556,35 +555,61 @@ gulp.task( "Watches for changes to the build inputs for built/local/run.js, then executes runtests-parallel.", ["build-rules", "watch-runner", "watch-services", "watch-lssl"], () => { - /** @type {CancelSource | undefined} */ - let runTestsSource; + const runTestsSemaphore = new Semaphore(1); + const fn = async () => { + try { + // Ensure only one instance of the test runner is running at any given time. + if (runTestsSemaphore.count > 0) { + await runTestsSemaphore.wait(); + try { + // Wait for any concurrent recompilations to complete... + try { + await delay(100); + while (project.hasRemainingWork()) { + await project.waitForWorkToComplete(); + await delay(500); + } + } + catch (e) { + if (e instanceof CancelError) return; + throw e; + } - const fn = debounce(() => { - runTests().catch(error => { - if (error instanceof CancelError) { + // cancel any pending or active test run if a new recompilation is triggered + const runTestsSource = new CancellationTokenSource(); + project.waitForWorkToStart().then(() => { + runTestsSource.cancel(); + }); + + if (cmdLineOptions.tests || cmdLineOptions.failed) { + await runConsoleTests(runJs, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ true, runTestsSource.token); + } + else { + await runConsoleTests(runJs, "min", /*runInParallel*/ true, /*watchMode*/ true, runTestsSource.token); + } + } + finally { + runTestsSemaphore.release(); + } + } + } + catch (e) { + if (e instanceof CancelError) { log.warn("Operation was canceled"); } else { - log.error(error); + log.error(e); } - }); - }, /*timeout*/ 100, { max: 500 }); + } + }; - gulp.watch(watchPatterns, () => project.wait(runTestsSource && runTestsSource.token).then(fn)); + gulp.watch(watchPatterns, (e) => fn()); // NOTE: gulp.watch is far too slow when watching tests/cases/**/* as it first enumerates *every* file const testFilePattern = /(\.ts|[\\/]tsconfig\.json)$/; fs.watch("tests/cases", { recursive: true }, (_, file) => { - if (testFilePattern.test(file)) project.wait(runTestsSource && runTestsSource.token).then(fn); + if (testFilePattern.test(file)) fn(); }); - - function runTests() { - if (runTestsSource) runTestsSource.cancel(); - runTestsSource = new CancelSource(); - return cmdLineOptions.tests || cmdLineOptions.failed - ? runConsoleTests(runJs, "mocha-fivemat-progress-reporter", /*runInParallel*/ false, /*watchMode*/ true, runTestsSource.token) - : runConsoleTests(runJs, "min", /*runInParallel*/ true, /*watchMode*/ true, runTestsSource.token); - } }); gulp.task("clean-built", /*help*/ false, [`clean:${diagnosticInformationMapTs}`], () => del(["built"])); diff --git a/package.json b/package.json index 510d3aab53b..55acc40268d 100644 --- a/package.json +++ b/package.json @@ -81,6 +81,7 @@ "mocha": "latest", "mocha-fivemat-progress-reporter": "latest", "plugin-error": "latest", + "prex": "^0.4.3", "q": "latest", "remove-internal": "^2.9.2", "run-sequence": "latest", diff --git a/scripts/build/cancellation.js b/scripts/build/cancellation.js deleted file mode 100644 index 793aaf19d86..00000000000 --- a/scripts/build/cancellation.js +++ /dev/null @@ -1,71 +0,0 @@ -// @ts-check -const symSource = Symbol("CancelToken.source"); -const symToken = Symbol("CancelSource.token"); -const symCancellationRequested = Symbol("CancelSource.cancellationRequested"); -const symCancellationCallbacks = Symbol("CancelSource.cancellationCallbacks"); - -class CancelSource { - constructor() { - this[symCancellationRequested] = false; - this[symCancellationCallbacks] = []; - } - - /** @type {CancelToken} */ - get token() { - return this[symToken] || (this[symToken] = new CancelToken(this)); - } - - cancel() { - if (!this[symCancellationRequested]) { - this[symCancellationRequested] = true; - for (const callback of this[symCancellationCallbacks]) { - callback(); - } - } - } -} -exports.CancelSource = CancelSource; - -class CancelToken { - /** - * @param {CancelSource} source - */ - constructor(source) { - if (source[symToken]) return source[symToken]; - this[symSource] = source; - } - - /** @type {boolean} */ - get cancellationRequested() { - return this[symSource][symCancellationRequested]; - } - - /** - * @param {() => void} callback - */ - subscribe(callback) { - const source = this[symSource]; - if (source[symCancellationRequested]) { - callback(); - return; - } - - source[symCancellationCallbacks].push(callback); - - return { - unsubscribe() { - const index = source[symCancellationCallbacks].indexOf(callback); - if (index !== -1) source[symCancellationCallbacks].splice(index, 1); - } - }; - } -} -exports.CancelToken = CancelToken; - -class CancelError extends Error { - constructor(message = "Operation was canceled") { - super(message); - this.name = "CancelError"; - } -} -exports.CancelError = CancelError; \ No newline at end of file diff --git a/scripts/build/countdown.js b/scripts/build/countdown.js deleted file mode 100644 index dda05352d28..00000000000 --- a/scripts/build/countdown.js +++ /dev/null @@ -1,62 +0,0 @@ -// @ts-check -const { CancelToken } = require("./cancellation"); - -class Countdown { - constructor(initialCount = 0) { - if (initialCount < 0) throw new Error(); - this._remainingCount = initialCount; - this._promise = undefined; - this._resolve = undefined; - } - - get remainingCount() { - return this._remainingCount; - } - - add(count = 1) { - if (count < 1 || !isFinite(count) || Math.trunc(count) !== count) throw new Error(); - if (this._remainingCount === 0) { - this._promise = undefined; - this._resolve = undefined; - } - - this._remainingCount += count; - } - - signal(count = 1) { - if (count < 1 || !isFinite(count) || Math.trunc(count) !== count) throw new Error(); - if (this._remainingCount - count < 0) throw new Error(); - this._remainingCount -= count; - if (this._remainingCount == 0) { - if (this._resolve) { - this._resolve(); - } - return true; - } - return false; - } - - /** @param {CancelToken} [token] */ - wait(token) { - if (!this._promise) { - this._promise = new Promise(resolve => { this._resolve = resolve; }); - } - if (this._remainingCount === 0) { - this._resolve(); - } - if (!token) return this._promise; - return new Promise((resolve, reject) => { - const subscription = token.subscribe(reject); - this._promise.then( - value => { - subscription.unsubscribe(); - resolve(value); - }, - error => { - subscription.unsubscribe(); - reject(error); - }); - }); - } -} -exports.Countdown = Countdown; \ No newline at end of file diff --git a/scripts/build/exec.js b/scripts/build/exec.js index 068bf33b9e9..024cb6d3b5b 100644 --- a/scripts/build/exec.js +++ b/scripts/build/exec.js @@ -3,7 +3,7 @@ const cp = require("child_process"); const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util) const isWin = /^win/.test(process.platform); const chalk = require("./chalk"); -const { CancelToken, CancelError } = require("./cancellation"); +const { CancelError } = require("prex"); module.exports = exec; @@ -15,16 +15,20 @@ module.exports = exec; * * @typedef ExecOptions * @property {boolean} [ignoreExitCode] - * @property {CancelToken} [cancelToken] + * @property {import("prex").CancellationToken} [cancelToken] */ function exec(cmd, args, options = {}) { return /**@type {Promise<{exitCode: number}>}*/(new Promise((resolve, reject) => { + if (options.cancelToken) { + options.cancelToken.throwIfCancellationRequested(); + } + log(`> ${chalk.green(cmd)} ${args.join(" ")}`); // TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition const subshellFlag = isWin ? "/c" : "-c"; const command = isWin ? [possiblyQuote(cmd), ...args] : [`${cmd} ${args.join(" ")}`]; const ex = cp.spawn(isWin ? "cmd" : "/bin/sh", [subshellFlag, ...command], { stdio: "inherit", windowsVerbatimArguments: true }); - const subscription = options.cancelToken && options.cancelToken.subscribe(() => { + const subscription = options.cancelToken && options.cancelToken.register(() => { log(`${chalk.red("killing")} '${chalk.green(cmd)} ${args.join(" ")}'...`); ex.kill("SIGINT"); ex.kill("SIGTERM"); @@ -32,7 +36,7 @@ function exec(cmd, args, options = {}) { reject(new CancelError()); }); ex.on("exit", exitCode => { - subscription && subscription.unsubscribe(); + if (subscription) subscription.unregister(); if (exitCode === 0 || options.ignoreExitCode) { resolve({ exitCode }); } @@ -41,7 +45,7 @@ function exec(cmd, args, options = {}) { } }); ex.on("error", error => { - subscription && subscription.unsubscribe(); + if (subscription) subscription.unregister(); reject(error); }); })); diff --git a/scripts/build/project.js b/scripts/build/project.js index 8519e4c71ec..bd41926a204 100644 --- a/scripts/build/project.js +++ b/scripts/build/project.js @@ -3,6 +3,8 @@ const path = require("path"); const fs = require("fs"); const gulp = require("./gulp"); const gulpif = require("gulp-if"); +const log = require("fancy-log"); // was `require("gulp-util").log (see https://github.com/gulpjs/gulp-util) +const chalk = require("./chalk"); const sourcemaps = require("gulp-sourcemaps"); const merge2 = require("merge2"); const tsc = require("gulp-typescript"); @@ -12,42 +14,51 @@ const ts = require("../../lib/typescript"); const del = require("del"); const needsUpdate = require("./needsUpdate"); const mkdirp = require("./mkdirp"); +const prettyTime = require("pretty-hrtime"); const { reportDiagnostics } = require("./diagnostics"); -const { Countdown } = require("./countdown"); -const { CancelToken } = require("./cancellation"); +const { CountdownEvent, Pulsar } = require("prex"); -const countdown = new Countdown(); +const workStartedEvent = new Pulsar(); +const countdown = new CountdownEvent(0); class CompilationGulp extends gulp.Gulp { - constructor() { - super(); - this.on("start", () => { - const onDone = () => { - this.removeListener("stop", onDone); - this.removeListener("err", onDone); - countdown.signal(); - }; - - this.on("stop", onDone); - this.on("err", onDone); - countdown.add(); - }); - } - /** * @param {boolean} [verbose] */ fork(verbose) { const child = new ForkedGulp(this.tasks); - if (verbose) { - child.on("task_start", e => gulp.emit("task_start", e)); - child.on("task_stop", e => gulp.emit("task_stop", e)); - child.on("task_err", e => gulp.emit("task_err", e)); - child.on("task_not_found", e => gulp.emit("task_not_found", e)); - child.on("task_recursion", e => gulp.emit("task_recursion", e)); - } + child.on("task_start", e => { + if (countdown.remainingCount === 0) { + countdown.reset(1); + workStartedEvent.pulseAll(); + } + else { + countdown.add(); + } + if (verbose) { + log('Starting', `'${chalk.cyan(e.task)}' ${chalk.gray(`(${countdown.remainingCount} remaining)`)}...`); + } + }); + child.on("task_stop", e => { + countdown.signal(); + if (verbose) { + log('Finished', `'${chalk.cyan(e.task)}' after ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`); + } + }); + child.on("task_err", e => { + countdown.signal(); + if (verbose) { + log(`'${chalk.cyan(e.task)}' ${chalk.red("errored after")} ${chalk.magenta(prettyTime(/** @type {*}*/(e).hrDuration))} ${chalk.gray(`(${countdown.remainingCount} remaining)`)}`); + log(e.err ? e.err.stack : e.message); + } + }); return child; } + + // @ts-ignore + start() { + throw new Error("Not supported, use fork."); + } } class ForkedGulp extends gulp.Gulp { @@ -57,17 +68,6 @@ class ForkedGulp extends gulp.Gulp { constructor(tasks) { super(); this.tasks = tasks; - this.on("start", () => { - const onDone = () => { - this.removeListener("stop", onDone); - this.removeListener("err", onDone); - countdown.signal(); - }; - - this.on("stop", onDone); - this.on("err", onDone); - countdown.add(); - }); } // Do not reset tasks @@ -241,12 +241,26 @@ exports.flatten = flatten; /** * Returns a Promise that resolves when all pending build tasks have completed - * @param {CancelToken} [token] + * @param {import("prex").CancellationToken} [token] */ -function wait(token) { +function waitForWorkToComplete(token) { return countdown.wait(token); } -exports.wait = wait; +exports.waitForWorkToComplete = waitForWorkToComplete; + +/** + * Returns a Promise that resolves when all pending build tasks have completed + * @param {import("prex").CancellationToken} [token] + */ +function waitForWorkToStart(token) { + return workStartedEvent.wait(token); +} +exports.waitForWorkToStart = waitForWorkToStart; + +function getRemainingWork() { + return countdown.remainingCount > 0; +} +exports.hasRemainingWork = getRemainingWork; /** * Resolve a TypeScript specifier into a fully-qualified module specifier and any requisite dependencies. diff --git a/scripts/build/tests.js b/scripts/build/tests.js index d631f1e35ac..3fd65b2c859 100644 --- a/scripts/build/tests.js +++ b/scripts/build/tests.js @@ -21,7 +21,7 @@ exports.localTest262Baseline = "internal/baselines/test262/local"; * @param {string} defaultReporter * @param {boolean} runInParallel * @param {boolean} watchMode - * @param {InstanceType} [cancelToken] + * @param {import("prex").CancellationToken} [cancelToken] */ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, cancelToken) { let testTimeout = cmdLineOptions.timeout; @@ -37,6 +37,7 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, const keepFailed = cmdLineOptions.keepFailed; if (!cmdLineOptions.dirty) { await cleanTestDirs(); + if (cancelToken) cancelToken.throwIfCancellationRequested(); } if (fs.existsSync(testConfigFile)) { diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 6545ce353e6..0c2d35f19a8 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -188,31 +188,21 @@ namespace ts { /* @internal */ export function getPackageJsonTypesVersionsPaths(typesVersions: MapLike>) { - if (!typeScriptVersion) typeScriptVersion = new Version(versionMajorMinor); + if (!typeScriptVersion) typeScriptVersion = new Version(version); - let bestVersion: Version | undefined; - let bestVersionKey: string | undefined; for (const key in typesVersions) { if (!hasProperty(typesVersions, key)) continue; - const keyVersion = Version.tryParse(key); - if (keyVersion === undefined) { + const keyRange = VersionRange.tryParse(key); + if (keyRange === undefined) { continue; } - // match the greatest version less than the current TypeScript version - if (keyVersion.compareTo(bestVersion) > 0 && - keyVersion.compareTo(typeScriptVersion) <= 0) { - bestVersion = keyVersion; - bestVersionKey = key; + // return the first entry whose range matches the current compiler version. + if (keyRange.test(typeScriptVersion)) { + return { version: key, paths: typesVersions[key] }; } } - - if (!bestVersionKey) { - return; - } - - return { version: bestVersionKey, paths: typesVersions[bestVersionKey] }; } export function getEffectiveTypeRoots(options: CompilerOptions, host: GetEffectiveTypeRootsHost): string[] | undefined { @@ -1132,7 +1122,7 @@ namespace ts { if (versionPaths && containsPath(candidate, file)) { const moduleName = getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, versionMajorMinor, moduleName); + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, moduleName); } const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); if (result) { @@ -1255,7 +1245,7 @@ namespace ts { if (packageInfo) ({ packageId, versionPaths } = packageInfo); if (versionPaths) { if (state.traceEnabled) { - trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, versionMajorMinor, rest); + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, versionPaths.version, version, rest); } const packageDirectoryExists = nodeModulesDirectoryExists && directoryProbablyExists(packageDirectory, state.host); const fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, versionPaths.paths, loader, !packageDirectoryExists, state); diff --git a/tests/baselines/reference/typesVersions.ambientModules.js b/tests/baselines/reference/typesVersions.ambientModules.js index 1d7e3f04ec3..7dee6e9e3fd 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.js +++ b/tests/baselines/reference/typesVersions.ambientModules.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersions.ambientModules.trace.json b/tests/baselines/reference/typesVersions.ambientModules.trace.json index 7a442ce5048..8e4d2ecba2d 100644 --- a/tests/baselines/reference/typesVersions.ambientModules.trace.json +++ b/tests/baselines/reference/typesVersions.ambientModules.trace.json @@ -11,7 +11,7 @@ "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", @@ -26,7 +26,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", @@ -41,7 +41,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.js' does not exist.", diff --git a/tests/baselines/reference/typesVersions.multiFile.js b/tests/baselines/reference/typesVersions.multiFile.js index 14f7fd8aaf4..cca708988c6 100644 --- a/tests/baselines/reference/typesVersions.multiFile.js +++ b/tests/baselines/reference/typesVersions.multiFile.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersions.multiFile.trace.json b/tests/baselines/reference/typesVersions.multiFile.trace.json index e7245fa5765..d52db48acfe 100644 --- a/tests/baselines/reference/typesVersions.multiFile.trace.json +++ b/tests/baselines/reference/typesVersions.multiFile.trace.json @@ -11,7 +11,7 @@ "File 'tests/cases/conformance/moduleResolution/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/moduleResolution/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/index' does not exist.", @@ -26,7 +26,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/moduleResolution/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/moduleResolution/node_modules/ext/ts3.1/other.ts' does not exist.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js index b1af852940b..ddd2f8b0ef5 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json index c3b0e232748..f1db86cc283 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.ambient.trace.json @@ -11,7 +11,7 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", @@ -26,7 +26,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", @@ -41,7 +41,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'JavaScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.js' does not exist.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js index 22cdb0087ef..5fd7da959ea 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json index 532e80feac7..eee9622037b 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFile.trace.json @@ -11,7 +11,7 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", @@ -26,7 +26,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt index 66624634d9f..540dd917fa0 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.errors.txt @@ -9,7 +9,7 @@ tests/cases/conformance/declarationEmit/main.ts(1,10): error TS2305: Module '"te "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js index c7b885d5e9e..ab415ca2b61 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json index 33d5a0e3177..cf08a29478f 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.trace.json @@ -9,7 +9,7 @@ "'package.json' has a 'typesVersions' field with version-specific path mappings.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", @@ -39,7 +39,7 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", @@ -54,7 +54,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "Module name 'other', matched pattern '*'.", "Trying substitution 'ts3.1/*', candidate module location: 'ts3.1/other'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/other.ts' does not exist.", diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js index 86a621161f6..fb7dfd74b2d 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.js @@ -6,7 +6,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { + ">=3.1.0-0": { "index" : ["ts3.1/index"] } } diff --git a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json index d31c0730fd9..fe65b605283 100644 --- a/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json +++ b/tests/baselines/reference/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.trace.json @@ -20,7 +20,7 @@ "File 'tests/cases/conformance/declarationEmit/node_modules/ext.d.ts' does not exist.", "'package.json' does not have a 'typings' field.", "'package.json' has 'types' field 'index' that references 'tests/cases/conformance/declarationEmit/node_modules/ext/index'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'index'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'index'.", "Module name 'index', matched pattern 'index'.", "Trying substitution 'ts3.1/index', candidate module location: 'ts3.1/index'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/ts3.1/index' does not exist.", @@ -35,7 +35,7 @@ "Loading module 'ext/other' from 'node_modules' folder, target file type 'TypeScript'.", "'package.json' has a 'typesVersions' field with version-specific path mappings.", "Found 'package.json' at 'tests/cases/conformance/declarationEmit/node_modules/ext/package.json'. Package ID is 'ext/other/index.d.ts@1.0.0'.", - "'package.json' has a 'typesVersions' entry '3.1' that matches compiler version '3.1', looking for a pattern to match module name 'other'.", + "'package.json' has a 'typesVersions' entry '>=3.1.0-0' that matches compiler version '3.1.0-dev', looking for a pattern to match module name 'other'.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.ts' does not exist.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.tsx' does not exist.", "File 'tests/cases/conformance/declarationEmit/node_modules/ext/other.d.ts' exist - use it as a name resolution result.", diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts index 447f3aaa82a..b03c1eea078 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.ambient.ts @@ -9,7 +9,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts index 57ae6c1d631..01adfac0480 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFile.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts index 3391361225d..ee37f436302 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToSelf.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts index 15072d2a7ed..7ef6adcce52 100644 --- a/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts +++ b/tests/cases/conformance/declarationEmit/typesVersionsDeclarationEmit.multiFileBackReferenceToUnmapped.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { + ">=3.1.0-0": { "index" : ["ts3.1/index"] } } diff --git a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts index 2de5f470473..870a1a1308d 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.ambientModules.ts @@ -8,7 +8,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } diff --git a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts index 8d57630af21..14a05118b65 100644 --- a/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts +++ b/tests/cases/conformance/moduleResolution/typesVersions.multiFile.ts @@ -7,7 +7,7 @@ "version": "1.0.0", "types": "index", "typesVersions": { - "3.1": { "*" : ["ts3.1/*"] } + ">=3.1.0-0": { "*" : ["ts3.1/*"] } } } From 0d3adffd1a87bec80e36feda4caad3638ff28b95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Wed, 29 Aug 2018 18:42:02 +0800 Subject: [PATCH 030/146] accept baseline --- ...ctAndSimpleParameterList_es2016.errors.txt | 114 +++++++++--------- 1 file changed, 57 insertions(+), 57 deletions(-) diff --git a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt index 4887cb4f07a..4f92ac06b2b 100644 --- a/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt +++ b/tests/baselines/reference/functionWithUseStrictAndSimpleParameterList_es2016.errors.txt @@ -1,33 +1,33 @@ -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(1,12): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(2,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(15,15): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(16,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,16): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,23): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(20,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(23,23): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(24,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(27,31): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(28,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,30): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(32,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,24): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,32): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(36,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,23): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,31): error TS1345: This parameter is not allowed with 'use strict' directive. -tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(41,5): error TS1346: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(1,12): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(2,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(15,15): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(16,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,16): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(19,23): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(20,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(23,23): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(24,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(27,31): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(28,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(31,30): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(32,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,24): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(35,32): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(36,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,23): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(39,31): error TS1346: This parameter is not allowed with 'use strict' directive. +tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts(41,5): error TS1347: 'use strict' directive cannot be used with non-simple parameter list. ==== tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts (19 errors) ==== function a(a = 10) { ~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:2:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:2:5: 'use strict' directive used here. "use strict"; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:1:12: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:1:12: Non-simple parameter declared here. } export var foo = 10; @@ -42,84 +42,84 @@ tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es function rest(...args: any[]) { ~~~~~~~~~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:16:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:16:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:15:15: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:15:15: Non-simple parameter declared here. } function rest1(a = 1, ...args) { ~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. ~~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:20:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:16: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:16: Non-simple parameter declared here. !!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:19:23: and here. } function paramDefault(param = 1) { ~~~~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:24:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:24:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:23:23: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:23:23: Non-simple parameter declared here. } function objectBindingPattern({foo}: any) { ~~~~~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:28:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:28:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:27:31: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:27:31: Non-simple parameter declared here. } function arrayBindingPattern([foo]: any[]) { ~~~~~~~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:32:5: 'use strict' directive used here. 'use strict'; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:30: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:31:30: Non-simple parameter declared here. } function manyParameter(a = 10, b = 20) { ~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. ~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:36:5: 'use strict' directive used here. "use strict"; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:24: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:24: Non-simple parameter declared here. !!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:35:32: and here. } function manyPrologue(a = 10, b = 20) { ~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. ~~~~~~ -!!! error TS1345: This parameter is not allowed with 'use strict' directive. -!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. +!!! error TS1346: This parameter is not allowed with 'use strict' directive. +!!! related TS1349 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:41:5: 'use strict' directive used here. "foo"; "use strict"; ~~~~~~~~~~~~~ -!!! error TS1346: 'use strict' directive cannot be used with non-simple parameter list. -!!! related TS1347 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:39:23: Non-simple parameter declared here. +!!! error TS1347: 'use strict' directive cannot be used with non-simple parameter list. +!!! related TS1348 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:39:23: Non-simple parameter declared here. !!! related TS6204 tests/cases/conformance/functions/functionWithUseStrictAndSimpleParameterList_es2016.ts:39:31: and here. } From 2fe349915319278ca7fbcc7a22da8b0aa175d572 Mon Sep 17 00:00:00 2001 From: Mine Starks Date: Thu, 30 Aug 2018 14:02:26 -0700 Subject: [PATCH 031/146] Fix faulty path handling --- src/server/editorServices.ts | 2 +- src/tsserver/server.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 117887d7611..ca8c61311ec 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -472,7 +472,7 @@ namespace ts.server { this.globalPlugins = opts.globalPlugins || emptyArray; this.pluginProbeLocations = opts.pluginProbeLocations || emptyArray; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; - this.typesMapLocation = (opts.typesMapLocation === undefined) ? combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; + this.typesMapLocation = (opts.typesMapLocation === undefined) ? combinePaths(getDirectoryPath(this.getExecutingFilePath()), "typesMap.json") : opts.typesMapLocation; this.syntaxOnly = opts.syntaxOnly; Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 3e5986e9408..d7ced146707 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -920,7 +920,7 @@ namespace ts.server { setStackTraceLimit(); const typingSafeListLocation = findArgument(Arguments.TypingSafeListLocation)!; // TODO: GH#18217 - const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(sys.getExecutingFilePath(), "../typesMap.json"); + const typesMapLocation = findArgument(Arguments.TypesMapLocation) || combinePaths(getDirectoryPath(sys.getExecutingFilePath()), "typesMap.json"); const npmLocation = findArgument(Arguments.NpmLocation); function parseStringArray(argName: string): ReadonlyArray { From 50ccd91263b5a3c7f53749e9bde3ca4520e5af0b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 13 Aug 2018 16:21:37 -0700 Subject: [PATCH 032/146] Baseline the require of json file in js file --- .../requireOfJsonFileInJsFile.errors.txt | 33 ++++++++++ .../requireOfJsonFileInJsFile.symbols | 50 +++++++++++++++ .../reference/requireOfJsonFileInJsFile.types | 63 +++++++++++++++++++ .../compiler/requireOfJsonFileInJsFile.ts | 26 ++++++++ 4 files changed, 172 insertions(+) create mode 100644 tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt create mode 100644 tests/baselines/reference/requireOfJsonFileInJsFile.symbols create mode 100644 tests/baselines/reference/requireOfJsonFileInJsFile.types create mode 100644 tests/cases/compiler/requireOfJsonFileInJsFile.ts diff --git a/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt b/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt new file mode 100644 index 00000000000..39236816e57 --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt @@ -0,0 +1,33 @@ +/user.js(2,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'. +/user.js(9,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'. +/user.js(12,7): error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'. + Property 'b' is missing in type '{ a: number; }'. + + +==== /user.js (3 errors) ==== + const json0 = require("./json.json"); + json0.b; // Error (good) + ~ +!!! error TS2339: Property 'b' does not exist on type '{ "a": number; }'. + + /** @type {{ b: number }} */ + const json1 = require("./json.json"); // No error (bad) + json1.b; // No error (OK since that's the type annotation) + + const js0 = require("./js.js"); + json0.b; // Error (good) + ~ +!!! error TS2339: Property 'b' does not exist on type '{ "a": number; }'. + + /** @type {{ b: number }} */ + const js1 = require("./js.js"); // Error (good) + ~~~ +!!! error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'. +!!! error TS2322: Property 'b' is missing in type '{ a: number; }'. + js1.b; +==== /json.json (0 errors) ==== + { "a": 0 } + +==== /js.js (0 errors) ==== + module.exports = { a: 0 }; + \ No newline at end of file diff --git a/tests/baselines/reference/requireOfJsonFileInJsFile.symbols b/tests/baselines/reference/requireOfJsonFileInJsFile.symbols new file mode 100644 index 00000000000..2a1e9b6ebd3 --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileInJsFile.symbols @@ -0,0 +1,50 @@ +=== /user.js === +const json0 = require("./json.json"); +>json0 : Symbol(json0, Decl(user.js, 0, 5)) +>require : Symbol(require) +>"./json.json" : Symbol("/json", Decl(json.json, 0, 0)) + +json0.b; // Error (good) +>json0 : Symbol(json0, Decl(user.js, 0, 5)) + +/** @type {{ b: number }} */ +const json1 = require("./json.json"); // No error (bad) +>json1 : Symbol(json1, Decl(user.js, 4, 5)) +>require : Symbol(require) +>"./json.json" : Symbol("/json", Decl(json.json, 0, 0)) + +json1.b; // No error (OK since that's the type annotation) +>json1.b : Symbol(b, Decl(user.js, 3, 12)) +>json1 : Symbol(json1, Decl(user.js, 4, 5)) +>b : Symbol(b, Decl(user.js, 3, 12)) + +const js0 = require("./js.js"); +>js0 : Symbol(js0, Decl(user.js, 7, 5)) +>require : Symbol(require) +>"./js.js" : Symbol("/js", Decl(js.js, 0, 0)) + +json0.b; // Error (good) +>json0 : Symbol(json0, Decl(user.js, 0, 5)) + +/** @type {{ b: number }} */ +const js1 = require("./js.js"); // Error (good) +>js1 : Symbol(js1, Decl(user.js, 11, 5)) +>require : Symbol(require) +>"./js.js" : Symbol("/js", Decl(js.js, 0, 0)) + +js1.b; +>js1.b : Symbol(b, Decl(user.js, 10, 12)) +>js1 : Symbol(js1, Decl(user.js, 11, 5)) +>b : Symbol(b, Decl(user.js, 10, 12)) + +=== /json.json === +{ "a": 0 } +>"a" : Symbol("a", Decl(json.json, 0, 1)) + +=== /js.js === +module.exports = { a: 0 }; +>module.exports : Symbol("/js", Decl(js.js, 0, 0)) +>module : Symbol(export=, Decl(js.js, 0, 0)) +>exports : Symbol(export=, Decl(js.js, 0, 0)) +>a : Symbol(a, Decl(js.js, 0, 18)) + diff --git a/tests/baselines/reference/requireOfJsonFileInJsFile.types b/tests/baselines/reference/requireOfJsonFileInJsFile.types new file mode 100644 index 00000000000..b069c87c395 --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileInJsFile.types @@ -0,0 +1,63 @@ +=== /user.js === +const json0 = require("./json.json"); +>json0 : { "a": number; } +>require("./json.json") : { "a": number; } +>require : any +>"./json.json" : "./json.json" + +json0.b; // Error (good) +>json0.b : any +>json0 : { "a": number; } +>b : any + +/** @type {{ b: number }} */ +const json1 = require("./json.json"); // No error (bad) +>json1 : { b: number; } +>require("./json.json") : { "a": number; } +>require : any +>"./json.json" : "./json.json" + +json1.b; // No error (OK since that's the type annotation) +>json1.b : number +>json1 : { b: number; } +>b : number + +const js0 = require("./js.js"); +>js0 : { a: number; } +>require("./js.js") : { a: number; } +>require : any +>"./js.js" : "./js.js" + +json0.b; // Error (good) +>json0.b : any +>json0 : { "a": number; } +>b : any + +/** @type {{ b: number }} */ +const js1 = require("./js.js"); // Error (good) +>js1 : { b: number; } +>require("./js.js") : { a: number; } +>require : any +>"./js.js" : "./js.js" + +js1.b; +>js1.b : number +>js1 : { b: number; } +>b : number + +=== /json.json === +{ "a": 0 } +>{ "a": 0 } : { "a": number; } +>"a" : number +>0 : 0 + +=== /js.js === +module.exports = { a: 0 }; +>module.exports = { a: 0 } : { a: number; } +>module.exports : { a: number; } +>module : { "/js": { a: number; }; } +>exports : { a: number; } +>{ a: 0 } : { a: number; } +>a : number +>0 : 0 + diff --git a/tests/cases/compiler/requireOfJsonFileInJsFile.ts b/tests/cases/compiler/requireOfJsonFileInJsFile.ts new file mode 100644 index 00000000000..be8a3b00746 --- /dev/null +++ b/tests/cases/compiler/requireOfJsonFileInJsFile.ts @@ -0,0 +1,26 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @strict: true +// @resolveJsonModule: true + +// @Filename: /json.json +{ "a": 0 } + +// @Filename: /js.js +module.exports = { a: 0 }; + +// @Filename: /user.js +const json0 = require("./json.json"); +json0.b; // Error (good) + +/** @type {{ b: number }} */ +const json1 = require("./json.json"); // No error (bad) +json1.b; // No error (OK since that's the type annotation) + +const js0 = require("./js.js"); +json0.b; // Error (good) + +/** @type {{ b: number }} */ +const js1 = require("./js.js"); // Error (good) +js1.b; \ No newline at end of file From 9eb0c9a88fa4f1cc5e83a314e6710079f67aa4ca Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 14 Aug 2018 13:24:39 -0700 Subject: [PATCH 033/146] Use widened type (just like importing using module.exports = in js file) Fixes #26429 --- src/compiler/checker.ts | 9 ++++++++- .../reference/requireOfJsonFileInJsFile.errors.txt | 7 ++++++- .../baselines/reference/requireOfJsonFileTypes.types | 12 ++++++------ 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..83cd2c1fe5c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5092,7 +5092,14 @@ namespace ts { // Handle export default expressions if (isSourceFile(declaration)) { const jsonSourceFile = cast(declaration, isJsonSourceFile); - return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType; + if (!jsonSourceFile.statements.length) { + return emptyObjectType; + } + const type = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + if (type.flags & TypeFlags.Object) { + return getRegularTypeOfObjectLiteral(type); + } + return type; } if (declaration.kind === SyntaxKind.ExportAssignment) { return checkExpression((declaration).expression); diff --git a/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt b/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt index 39236816e57..dcc976a1b5b 100644 --- a/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt +++ b/tests/baselines/reference/requireOfJsonFileInJsFile.errors.txt @@ -1,10 +1,12 @@ /user.js(2,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'. +/user.js(5,7): error TS2322: Type '{ "a": number; }' is not assignable to type '{ b: number; }'. + Property 'b' is missing in type '{ "a": number; }'. /user.js(9,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'. /user.js(12,7): error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'. Property 'b' is missing in type '{ a: number; }'. -==== /user.js (3 errors) ==== +==== /user.js (4 errors) ==== const json0 = require("./json.json"); json0.b; // Error (good) ~ @@ -12,6 +14,9 @@ /** @type {{ b: number }} */ const json1 = require("./json.json"); // No error (bad) + ~~~~~ +!!! error TS2322: Type '{ "a": number; }' is not assignable to type '{ b: number; }'. +!!! error TS2322: Property 'b' is missing in type '{ "a": number; }'. json1.b; // No error (OK since that's the type annotation) const js0 = require("./js.js"); diff --git a/tests/baselines/reference/requireOfJsonFileTypes.types b/tests/baselines/reference/requireOfJsonFileTypes.types index d9cd38cd58f..d4587696fc7 100644 --- a/tests/baselines/reference/requireOfJsonFileTypes.types +++ b/tests/baselines/reference/requireOfJsonFileTypes.types @@ -6,10 +6,10 @@ import c = require('./c.json'); >c : (string | null)[] import d = require('./d.json'); ->d : "dConfig" +>d : string import e = require('./e.json'); ->e : -10 +>e : number import f = require('./f.json'); >f : number[] @@ -64,14 +64,14 @@ const stringOrNumberOrNull: string | number | null = c[0]; >0 : 0 stringLiteral = d; ->stringLiteral = d : "dConfig" +>stringLiteral = d : string >stringLiteral : string ->d : "dConfig" +>d : string numberLiteral = e; ->numberLiteral = e : -10 +>numberLiteral = e : number >numberLiteral : number ->e : -10 +>e : number numberLiteral = f[0]; >numberLiteral = f[0] : number From e41dbcdccd9c877c777cf63d2c13e12afc26a629 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 31 Aug 2018 13:05:52 -0700 Subject: [PATCH 034/146] Support json module emit when module emit is commonjs, amd, es2015 or esnext Fixes #25755 and #26020 --- src/compiler/checker.ts | 2 +- src/compiler/diagnosticMessages.json | 2 +- src/compiler/emitter.ts | 4 +++- src/compiler/program.ts | 6 +++--- src/compiler/transformers/module/module.ts | 12 ++++++++--- src/compiler/utilities.ts | 12 +++++++++++ ...WithModuleNodeResolutionEmitAmd.errors.txt | 12 ----------- ...eWithModuleNodeResolutionEmitAmdOutFile.js | 20 +++++++++++++++++++ ...ModuleNodeResolutionEmitAmdOutFile.symbols | 12 +++++++++++ ...thModuleNodeResolutionEmitAmdOutFile.types | 16 +++++++++++++++ ...hModuleNodeResolutionEmitEs2015.errors.txt | 12 ----------- ...hModuleNodeResolutionEmitEsNext.errors.txt | 12 ----------- ...ithModuleNodeResolutionEmitNone.errors.txt | 4 ++-- ...hModuleNodeResolutionEmitSystem.errors.txt | 4 ++-- ...WithModuleNodeResolutionEmitUmd.errors.txt | 4 ++-- ...eWithModuleNodeResolutionEmitAmdOutFile.ts | 14 +++++++++++++ 16 files changed, 97 insertions(+), 51 deletions(-) delete mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmd.errors.txt create mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.js create mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.symbols create mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.types delete mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEs2015.errors.txt delete mode 100644 tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEsNext.errors.txt create mode 100644 tests/cases/compiler/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..6680c390a0a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2252,7 +2252,7 @@ namespace ts { else if (!compilerOptions.resolveJsonModule && fileExtensionIs(moduleReference, Extension.Json) && getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeJs && - getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS) { + hasJsonModuleEmitEnabled(compilerOptions)) { error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference); } else { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 9ba3c4e8cf1..de61586dcdd 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2892,7 +2892,7 @@ "category": "Error", "code": 5070 }, - "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'.": { + "Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'.": { "category": "Error", "code": 5071 }, diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 613fe7f5c84..8cb1d4f34a9 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1780,7 +1780,9 @@ namespace ts { function emitExpressionStatement(node: ExpressionStatement) { emitExpression(node.expression); - if (!isJsonSourceFile(currentSourceFile)) { + // Emit semicolon in non json files + // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation) + if (!isJsonSourceFile(currentSourceFile) || nodeIsSynthesized(node.expression)) { writeSemicolon(); } } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 2bbf17e6098..16825209e59 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2549,9 +2549,9 @@ namespace ts { if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) { createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule"); } - // Any emit other than common js is error - else if (getEmitModuleKind(options) !== ModuleKind.CommonJS) { - createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs, "resolveJsonModule", "module"); + // Any emit other than common js, amd, es2015 or esnext is error + else if (!hasJsonModuleEmitEnabled(options)) { + createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module"); } } diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 09bf1b75b9c..1b3a623c32d 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -53,7 +53,10 @@ namespace ts { * @param node The SourceFile node. */ function transformSourceFile(node: SourceFile) { - if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & TransformFlags.ContainsDynamicImport)) { + if (node.isDeclarationFile || + !(isEffectiveExternalModule(node, compilerOptions) || + node.transformFlags & TransformFlags.ContainsDynamicImport || + (isJsonSourceFile(node) && hasJsonModuleEmitEnabled(compilerOptions) && (compilerOptions.out || compilerOptions.outFile)))) { return node; } @@ -117,6 +120,7 @@ namespace ts { function transformAMDModule(node: SourceFile) { const define = createIdentifier("define"); const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions); + const jsonSourceFile = isJsonSourceFile(node) && node; // An AMD define function has the following shape: // @@ -158,7 +162,7 @@ namespace ts { // Add the dependency array argument: // // ["require", "exports", module1", "module2", ...] - createArrayLiteral([ + createArrayLiteral(jsonSourceFile ? emptyArray : [ createLiteral("require"), createLiteral("exports"), ...aliasedModuleNames, @@ -168,7 +172,9 @@ namespace ts { // Add the module body function argument: // // function (require, exports, module1, module2) ... - createFunctionExpression( + jsonSourceFile ? + jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : createObjectLiteral() : + createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index da13fcb4391..6b8115112e1 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7004,6 +7004,18 @@ namespace ts { return moduleResolution; } + export function hasJsonModuleEmitEnabled(options: CompilerOptions) { + switch (getEmitModuleKind(options)) { + case ModuleKind.CommonJS: + case ModuleKind.AMD: + case ModuleKind.ES2015: + case ModuleKind.ESNext: + return true; + default: + return false; + } + } + export function unreachableCodeIsError(options: CompilerOptions): boolean { return options.allowUnreachableCode === false; } diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmd.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmd.errors.txt deleted file mode 100644 index eab6745285b..00000000000 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmd.errors.txt +++ /dev/null @@ -1,12 +0,0 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. - - -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. -==== tests/cases/compiler/file1.ts (0 errors) ==== - import * as b from './b.json'; - -==== tests/cases/compiler/b.json (0 errors) ==== - { - "a": true, - "b": "hello" - } \ No newline at end of file diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.js b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.js new file mode 100644 index 00000000000..f6aa6d997be --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.js @@ -0,0 +1,20 @@ +//// [tests/cases/compiler/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.ts] //// + +//// [file1.ts] +import * as b from './b.json'; + +//// [b.json] +{ + "a": true, + "b": "hello" +} + +//// [out/output.js] +define("b", [], { + "a": true, + "b": "hello" +}); +define("file1", ["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; +}); diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.symbols b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.symbols new file mode 100644 index 00000000000..827f2e674e6 --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.symbols @@ -0,0 +1,12 @@ +=== tests/cases/compiler/file1.ts === +import * as b from './b.json'; +>b : Symbol(b, Decl(file1.ts, 0, 6)) + +=== tests/cases/compiler/b.json === +{ + "a": true, +>"a" : Symbol("a", Decl(b.json, 0, 1)) + + "b": "hello" +>"b" : Symbol("b", Decl(b.json, 1, 14)) +} diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.types b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.types new file mode 100644 index 00000000000..9e5cc29d342 --- /dev/null +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/file1.ts === +import * as b from './b.json'; +>b : { "a": boolean; "b": string; } + +=== tests/cases/compiler/b.json === +{ +>{ "a": true, "b": "hello"} : { "a": boolean; "b": string; } + + "a": true, +>"a" : boolean +>true : true + + "b": "hello" +>"b" : string +>"hello" : "hello" +} diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEs2015.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEs2015.errors.txt deleted file mode 100644 index eab6745285b..00000000000 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEs2015.errors.txt +++ /dev/null @@ -1,12 +0,0 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. - - -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. -==== tests/cases/compiler/file1.ts (0 errors) ==== - import * as b from './b.json'; - -==== tests/cases/compiler/b.json (0 errors) ==== - { - "a": true, - "b": "hello" - } \ No newline at end of file diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEsNext.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEsNext.errors.txt deleted file mode 100644 index b9c37651205..00000000000 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitEsNext.errors.txt +++ /dev/null @@ -1,12 +0,0 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. - - -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. -==== tests/cases/compiler/file1.ts (0 errors) ==== - import * as b from './b.json'; - -==== tests/cases/compiler/b.json (0 errors) ==== - { - "a": true, - "b": "hello" - } \ No newline at end of file diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitNone.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitNone.errors.txt index 8a40ac52e90..6772461f487 100644 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitNone.errors.txt +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitNone.errors.txt @@ -1,8 +1,8 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. tests/cases/compiler/file1.ts(1,1): error TS1148: Cannot use imports, exports, or module augmentations when '--module' is 'none'. -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. ==== tests/cases/compiler/file1.ts (1 errors) ==== import * as b from './b.json'; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitSystem.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitSystem.errors.txt index eab6745285b..8b570387ce7 100644 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitSystem.errors.txt +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitSystem.errors.txt @@ -1,7 +1,7 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. ==== tests/cases/compiler/file1.ts (0 errors) ==== import * as b from './b.json'; diff --git a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitUmd.errors.txt b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitUmd.errors.txt index eab6745285b..8b570387ce7 100644 --- a/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitUmd.errors.txt +++ b/tests/baselines/reference/requireOfJsonFileWithModuleNodeResolutionEmitUmd.errors.txt @@ -1,7 +1,7 @@ -error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. -!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs'. +!!! error TS5071: Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'. ==== tests/cases/compiler/file1.ts (0 errors) ==== import * as b from './b.json'; diff --git a/tests/cases/compiler/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.ts b/tests/cases/compiler/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.ts new file mode 100644 index 00000000000..6c73015d222 --- /dev/null +++ b/tests/cases/compiler/requireOfJsonFileWithModuleNodeResolutionEmitAmdOutFile.ts @@ -0,0 +1,14 @@ +// @module: amd +// @moduleResolution: node +// @outFile: out/output.js +// @fullEmitPaths: true +// @resolveJsonModule: true + +// @Filename: file1.ts +import * as b from './b.json'; + +// @Filename: b.json +{ + "a": true, + "b": "hello" +} \ No newline at end of file From f1a179a314fdcc4875a90e9f75ee4a18e7354e03 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 31 Aug 2018 15:24:53 -0700 Subject: [PATCH 035/146] Narrowing unknown by typeof object to object | null Fixes #26327 --- src/compiler/checker.ts | 3 +++ .../reference/narrowUnknownByTypeofObject.js | 14 ++++++++++++++ .../narrowUnknownByTypeofObject.symbols | 13 +++++++++++++ .../reference/narrowUnknownByTypeofObject.types | 16 ++++++++++++++++ .../compiler/narrowUnknownByTypeofObject.ts | 6 ++++++ 5 files changed, 52 insertions(+) create mode 100644 tests/baselines/reference/narrowUnknownByTypeofObject.js create mode 100644 tests/baselines/reference/narrowUnknownByTypeofObject.symbols create mode 100644 tests/baselines/reference/narrowUnknownByTypeofObject.types create mode 100644 tests/cases/compiler/narrowUnknownByTypeofObject.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..ac5733392e5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14925,6 +14925,9 @@ namespace ts { return type; } if (assumeTrue && !(type.flags & TypeFlags.Union)) { + if (type.flags & TypeFlags.Unknown && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } // We narrow a non-union type to an exact primitive type if the non-union type // is a supertype of that primitive type. For example, type 'any' can be narrowed // to one of the primitive types. diff --git a/tests/baselines/reference/narrowUnknownByTypeofObject.js b/tests/baselines/reference/narrowUnknownByTypeofObject.js new file mode 100644 index 00000000000..076d91e0df8 --- /dev/null +++ b/tests/baselines/reference/narrowUnknownByTypeofObject.js @@ -0,0 +1,14 @@ +//// [narrowUnknownByTypeofObject.ts] +function foo(x: unknown) { + if (typeof x === "object") { + x + } +} + + +//// [narrowUnknownByTypeofObject.js] +function foo(x) { + if (typeof x === "object") { + x; + } +} diff --git a/tests/baselines/reference/narrowUnknownByTypeofObject.symbols b/tests/baselines/reference/narrowUnknownByTypeofObject.symbols new file mode 100644 index 00000000000..ee3ec77ec04 --- /dev/null +++ b/tests/baselines/reference/narrowUnknownByTypeofObject.symbols @@ -0,0 +1,13 @@ +=== tests/cases/compiler/narrowUnknownByTypeofObject.ts === +function foo(x: unknown) { +>foo : Symbol(foo, Decl(narrowUnknownByTypeofObject.ts, 0, 0)) +>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13)) + + if (typeof x === "object") { +>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13)) + + x +>x : Symbol(x, Decl(narrowUnknownByTypeofObject.ts, 0, 13)) + } +} + diff --git a/tests/baselines/reference/narrowUnknownByTypeofObject.types b/tests/baselines/reference/narrowUnknownByTypeofObject.types new file mode 100644 index 00000000000..98225861d1e --- /dev/null +++ b/tests/baselines/reference/narrowUnknownByTypeofObject.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/narrowUnknownByTypeofObject.ts === +function foo(x: unknown) { +>foo : (x: unknown) => void +>x : unknown + + if (typeof x === "object") { +>typeof x === "object" : boolean +>typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>x : unknown +>"object" : "object" + + x +>x : object | null + } +} + diff --git a/tests/cases/compiler/narrowUnknownByTypeofObject.ts b/tests/cases/compiler/narrowUnknownByTypeofObject.ts new file mode 100644 index 00000000000..36e1c18f4f6 --- /dev/null +++ b/tests/cases/compiler/narrowUnknownByTypeofObject.ts @@ -0,0 +1,6 @@ +// @strictNullChecks: true +function foo(x: unknown) { + if (typeof x === "object") { + x + } +} From f2d26fd0bba373bf4a8d2cf2dd8cbfb9abf310af Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Sat, 1 Sep 2018 19:48:47 -0400 Subject: [PATCH 036/146] Argument arity error should only consider signatures with correct type argument arity. Fixes #26835. --- src/compiler/checker.ts | 19 +++++++++++-------- .../reference/functionCall18.errors.txt | 11 +++++++++++ tests/baselines/reference/functionCall18.js | 9 +++++++++ .../reference/functionCall18.symbols | 17 +++++++++++++++++ .../baselines/reference/functionCall18.types | 16 ++++++++++++++++ tests/cases/compiler/functionCall18.ts | 4 ++++ 6 files changed, 68 insertions(+), 8 deletions(-) create mode 100644 tests/baselines/reference/functionCall18.errors.txt create mode 100644 tests/baselines/reference/functionCall18.js create mode 100644 tests/baselines/reference/functionCall18.symbols create mode 100644 tests/baselines/reference/functionCall18.types create mode 100644 tests/cases/compiler/functionCall18.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..e52f89e9a06 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19174,14 +19174,17 @@ namespace ts { else if (candidateForTypeArgumentError) { checkTypeArguments(candidateForTypeArgumentError, (node as CallExpression | TaggedTemplateExpression).typeArguments!, /*reportErrors*/ true, fallbackError); } - else if (typeArguments && every(signatures, sig => typeArguments!.length < getMinTypeArgumentCount(sig.typeParameters) || typeArguments!.length > length(sig.typeParameters))) { - diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments)); - } - else if (!isDecorator) { - diagnostics.add(getArgumentArityError(node, signatures, args)); - } - else if (fallbackError) { - diagnostics.add(createDiagnosticForNode(node, fallbackError)); + else { + const signaturesWithCorrectTypeArgumentArity = filter(signatures, s => hasCorrectTypeArgumentArity(s, typeArguments)); + if (signaturesWithCorrectTypeArgumentArity.length === 0) { + diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments!)); + } + else if (!isDecorator) { + diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args)); + } + else if (fallbackError) { + diagnostics.add(createDiagnosticForNode(node, fallbackError)); + } } return produceDiagnostics || !args ? resolveErrorCall(node) : getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray); diff --git a/tests/baselines/reference/functionCall18.errors.txt b/tests/baselines/reference/functionCall18.errors.txt new file mode 100644 index 00000000000..99d7415425c --- /dev/null +++ b/tests/baselines/reference/functionCall18.errors.txt @@ -0,0 +1,11 @@ +tests/cases/compiler/functionCall18.ts(4,1): error TS2554: Expected 2 arguments, but got 1. + + +==== tests/cases/compiler/functionCall18.ts (1 errors) ==== + // Repro from #26835 + declare function foo(a: T, b: T); + declare function foo(a: {}); + foo("hello"); + ~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 2 arguments, but got 1. + \ No newline at end of file diff --git a/tests/baselines/reference/functionCall18.js b/tests/baselines/reference/functionCall18.js new file mode 100644 index 00000000000..6e059205c62 --- /dev/null +++ b/tests/baselines/reference/functionCall18.js @@ -0,0 +1,9 @@ +//// [functionCall18.ts] +// Repro from #26835 +declare function foo(a: T, b: T); +declare function foo(a: {}); +foo("hello"); + + +//// [functionCall18.js] +foo("hello"); diff --git a/tests/baselines/reference/functionCall18.symbols b/tests/baselines/reference/functionCall18.symbols new file mode 100644 index 00000000000..ebf635d91e9 --- /dev/null +++ b/tests/baselines/reference/functionCall18.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/functionCall18.ts === +// Repro from #26835 +declare function foo(a: T, b: T); +>foo : Symbol(foo, Decl(functionCall18.ts, 0, 0), Decl(functionCall18.ts, 1, 36)) +>T : Symbol(T, Decl(functionCall18.ts, 1, 21)) +>a : Symbol(a, Decl(functionCall18.ts, 1, 24)) +>T : Symbol(T, Decl(functionCall18.ts, 1, 21)) +>b : Symbol(b, Decl(functionCall18.ts, 1, 29)) +>T : Symbol(T, Decl(functionCall18.ts, 1, 21)) + +declare function foo(a: {}); +>foo : Symbol(foo, Decl(functionCall18.ts, 0, 0), Decl(functionCall18.ts, 1, 36)) +>a : Symbol(a, Decl(functionCall18.ts, 2, 21)) + +foo("hello"); +>foo : Symbol(foo, Decl(functionCall18.ts, 0, 0), Decl(functionCall18.ts, 1, 36)) + diff --git a/tests/baselines/reference/functionCall18.types b/tests/baselines/reference/functionCall18.types new file mode 100644 index 00000000000..90fa33f0617 --- /dev/null +++ b/tests/baselines/reference/functionCall18.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/functionCall18.ts === +// Repro from #26835 +declare function foo(a: T, b: T); +>foo : { (a: T, b: T): any; (a: {}): any; } +>a : T +>b : T + +declare function foo(a: {}); +>foo : { (a: T, b: T): any; (a: {}): any; } +>a : {} + +foo("hello"); +>foo("hello") : any +>foo : { (a: T, b: T): any; (a: {}): any; } +>"hello" : "hello" + diff --git a/tests/cases/compiler/functionCall18.ts b/tests/cases/compiler/functionCall18.ts new file mode 100644 index 00000000000..848580db729 --- /dev/null +++ b/tests/cases/compiler/functionCall18.ts @@ -0,0 +1,4 @@ +// Repro from #26835 +declare function foo(a: T, b: T); +declare function foo(a: {}); +foo("hello"); From 059fcc9aa95a75019230b8ec30d2ea1bb8447396 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 2 Sep 2018 08:58:00 -0700 Subject: [PATCH 037/146] Defer reduction of identical function types in unions and intersections --- src/compiler/checker.ts | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..3b736093e78 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8691,10 +8691,7 @@ namespace ts { const len = typeSet.length; const index = len && type.id > typeSet[len - 1].id ? ~len : binarySearch(typeSet, type, getTypeId, compareValues); if (index < 0) { - if (!(flags & TypeFlags.Object && (type).objectFlags & ObjectFlags.Anonymous && - type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && containsIdenticalType(typeSet, type))) { - typeSet.splice(~index, 0, type); - } + typeSet.splice(~index, 0, type); } } } @@ -8710,15 +8707,6 @@ namespace ts { return includes; } - function containsIdenticalType(types: ReadonlyArray, type: Type) { - for (const t of types) { - if (isTypeIdenticalTo(t, type)) { - return true; - } - } - return false; - } - function isSubtypeOfAny(source: Type, targets: ReadonlyArray): boolean { for (const target of targets) { if (source !== target && isTypeSubtypeOf(source, target) && ( @@ -8899,10 +8887,7 @@ namespace ts { if (flags & TypeFlags.AnyOrUnknown) { if (type === wildcardType) includes |= TypeFlags.Wildcard; } - else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !contains(typeSet, type) && - !(flags & TypeFlags.Object && (type).objectFlags & ObjectFlags.Anonymous && - type.symbol && type.symbol.flags & (SymbolFlags.Function | SymbolFlags.Method) && - containsIdenticalType(typeSet, type))) { + else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !contains(typeSet, type)) { typeSet.push(type); } } From d9e0d6b07f91c19621db4317b33cc1de5fb190b5 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 2 Sep 2018 08:58:32 -0700 Subject: [PATCH 038/146] Accept new baselines --- .../checkJsxChildrenProperty4.errors.txt | 12 +++++------ .../overrideBaseIntersectionMethod.types | 4 ++-- .../typeParameterExtendingUnion1.types | 4 ++-- .../typeParameterExtendingUnion2.types | 8 ++++---- .../reference/unionTypeMembers.types | 20 +++++++++---------- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt index 4851bc3b466..8e7a3adb518 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty4.errors.txt @@ -1,8 +1,8 @@ tests/cases/conformance/jsx/file.tsx(24,28): error TS2551: Property 'NAme' does not exist on type 'IUser'. Did you mean 'Name'? -tests/cases/conformance/jsx/file.tsx(32,10): error TS2322: Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IFetchUserProps'. +tests/cases/conformance/jsx/file.tsx(32,10): error TS2322: Type '{ children: (((user: IUser) => Element) | ((user: IUser) => Element))[]; }' is not assignable to type 'IFetchUserProps'. Types of property 'children' are incompatible. - Type '((user: IUser) => Element)[]' is not assignable to type '(user: IUser) => Element'. - Type '((user: IUser) => Element)[]' provides no match for the signature '(user: IUser): Element'. + Type '(((user: IUser) => Element) | ((user: IUser) => Element))[]' is not assignable to type '(user: IUser) => Element'. + Type '(((user: IUser) => Element) | ((user: IUser) => Element))[]' provides no match for the signature '(user: IUser): Element'. ==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== @@ -42,10 +42,10 @@ tests/cases/conformance/jsx/file.tsx(32,10): error TS2322: Type '{ children: ((u return ( ~~~~~~~~~ -!!! error TS2322: Type '{ children: ((user: IUser) => Element)[]; }' is not assignable to type 'IFetchUserProps'. +!!! error TS2322: Type '{ children: (((user: IUser) => Element) | ((user: IUser) => Element))[]; }' is not assignable to type 'IFetchUserProps'. !!! error TS2322: Types of property 'children' are incompatible. -!!! error TS2322: Type '((user: IUser) => Element)[]' is not assignable to type '(user: IUser) => Element'. -!!! error TS2322: Type '((user: IUser) => Element)[]' provides no match for the signature '(user: IUser): Element'. +!!! error TS2322: Type '(((user: IUser) => Element) | ((user: IUser) => Element))[]' is not assignable to type '(user: IUser) => Element'. +!!! error TS2322: Type '(((user: IUser) => Element) | ((user: IUser) => Element))[]' provides no match for the signature '(user: IUser): Element'. diff --git a/tests/baselines/reference/overrideBaseIntersectionMethod.types b/tests/baselines/reference/overrideBaseIntersectionMethod.types index 57d06fe648f..3ca80a06a1a 100644 --- a/tests/baselines/reference/overrideBaseIntersectionMethod.types +++ b/tests/baselines/reference/overrideBaseIntersectionMethod.types @@ -78,9 +78,9 @@ class Foo extends WithLocation(Point) { return super.getLocation() >super.getLocation() : [number, number] ->super.getLocation : () => [number, number] +>super.getLocation : (() => [number, number]) & (() => [number, number]) >super : WithLocation.(Anonymous class) & Point ->getLocation : () => [number, number] +>getLocation : (() => [number, number]) & (() => [number, number]) } whereAmI() { >whereAmI : () => [number, number] diff --git a/tests/baselines/reference/typeParameterExtendingUnion1.types b/tests/baselines/reference/typeParameterExtendingUnion1.types index 85c2096823b..e3eb4c14ca0 100644 --- a/tests/baselines/reference/typeParameterExtendingUnion1.types +++ b/tests/baselines/reference/typeParameterExtendingUnion1.types @@ -30,9 +30,9 @@ function f(a: T) { a.run(); >a.run() : void ->a.run : () => void +>a.run : (() => void) | (() => void) >a : T ->run : () => void +>run : (() => void) | (() => void) run(a); >run(a) : void diff --git a/tests/baselines/reference/typeParameterExtendingUnion2.types b/tests/baselines/reference/typeParameterExtendingUnion2.types index c19076ddd68..074ac3b3fff 100644 --- a/tests/baselines/reference/typeParameterExtendingUnion2.types +++ b/tests/baselines/reference/typeParameterExtendingUnion2.types @@ -19,9 +19,9 @@ function run(a: Cat | Dog) { a.run(); >a.run() : void ->a.run : () => void +>a.run : (() => void) | (() => void) >a : Cat | Dog ->run : () => void +>run : (() => void) | (() => void) } function f(a: T) { @@ -30,9 +30,9 @@ function f(a: T) { a.run(); >a.run() : void ->a.run : () => void +>a.run : (() => void) | (() => void) >a : T ->run : () => void +>run : (() => void) | (() => void) run(a); >run(a) : void diff --git a/tests/baselines/reference/unionTypeMembers.types b/tests/baselines/reference/unionTypeMembers.types index 5b19ab5540c..e26d00c45f9 100644 --- a/tests/baselines/reference/unionTypeMembers.types +++ b/tests/baselines/reference/unionTypeMembers.types @@ -95,9 +95,9 @@ str = x.commonMethodType(str); // (a: string) => string so result should be stri >str = x.commonMethodType(str) : string >str : string >x.commonMethodType(str) : string ->x.commonMethodType : (a: string) => string +>x.commonMethodType : ((a: string) => string) | ((a: string) => string) >x : I1 | I2 ->commonMethodType : (a: string) => string +>commonMethodType : ((a: string) => string) | ((a: string) => string) >str : string strOrNum = x.commonPropertyDifferenType; @@ -133,36 +133,36 @@ num = x.commonMethodWithTypeParameter(num); >num = x.commonMethodWithTypeParameter(num) : number >num : number >x.commonMethodWithTypeParameter(num) : number ->x.commonMethodWithTypeParameter : (a: number) => number +>x.commonMethodWithTypeParameter : ((a: number) => number) | ((a: number) => number) >x : I1 | I2 ->commonMethodWithTypeParameter : (a: number) => number +>commonMethodWithTypeParameter : ((a: number) => number) | ((a: number) => number) >num : number num = x.commonMethodWithOwnTypeParameter(num); >num = x.commonMethodWithOwnTypeParameter(num) : number >num : number >x.commonMethodWithOwnTypeParameter(num) : number ->x.commonMethodWithOwnTypeParameter : (a: U) => U +>x.commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >x : I1 | I2 ->commonMethodWithOwnTypeParameter : (a: U) => U +>commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >num : number str = x.commonMethodWithOwnTypeParameter(str); >str = x.commonMethodWithOwnTypeParameter(str) : string >str : string >x.commonMethodWithOwnTypeParameter(str) : string ->x.commonMethodWithOwnTypeParameter : (a: U) => U +>x.commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >x : I1 | I2 ->commonMethodWithOwnTypeParameter : (a: U) => U +>commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >str : string strOrNum = x.commonMethodWithOwnTypeParameter(strOrNum); >strOrNum = x.commonMethodWithOwnTypeParameter(strOrNum) : string | number >strOrNum : string | number >x.commonMethodWithOwnTypeParameter(strOrNum) : string | number ->x.commonMethodWithOwnTypeParameter : (a: U) => U +>x.commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >x : I1 | I2 ->commonMethodWithOwnTypeParameter : (a: U) => U +>commonMethodWithOwnTypeParameter : ((a: U) => U) | ((a: U) => U) >strOrNum : string | number x.propertyOnlyInI1; // error From c87ca2f1ab8caab05c6085c0135bdcf7a61ac042 Mon Sep 17 00:00:00 2001 From: christian Date: Mon, 3 Sep 2018 22:57:26 -0400 Subject: [PATCH 039/146] Fix diagnostic reporting for empty files in tsconfig --- src/compiler/commandLineParser.ts | 16 ++++--- src/compiler/tsbuild.ts | 16 +++++-- src/testRunner/unittests/tsbuild.ts | 42 +++++++++++++++++++ src/testRunner/unittests/tsconfigParsing.ts | 39 +++++++++++++++++ tests/projects/empty-files/core/index.ts | 1 + tests/projects/empty-files/core/tsconfig.json | 7 ++++ .../empty-files/no-references/tsconfig.json | 9 ++++ .../empty-files/with-references/tsconfig.json | 11 +++++ 8 files changed, 132 insertions(+), 9 deletions(-) create mode 100644 tests/projects/empty-files/core/index.ts create mode 100644 tests/projects/empty-files/core/tsconfig.json create mode 100644 tests/projects/empty-files/no-references/tsconfig.json create mode 100644 tests/projects/empty-files/with-references/tsconfig.json diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index e4c4edcb4db..5d87525073f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1843,7 +1843,9 @@ namespace ts { if (hasProperty(raw, "files") && !isNullOrUndefined(raw.files)) { if (isArray(raw.files)) { filesSpecs = >raw.files; - if (filesSpecs.length === 0) { + const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); + const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; + if (filesSpecs.length === 0 && hasZeroOrNoReferences) { createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); } } @@ -2067,11 +2069,6 @@ namespace ts { createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0) ); return; - case "files": - if ((>value).length === 0) { - errors.push(createDiagnosticForNodeInSourceFile(sourceFile, valueNode, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); - } - return; } }, onSetUnknownOptionKeyValueInRoot(key: string, keyNode: PropertyName, _value: CompilerOptionsValue, _valueNode: Expression) { @@ -2081,6 +2078,13 @@ namespace ts { } }; const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); + const hasZeroFiles = json && json.files && json.files.length === 0; + const hasZeroOrNoReferences = !(json && json.references) || json.references.length === 0; + + if (hasZeroFiles && hasZeroOrNoReferences) { + errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, sourceFile.fileName)); + } + if (!typeAcquisition) { if (typingOptionstypeAcquisition) { typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ? diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 4ddda98a41f..418185b4c16 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -946,7 +946,6 @@ namespace ts { context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } - if (configFile.fileNames.length === 0) { // Nothing to build - must be a solution file, basically return BuildResultFlags.None; @@ -956,7 +955,8 @@ namespace ts { projectReferences: configFile.projectReferences, host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors, }; const program = createProgram(programOptions); @@ -1149,7 +1149,6 @@ namespace ts { const queue = graph.buildQueue; reportBuildQueue(graph); - let anyFailed = false; for (const next of queue) { const proj = configFileCache.parseConfigFile(next); @@ -1157,11 +1156,15 @@ namespace ts { anyFailed = true; break; } + + // report errors early when using continue or break statements + const errors = proj.errors; const status = getUpToDateStatus(proj); verboseReportProjectStatus(next, status); const projName = proj.options.configFilePath!; if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + reportErrors(errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1171,17 +1174,20 @@ namespace ts { } if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + reportErrors(errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { + reportErrors(errors); if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { + reportErrors(errors); // Do nothing continue; } @@ -1193,6 +1199,10 @@ namespace ts { return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } + function reportErrors(errors: Diagnostic[]) { + errors.forEach((err) => host.reportDiagnostic(err)); + } + /** * Report the build ordering inferred from the current project graph if we're in verbose mode */ diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index ea99ee92457..6d6f95ce19c 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -292,6 +292,48 @@ namespace ts { }); } + export namespace EmptyFiles { + const projFs = loadProjectFromDisk("tests/projects/empty-files"); + + const allExpectedOutputs = [ + "/src/core/index.js", + "/src/core/index.d.ts", + "/src/core/index.d.ts.map", + ]; + + describe("tsbuild - empty files option in tsconfig", () => { + it("has empty files diagnostic when files is empty and no references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(Diagnostics.The_files_list_in_config_file_0_is_empty); + + // Check for outputs to not be written. + for (const output of allExpectedOutputs) { + assert(!fs.existsSync(output), `Expect file ${output} to not exist`); + } + }); + + it("does not have empty files diagnostic when files is empty and references are provided", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false }); + + host.clearDiagnostics(); + builder.buildAllProjects(); + host.assertDiagnosticMessages(/*empty*/); + + // Check for outputs to be written. + for (const output of allExpectedOutputs) { + assert(fs.existsSync(output), `Expect file ${output} to exist`); + } + }); + }); + } + describe("tsbuild - graph-ordering", () => { let host: fakes.SolutionBuilderHost | undefined; const deps: [string, string][] = [ diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/tsconfigParsing.ts index 6ef5697046f..c2e8f0eb10d 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/tsconfigParsing.ts @@ -61,6 +61,19 @@ namespace ts { } } + function assertParseFileDiagnosticsExclusion(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedExcludedDiagnosticCode: number) { + { + const parsed = getParsedCommandJson(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + { + const parsed = getParsedCommandJsonNode(jsonText, configFileName, basePath, allFileList); + assert.isTrue(parsed.errors.length >= 0); + assert.isTrue(parsed.errors.findIndex(e => e.code === expectedExcludedDiagnosticCode) === -1, `Expected error code ${expectedExcludedDiagnosticCode} to not be in ${JSON.stringify(parsed.errors)}`); + } + } + it("returns empty config for file with only whitespaces", () => { assertParseResult("", { config : {} }); assertParseResult(" ", { config : {} }); @@ -274,6 +287,32 @@ namespace ts { "files": [] }`; assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code, + /*noLocation*/ true); + }); + + it("generates errors for empty files list when no references are provided", () => { + const content = `{ + "files": [], + "references": [] + }`; + assertParseFileDiagnostics(content, + "/apath/tsconfig.json", + "tests/cases/unittests", + ["/apath/a.ts"], + Diagnostics.The_files_list_in_config_file_0_is_empty.code, + /*noLocation*/ true); + }); + + it("does not generate errors for empty files list when one or more references are provided", () => { + const content = `{ + "files": [], + "references": [{ "path": "/apath" }] + }`; + assertParseFileDiagnosticsExclusion(content, "/apath/tsconfig.json", "tests/cases/unittests", ["/apath/a.ts"], diff --git a/tests/projects/empty-files/core/index.ts b/tests/projects/empty-files/core/index.ts new file mode 100644 index 00000000000..3da69271e97 --- /dev/null +++ b/tests/projects/empty-files/core/index.ts @@ -0,0 +1 @@ +export function multiply(a: number, b: number) { return a * b; } diff --git a/tests/projects/empty-files/core/tsconfig.json b/tests/projects/empty-files/core/tsconfig.json new file mode 100644 index 00000000000..24b64bc7b2c --- /dev/null +++ b/tests/projects/empty-files/core/tsconfig.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "composite": true, + "declaration": true, + "declarationMap": true + } +} \ No newline at end of file diff --git a/tests/projects/empty-files/no-references/tsconfig.json b/tests/projects/empty-files/no-references/tsconfig.json new file mode 100644 index 00000000000..9b02f3654e3 --- /dev/null +++ b/tests/projects/empty-files/no-references/tsconfig.json @@ -0,0 +1,9 @@ +{ + "references": [], + "files": [], + "compilerOptions": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/tests/projects/empty-files/with-references/tsconfig.json b/tests/projects/empty-files/with-references/tsconfig.json new file mode 100644 index 00000000000..bf5e2690064 --- /dev/null +++ b/tests/projects/empty-files/with-references/tsconfig.json @@ -0,0 +1,11 @@ +{ + "references": [ + { "path": "../core" }, + ], + "files": [], + "compilerOptions": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file From 959dbbba2821c63bcb1de9d4422a80aeab6b5156 Mon Sep 17 00:00:00 2001 From: christian Date: Mon, 3 Sep 2018 23:16:53 -0400 Subject: [PATCH 040/146] Add newline to bottom of tsconfig files --- tests/projects/empty-files/core/tsconfig.json | 2 +- tests/projects/empty-files/no-references/tsconfig.json | 2 +- tests/projects/empty-files/with-references/tsconfig.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/projects/empty-files/core/tsconfig.json b/tests/projects/empty-files/core/tsconfig.json index 24b64bc7b2c..0e8205977dd 100644 --- a/tests/projects/empty-files/core/tsconfig.json +++ b/tests/projects/empty-files/core/tsconfig.json @@ -4,4 +4,4 @@ "declaration": true, "declarationMap": true } -} \ No newline at end of file +} diff --git a/tests/projects/empty-files/no-references/tsconfig.json b/tests/projects/empty-files/no-references/tsconfig.json index 9b02f3654e3..c6b8f1a43d7 100644 --- a/tests/projects/empty-files/no-references/tsconfig.json +++ b/tests/projects/empty-files/no-references/tsconfig.json @@ -6,4 +6,4 @@ "declaration": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} diff --git a/tests/projects/empty-files/with-references/tsconfig.json b/tests/projects/empty-files/with-references/tsconfig.json index bf5e2690064..3a55cad1b1c 100644 --- a/tests/projects/empty-files/with-references/tsconfig.json +++ b/tests/projects/empty-files/with-references/tsconfig.json @@ -8,4 +8,4 @@ "declaration": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} From 239a7b9a4f2ca6bc766a4ee0fc0614c3a7ce0b15 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 4 Sep 2018 13:35:57 +0200 Subject: [PATCH 041/146] better condition for file include exhaustiveness check As `files` always contains declaration files of external libraries, lib files and declaration files from typeRoots, the previous condition evaluated to false for probably all projects out there. This changes the condition to compare array length after filtering out all declaration files. That avoids unnecessary work of path normalization in the common case where everything is ok. --- src/compiler/program.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 2bbf17e6098..c6473f2cb99 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2432,12 +2432,14 @@ namespace ts { } // List of collected files is complete; validate exhautiveness if this is a project with a file list - if (options.composite && rootNames.length < files.length) { - const normalizedRootNames = rootNames.map(r => normalizePath(r).toLowerCase()); - const sourceFiles = files.filter(f => !f.isDeclarationFile).map(f => normalizePath(f.path).toLowerCase()); - for (const file of sourceFiles) { - if (normalizedRootNames.every(r => r !== file)) { - programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + if (options.composite) { + const sourceFiles = files.filter(f => !f.isDeclarationFile); + if (rootNames.length < sourceFiles.length) { + const normalizedRootNames = rootNames.map(r => normalizePath(r).toLowerCase()); + for (const file of sourceFiles.map(f => normalizePath(f.path).toLowerCase())) { + if (normalizedRootNames.indexOf(file) === -1) { + programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern, file)); + } } } } From 3d812ef93aece7fd81e0d4ef2b0a961647840ed2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 4 Sep 2018 11:07:50 -0700 Subject: [PATCH 042/146] Added test. --- tests/cases/compiler/errorsWithCallablesInUnions01.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 tests/cases/compiler/errorsWithCallablesInUnions01.ts diff --git a/tests/cases/compiler/errorsWithCallablesInUnions01.ts b/tests/cases/compiler/errorsWithCallablesInUnions01.ts new file mode 100644 index 00000000000..2cb6a3ebd35 --- /dev/null +++ b/tests/cases/compiler/errorsWithCallablesInUnions01.ts @@ -0,0 +1,10 @@ +interface IDirectiveLinkFn { + (scope: TScope): void; +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; +} + +export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} From 289ae3cca66b79e39a3f60f3bf029462c350fe39 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 4 Sep 2018 15:47:04 -0700 Subject: [PATCH 043/146] Accepted baseleines. --- .../errorsWithCallablesInUnions01.errors.txt | 19 ++++++++++++ .../errorsWithCallablesInUnions01.js | 17 ++++++++++ .../errorsWithCallablesInUnions01.symbols | 31 +++++++++++++++++++ .../errorsWithCallablesInUnions01.types | 19 ++++++++++++ 4 files changed, 86 insertions(+) create mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt create mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.js create mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.symbols create mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.types diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt b/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt new file mode 100644 index 00000000000..bf117e0c8b3 --- /dev/null +++ b/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/errorsWithCallablesInUnions01.ts(10,12): error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. + Type '(x: string) => void' has no properties in common with type 'IDirectivePrePost'. + + +==== tests/cases/compiler/errorsWithCallablesInUnions01.ts (1 errors) ==== + interface IDirectiveLinkFn { + (scope: TScope): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} + ~~~~ +!!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. +!!! error TS2322: Type '(x: string) => void' has no properties in common with type 'IDirectivePrePost'. + \ No newline at end of file diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.js b/tests/baselines/reference/errorsWithCallablesInUnions01.js new file mode 100644 index 00000000000..f9ea8041b16 --- /dev/null +++ b/tests/baselines/reference/errorsWithCallablesInUnions01.js @@ -0,0 +1,17 @@ +//// [errorsWithCallablesInUnions01.ts] +interface IDirectiveLinkFn { + (scope: TScope): void; +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; +} + +export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} + + +//// [errorsWithCallablesInUnions01.js] +"use strict"; +exports.__esModule = true; +exports.blah = function (x) { }; diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.symbols b/tests/baselines/reference/errorsWithCallablesInUnions01.symbols new file mode 100644 index 00000000000..40b48dc2458 --- /dev/null +++ b/tests/baselines/reference/errorsWithCallablesInUnions01.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/errorsWithCallablesInUnions01.ts === +interface IDirectiveLinkFn { +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) +>TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 0, 27)) + + (scope: TScope): void; +>scope : Symbol(scope, Decl(errorsWithCallablesInUnions01.ts, 1, 5)) +>TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 0, 27)) +} + +interface IDirectivePrePost { +>IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithCallablesInUnions01.ts, 2, 1)) +>TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) + + pre?: IDirectiveLinkFn; +>pre : Symbol(IDirectivePrePost.pre, Decl(errorsWithCallablesInUnions01.ts, 4, 37)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) +>TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) + + post?: IDirectiveLinkFn; +>post : Symbol(IDirectivePrePost.post, Decl(errorsWithCallablesInUnions01.ts, 5, 35)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) +>TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) +} + +export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} +>blah : Symbol(blah, Decl(errorsWithCallablesInUnions01.ts, 9, 10)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) +>IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithCallablesInUnions01.ts, 2, 1)) +>x : Symbol(x, Decl(errorsWithCallablesInUnions01.ts, 9, 73)) + diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.types b/tests/baselines/reference/errorsWithCallablesInUnions01.types new file mode 100644 index 00000000000..492d870b6e4 --- /dev/null +++ b/tests/baselines/reference/errorsWithCallablesInUnions01.types @@ -0,0 +1,19 @@ +=== tests/cases/compiler/errorsWithCallablesInUnions01.ts === +interface IDirectiveLinkFn { + (scope: TScope): void; +>scope : TScope +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; +>pre : IDirectiveLinkFn + + post?: IDirectiveLinkFn; +>post : IDirectiveLinkFn +} + +export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} +>blah : IDirectiveLinkFn | IDirectivePrePost +>(x: string) => {} : (x: string) => void +>x : string + From c5c594f1e7b2e18b73c3f4fbc7733d1898672511 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 4 Sep 2018 19:25:46 -0700 Subject: [PATCH 044/146] Try finding the first type with a call/construct signature when relating to unions. --- src/compiler/checker.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index da1af15dfa4..7d06f4432f7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11395,7 +11395,8 @@ namespace ts { const bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || - findBestTypeForObjectLiteral(source, target); + findBestTypeForObjectLiteral(source, target) || + findBestTypeForInvokable(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } @@ -11426,6 +11427,15 @@ namespace ts { } } + function findBestTypeForInvokable(source: Type, unionTarget: UnionOrIntersectionType) { + let signatureKind = SignatureKind.Call; + const hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 || + (signatureKind = SignatureKind.Construct, getSignaturesOfType(source, signatureKind).length > 0); + if (hasSignatures) { + return find(unionTarget.types, t => getSignaturesOfType(t, signatureKind).length > 0); + } + } + // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source: Type, target: UnionOrIntersectionType) { let match: Type | undefined; From cd399fb49bf25c0c12a9734aedd5babb759829f4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 4 Sep 2018 19:26:00 -0700 Subject: [PATCH 045/146] Accepted baselines. --- ...ntextualTypeWithUnionTypeObjectLiteral.errors.txt | 12 ++++++------ .../errorsWithCallablesInUnions01.errors.txt | 8 ++++++-- .../functionExpressionContextualTyping2.errors.txt | 8 ++++---- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/tests/baselines/reference/contextualTypeWithUnionTypeObjectLiteral.errors.txt b/tests/baselines/reference/contextualTypeWithUnionTypeObjectLiteral.errors.txt index e4ffa209e6f..fb44cb57da7 100644 --- a/tests/baselines/reference/contextualTypeWithUnionTypeObjectLiteral.errors.txt +++ b/tests/baselines/reference/contextualTypeWithUnionTypeObjectLiteral.errors.txt @@ -22,9 +22,9 @@ tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts( Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts(58,5): error TS2322: Type '(a: string, b: number) => string | number' is not assignable to type '((a: string, b: number) => string) | ((a: string, b: number) => number)'. - Type '(a: string, b: number) => string | number' is not assignable to type '(a: string, b: number) => number'. - Type 'string | number' is not assignable to type 'number'. - Type 'string' is not assignable to type 'number'. + Type '(a: string, b: number) => string | number' is not assignable to type '(a: string, b: number) => string'. + Type 'string | number' is not assignable to type 'string'. + Type 'number' is not assignable to type 'string'. ==== tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts (6 errors) ==== @@ -116,8 +116,8 @@ tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts( commonMethodDifferentReturnType: (a, b) => strOrNumber, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '(a: string, b: number) => string | number' is not assignable to type '((a: string, b: number) => string) | ((a: string, b: number) => number)'. -!!! error TS2322: Type '(a: string, b: number) => string | number' is not assignable to type '(a: string, b: number) => number'. -!!! error TS2322: Type 'string | number' is not assignable to type 'number'. -!!! error TS2322: Type 'string' is not assignable to type 'number'. +!!! error TS2322: Type '(a: string, b: number) => string | number' is not assignable to type '(a: string, b: number) => string'. +!!! error TS2322: Type 'string | number' is not assignable to type 'string'. +!!! error TS2322: Type 'number' is not assignable to type 'string'. !!! related TS6500 tests/cases/conformance/types/union/contextualTypeWithUnionTypeObjectLiteral.ts:35:5: The expected type comes from property 'commonMethodDifferentReturnType' which is declared here on type 'I11 | I21' }; \ No newline at end of file diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt b/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt index bf117e0c8b3..4881c4f7ff1 100644 --- a/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt +++ b/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt @@ -1,5 +1,7 @@ tests/cases/compiler/errorsWithCallablesInUnions01.ts(10,12): error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. - Type '(x: string) => void' has no properties in common with type 'IDirectivePrePost'. + Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. + Types of parameters 'x' and 'scope' are incompatible. + Type 'number' is not assignable to type 'string'. ==== tests/cases/compiler/errorsWithCallablesInUnions01.ts (1 errors) ==== @@ -15,5 +17,7 @@ tests/cases/compiler/errorsWithCallablesInUnions01.ts(10,12): error TS2322: Type export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} ~~~~ !!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. -!!! error TS2322: Type '(x: string) => void' has no properties in common with type 'IDirectivePrePost'. +!!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. +!!! error TS2322: Types of parameters 'x' and 'scope' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/functionExpressionContextualTyping2.errors.txt b/tests/baselines/reference/functionExpressionContextualTyping2.errors.txt index 6a3a7998f09..d50e0c4b6d6 100644 --- a/tests/baselines/reference/functionExpressionContextualTyping2.errors.txt +++ b/tests/baselines/reference/functionExpressionContextualTyping2.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.ts(11,1): error TS2322: Type '(foo: number, bar: string) => boolean' is not assignable to type '((n: number, s: string) => number) | ((n: number, s: string) => string)'. - Type '(foo: number, bar: string) => boolean' is not assignable to type '(n: number, s: string) => string'. - Type 'boolean' is not assignable to type 'string'. + Type '(foo: number, bar: string) => boolean' is not assignable to type '(n: number, s: string) => number'. + Type 'boolean' is not assignable to type 'number'. ==== tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.ts (1 errors) ==== @@ -17,5 +17,5 @@ tests/cases/conformance/expressions/contextualTyping/functionExpressionContextua a1 = (foo, bar) => { return true; } // Error ~~ !!! error TS2322: Type '(foo: number, bar: string) => boolean' is not assignable to type '((n: number, s: string) => number) | ((n: number, s: string) => string)'. -!!! error TS2322: Type '(foo: number, bar: string) => boolean' is not assignable to type '(n: number, s: string) => string'. -!!! error TS2322: Type 'boolean' is not assignable to type 'string'. \ No newline at end of file +!!! error TS2322: Type '(foo: number, bar: string) => boolean' is not assignable to type '(n: number, s: string) => number'. +!!! error TS2322: Type 'boolean' is not assignable to type 'number'. \ No newline at end of file From e726e4cfecbe808cdca9122ea9e62835498706b0 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 5 Sep 2018 11:23:39 -0700 Subject: [PATCH 046/146] PR Feedback --- src/compiler/diagnosticMessages.json | 4 ++++ src/compiler/moduleNameResolver.ts | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 8eb5f73b1a9..a1e33f00d8f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3684,6 +3684,10 @@ "category": "Message", "code": 6208 }, + "'package.json' has a 'typesVersions' entry '{0}' that is not a valid semver range.": { + "category": "Message", + "code": 6209 + }, "Projects to reference": { "category": "Message", diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index 0c2d35f19a8..bae4dbfa430 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -165,6 +165,14 @@ namespace ts { const typesVersions = readPackageJsonTypesVersionsField(jsonContent, state); if (typesVersions === undefined) return; + if (state.traceEnabled) { + for (const key in typesVersions) { + if (hasProperty(typesVersions, key) && !VersionRange.tryParse(key)) { + trace(state.host, Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key); + } + } + } + const result = getPackageJsonTypesVersionsPaths(typesVersions); if (!result) { if (state.traceEnabled) { From 69c7e67c88af4428e88261f3beb1fdec63ff441a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 5 Sep 2018 13:49:38 -0700 Subject: [PATCH 047/146] Check privateness when emittign readonly/const props (#26920) --- src/compiler/transformers/declarations.ts | 5 ++-- .../declarationEmitPrivateReadonlyLiterals.js | 28 +++++++++++++++++++ ...arationEmitPrivateReadonlyLiterals.symbols | 17 +++++++++++ ...clarationEmitPrivateReadonlyLiterals.types | 21 ++++++++++++++ .../declarationEmitPrivateReadonlyLiterals.ts | 8 ++++++ 5 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.js create mode 100644 tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.symbols create mode 100644 tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.types create mode 100644 tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 9974b60875b..f31058743a2 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1324,12 +1324,13 @@ namespace ts { } type CanHaveLiteralInitializer = VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration; - function canHaveLiteralInitializer(node: Node): node is CanHaveLiteralInitializer { + function canHaveLiteralInitializer(node: Node): boolean { switch (node.kind) { - case SyntaxKind.VariableDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: + return !hasModifier(node, ModifierFlags.Private); case SyntaxKind.Parameter: + case SyntaxKind.VariableDeclaration: return true; } return false; diff --git a/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.js b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.js new file mode 100644 index 00000000000..c7e1d1e8ee6 --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.js @@ -0,0 +1,28 @@ +//// [declarationEmitPrivateReadonlyLiterals.ts] +class Foo { + private static readonly A = "a"; + private readonly B = "b"; + private static readonly C = 42; + private readonly D = 42; +} + + +//// [declarationEmitPrivateReadonlyLiterals.js] +var Foo = /** @class */ (function () { + function Foo() { + this.B = "b"; + this.D = 42; + } + Foo.A = "a"; + Foo.C = 42; + return Foo; +}()); + + +//// [declarationEmitPrivateReadonlyLiterals.d.ts] +declare class Foo { + private static readonly A; + private readonly B; + private static readonly C; + private readonly D; +} diff --git a/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.symbols b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.symbols new file mode 100644 index 00000000000..ac3d42abf3a --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts === +class Foo { +>Foo : Symbol(Foo, Decl(declarationEmitPrivateReadonlyLiterals.ts, 0, 0)) + + private static readonly A = "a"; +>A : Symbol(Foo.A, Decl(declarationEmitPrivateReadonlyLiterals.ts, 0, 11)) + + private readonly B = "b"; +>B : Symbol(Foo.B, Decl(declarationEmitPrivateReadonlyLiterals.ts, 1, 36)) + + private static readonly C = 42; +>C : Symbol(Foo.C, Decl(declarationEmitPrivateReadonlyLiterals.ts, 2, 29)) + + private readonly D = 42; +>D : Symbol(Foo.D, Decl(declarationEmitPrivateReadonlyLiterals.ts, 3, 35)) +} + diff --git a/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.types b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.types new file mode 100644 index 00000000000..10fdff00b2e --- /dev/null +++ b/tests/baselines/reference/declarationEmitPrivateReadonlyLiterals.types @@ -0,0 +1,21 @@ +=== tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts === +class Foo { +>Foo : Foo + + private static readonly A = "a"; +>A : "a" +>"a" : "a" + + private readonly B = "b"; +>B : "b" +>"b" : "b" + + private static readonly C = 42; +>C : 42 +>42 : 42 + + private readonly D = 42; +>D : 42 +>42 : 42 +} + diff --git a/tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts b/tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts new file mode 100644 index 00000000000..3471929a2f7 --- /dev/null +++ b/tests/cases/compiler/declarationEmitPrivateReadonlyLiterals.ts @@ -0,0 +1,8 @@ +// @declaration: true + +class Foo { + private static readonly A = "a"; + private readonly B = "b"; + private static readonly C = 42; + private readonly D = 42; +} From 0b1183a4611bbf7568cecebc39d7e60128c4ec00 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 5 Sep 2018 14:52:47 -0700 Subject: [PATCH 048/146] Allow isSymbolAccessible to paint object literal declarations as visible (#24668) * Dont use resolveEntityName for computed property name symbol resolution - use checkExpression and resolvedSymbol instead * Fix lint --- src/compiler/checker.ts | 13 ++++++++- ...ctLiteralComputedNameNoDeclarationError.js | 29 +++++++++++++++++++ ...eralComputedNameNoDeclarationError.symbols | 18 ++++++++++++ ...iteralComputedNameNoDeclarationError.types | 23 +++++++++++++++ ...ctLiteralComputedNameNoDeclarationError.ts | 8 +++++ 5 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.js create mode 100644 tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.symbols create mode 100644 tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.types create mode 100644 tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index db040abdd52..5211abef285 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2871,7 +2871,18 @@ namespace ts { // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible // It is accessible if the parent m is accessible because then m.c can be accessed through qualification - const parentResult = isAnySymbolAccessible(getContainersOfSymbol(symbol, enclosingDeclaration), enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); + + let containers = getContainersOfSymbol(symbol, enclosingDeclaration); + // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct + // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however, + // we'd like to make that connection here - potentially causing us to paint the declararation's visibiility, and therefore the literal. + const firstDecl: Node = first(symbol.declarations); + if (!length(containers) && meaning & SymbolFlags.Value && firstDecl && isObjectLiteralExpression(firstDecl)) { + if (firstDecl.parent && isVariableDeclaration(firstDecl.parent) && firstDecl === firstDecl.parent.initializer) { + containers = [getSymbolOfNode(firstDecl.parent)]; + } + } + const parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible); if (parentResult) { return parentResult; } diff --git a/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.js b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.js new file mode 100644 index 00000000000..5c5e5feccd8 --- /dev/null +++ b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.js @@ -0,0 +1,29 @@ +//// [objectLiteralComputedNameNoDeclarationError.ts] +const Foo = { + BANANA: 'banana' as 'banana', +} + +export const Baa = { + [Foo.BANANA]: 1 +}; + +//// [objectLiteralComputedNameNoDeclarationError.js] +"use strict"; +exports.__esModule = true; +var _a; +var Foo = { + BANANA: 'banana' +}; +exports.Baa = (_a = {}, + _a[Foo.BANANA] = 1, + _a); + + +//// [objectLiteralComputedNameNoDeclarationError.d.ts] +declare const Foo: { + BANANA: "banana"; +}; +export declare const Baa: { + [Foo.BANANA]: number; +}; +export {}; diff --git a/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.symbols b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.symbols new file mode 100644 index 00000000000..dce3f633b10 --- /dev/null +++ b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.symbols @@ -0,0 +1,18 @@ +=== tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts === +const Foo = { +>Foo : Symbol(Foo, Decl(objectLiteralComputedNameNoDeclarationError.ts, 0, 5)) + + BANANA: 'banana' as 'banana', +>BANANA : Symbol(BANANA, Decl(objectLiteralComputedNameNoDeclarationError.ts, 0, 13)) +} + +export const Baa = { +>Baa : Symbol(Baa, Decl(objectLiteralComputedNameNoDeclarationError.ts, 4, 12)) + + [Foo.BANANA]: 1 +>[Foo.BANANA] : Symbol([Foo.BANANA], Decl(objectLiteralComputedNameNoDeclarationError.ts, 4, 20)) +>Foo.BANANA : Symbol(BANANA, Decl(objectLiteralComputedNameNoDeclarationError.ts, 0, 13)) +>Foo : Symbol(Foo, Decl(objectLiteralComputedNameNoDeclarationError.ts, 0, 5)) +>BANANA : Symbol(BANANA, Decl(objectLiteralComputedNameNoDeclarationError.ts, 0, 13)) + +}; diff --git a/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.types b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.types new file mode 100644 index 00000000000..17ef7ff584d --- /dev/null +++ b/tests/baselines/reference/objectLiteralComputedNameNoDeclarationError.types @@ -0,0 +1,23 @@ +=== tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts === +const Foo = { +>Foo : { BANANA: "banana"; } +>{ BANANA: 'banana' as 'banana',} : { BANANA: "banana"; } + + BANANA: 'banana' as 'banana', +>BANANA : "banana" +>'banana' as 'banana' : "banana" +>'banana' : "banana" +} + +export const Baa = { +>Baa : { [Foo.BANANA]: number; } +>{ [Foo.BANANA]: 1} : { [Foo.BANANA]: number; } + + [Foo.BANANA]: 1 +>[Foo.BANANA] : number +>Foo.BANANA : "banana" +>Foo : { BANANA: "banana"; } +>BANANA : "banana" +>1 : 1 + +}; diff --git a/tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts b/tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts new file mode 100644 index 00000000000..93755f5e5d5 --- /dev/null +++ b/tests/cases/compiler/objectLiteralComputedNameNoDeclarationError.ts @@ -0,0 +1,8 @@ +// @declaration: true +const Foo = { + BANANA: 'banana' as 'banana', +} + +export const Baa = { + [Foo.BANANA]: 1 +}; \ No newline at end of file From d989e10c4926e115c92325202430ea1fc75d653f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Sep 2018 11:50:47 -0700 Subject: [PATCH 049/146] Renamed test. --- .../compiler/errorsWithCallablesInUnions01.ts | 10 ---------- .../compiler/errorsWithInvokablesInUnions01.ts | 18 ++++++++++++++++++ 2 files changed, 18 insertions(+), 10 deletions(-) delete mode 100644 tests/cases/compiler/errorsWithCallablesInUnions01.ts create mode 100644 tests/cases/compiler/errorsWithInvokablesInUnions01.ts diff --git a/tests/cases/compiler/errorsWithCallablesInUnions01.ts b/tests/cases/compiler/errorsWithCallablesInUnions01.ts deleted file mode 100644 index 2cb6a3ebd35..00000000000 --- a/tests/cases/compiler/errorsWithCallablesInUnions01.ts +++ /dev/null @@ -1,10 +0,0 @@ -interface IDirectiveLinkFn { - (scope: TScope): void; -} - -interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; -} - -export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} diff --git a/tests/cases/compiler/errorsWithInvokablesInUnions01.ts b/tests/cases/compiler/errorsWithInvokablesInUnions01.ts new file mode 100644 index 00000000000..56491af71ce --- /dev/null +++ b/tests/cases/compiler/errorsWithInvokablesInUnions01.ts @@ -0,0 +1,18 @@ +interface ConstructableA { + new(): { somePropA: any }; +} + +interface IDirectiveLinkFn { + (scope: TScope): void; +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; +} + +export let blah: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = (x: string) => {} + +export let ctor: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = class { + someUnaccountedProp: any; +} From d0673762f10262209401765ea4bfd5810252b63c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Sep 2018 15:12:23 -0700 Subject: [PATCH 050/146] Accepted baselines. --- .../errorsWithCallablesInUnions01.errors.txt | 23 --------- .../errorsWithCallablesInUnions01.js | 17 ------- .../errorsWithCallablesInUnions01.symbols | 31 ------------ .../errorsWithCallablesInUnions01.types | 19 ------- .../errorsWithInvokablesInUnions01.errors.txt | 40 +++++++++++++++ .../errorsWithInvokablesInUnions01.js | 30 ++++++++++++ .../errorsWithInvokablesInUnions01.symbols | 49 +++++++++++++++++++ .../errorsWithInvokablesInUnions01.types | 32 ++++++++++++ 8 files changed, 151 insertions(+), 90 deletions(-) delete mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt delete mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.js delete mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.symbols delete mode 100644 tests/baselines/reference/errorsWithCallablesInUnions01.types create mode 100644 tests/baselines/reference/errorsWithInvokablesInUnions01.errors.txt create mode 100644 tests/baselines/reference/errorsWithInvokablesInUnions01.js create mode 100644 tests/baselines/reference/errorsWithInvokablesInUnions01.symbols create mode 100644 tests/baselines/reference/errorsWithInvokablesInUnions01.types diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt b/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt deleted file mode 100644 index 4881c4f7ff1..00000000000 --- a/tests/baselines/reference/errorsWithCallablesInUnions01.errors.txt +++ /dev/null @@ -1,23 +0,0 @@ -tests/cases/compiler/errorsWithCallablesInUnions01.ts(10,12): error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. - Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. - Types of parameters 'x' and 'scope' are incompatible. - Type 'number' is not assignable to type 'string'. - - -==== tests/cases/compiler/errorsWithCallablesInUnions01.ts (1 errors) ==== - interface IDirectiveLinkFn { - (scope: TScope): void; - } - - interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; - } - - export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} - ~~~~ -!!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn | IDirectivePrePost'. -!!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. -!!! error TS2322: Types of parameters 'x' and 'scope' are incompatible. -!!! error TS2322: Type 'number' is not assignable to type 'string'. - \ No newline at end of file diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.js b/tests/baselines/reference/errorsWithCallablesInUnions01.js deleted file mode 100644 index f9ea8041b16..00000000000 --- a/tests/baselines/reference/errorsWithCallablesInUnions01.js +++ /dev/null @@ -1,17 +0,0 @@ -//// [errorsWithCallablesInUnions01.ts] -interface IDirectiveLinkFn { - (scope: TScope): void; -} - -interface IDirectivePrePost { - pre?: IDirectiveLinkFn; - post?: IDirectiveLinkFn; -} - -export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} - - -//// [errorsWithCallablesInUnions01.js] -"use strict"; -exports.__esModule = true; -exports.blah = function (x) { }; diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.symbols b/tests/baselines/reference/errorsWithCallablesInUnions01.symbols deleted file mode 100644 index 40b48dc2458..00000000000 --- a/tests/baselines/reference/errorsWithCallablesInUnions01.symbols +++ /dev/null @@ -1,31 +0,0 @@ -=== tests/cases/compiler/errorsWithCallablesInUnions01.ts === -interface IDirectiveLinkFn { ->IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) ->TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 0, 27)) - - (scope: TScope): void; ->scope : Symbol(scope, Decl(errorsWithCallablesInUnions01.ts, 1, 5)) ->TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 0, 27)) -} - -interface IDirectivePrePost { ->IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithCallablesInUnions01.ts, 2, 1)) ->TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) - - pre?: IDirectiveLinkFn; ->pre : Symbol(IDirectivePrePost.pre, Decl(errorsWithCallablesInUnions01.ts, 4, 37)) ->IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) ->TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) - - post?: IDirectiveLinkFn; ->post : Symbol(IDirectivePrePost.post, Decl(errorsWithCallablesInUnions01.ts, 5, 35)) ->IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) ->TScope : Symbol(TScope, Decl(errorsWithCallablesInUnions01.ts, 4, 28)) -} - -export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} ->blah : Symbol(blah, Decl(errorsWithCallablesInUnions01.ts, 9, 10)) ->IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithCallablesInUnions01.ts, 0, 0)) ->IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithCallablesInUnions01.ts, 2, 1)) ->x : Symbol(x, Decl(errorsWithCallablesInUnions01.ts, 9, 73)) - diff --git a/tests/baselines/reference/errorsWithCallablesInUnions01.types b/tests/baselines/reference/errorsWithCallablesInUnions01.types deleted file mode 100644 index 492d870b6e4..00000000000 --- a/tests/baselines/reference/errorsWithCallablesInUnions01.types +++ /dev/null @@ -1,19 +0,0 @@ -=== tests/cases/compiler/errorsWithCallablesInUnions01.ts === -interface IDirectiveLinkFn { - (scope: TScope): void; ->scope : TScope -} - -interface IDirectivePrePost { - pre?: IDirectiveLinkFn; ->pre : IDirectiveLinkFn - - post?: IDirectiveLinkFn; ->post : IDirectiveLinkFn -} - -export let blah: IDirectiveLinkFn | IDirectivePrePost = (x: string) => {} ->blah : IDirectiveLinkFn | IDirectivePrePost ->(x: string) => {} : (x: string) => void ->x : string - diff --git a/tests/baselines/reference/errorsWithInvokablesInUnions01.errors.txt b/tests/baselines/reference/errorsWithInvokablesInUnions01.errors.txt new file mode 100644 index 00000000000..b70d3d744ef --- /dev/null +++ b/tests/baselines/reference/errorsWithInvokablesInUnions01.errors.txt @@ -0,0 +1,40 @@ +tests/cases/compiler/errorsWithInvokablesInUnions01.ts(14,12): error TS2322: Type '(x: string) => void' is not assignable to type 'ConstructableA | IDirectiveLinkFn | IDirectivePrePost'. + Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. + Types of parameters 'x' and 'scope' are incompatible. + Type 'number' is not assignable to type 'string'. +tests/cases/compiler/errorsWithInvokablesInUnions01.ts(16,12): error TS2322: Type 'typeof ctor' is not assignable to type 'ConstructableA | IDirectiveLinkFn | IDirectivePrePost'. + Type 'typeof ctor' is not assignable to type 'ConstructableA'. + Type 'ctor' is not assignable to type '{ somePropA: any; }'. + Property 'somePropA' is missing in type 'ctor'. + + +==== tests/cases/compiler/errorsWithInvokablesInUnions01.ts (2 errors) ==== + interface ConstructableA { + new(): { somePropA: any }; + } + + interface IDirectiveLinkFn { + (scope: TScope): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + export let blah: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = (x: string) => {} + ~~~~ +!!! error TS2322: Type '(x: string) => void' is not assignable to type 'ConstructableA | IDirectiveLinkFn | IDirectivePrePost'. +!!! error TS2322: Type '(x: string) => void' is not assignable to type 'IDirectiveLinkFn'. +!!! error TS2322: Types of parameters 'x' and 'scope' are incompatible. +!!! error TS2322: Type 'number' is not assignable to type 'string'. + + export let ctor: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = class { + ~~~~ +!!! error TS2322: Type 'typeof ctor' is not assignable to type 'ConstructableA | IDirectiveLinkFn | IDirectivePrePost'. +!!! error TS2322: Type 'typeof ctor' is not assignable to type 'ConstructableA'. +!!! error TS2322: Type 'ctor' is not assignable to type '{ somePropA: any; }'. +!!! error TS2322: Property 'somePropA' is missing in type 'ctor'. + someUnaccountedProp: any; + } + \ No newline at end of file diff --git a/tests/baselines/reference/errorsWithInvokablesInUnions01.js b/tests/baselines/reference/errorsWithInvokablesInUnions01.js new file mode 100644 index 00000000000..47c2df0fc23 --- /dev/null +++ b/tests/baselines/reference/errorsWithInvokablesInUnions01.js @@ -0,0 +1,30 @@ +//// [errorsWithInvokablesInUnions01.ts] +interface ConstructableA { + new(): { somePropA: any }; +} + +interface IDirectiveLinkFn { + (scope: TScope): void; +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; +} + +export let blah: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = (x: string) => {} + +export let ctor: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = class { + someUnaccountedProp: any; +} + + +//// [errorsWithInvokablesInUnions01.js] +"use strict"; +exports.__esModule = true; +exports.blah = function (x) { }; +exports.ctor = /** @class */ (function () { + function class_1() { + } + return class_1; +}()); diff --git a/tests/baselines/reference/errorsWithInvokablesInUnions01.symbols b/tests/baselines/reference/errorsWithInvokablesInUnions01.symbols new file mode 100644 index 00000000000..a82cecb7665 --- /dev/null +++ b/tests/baselines/reference/errorsWithInvokablesInUnions01.symbols @@ -0,0 +1,49 @@ +=== tests/cases/compiler/errorsWithInvokablesInUnions01.ts === +interface ConstructableA { +>ConstructableA : Symbol(ConstructableA, Decl(errorsWithInvokablesInUnions01.ts, 0, 0)) + + new(): { somePropA: any }; +>somePropA : Symbol(somePropA, Decl(errorsWithInvokablesInUnions01.ts, 1, 10)) +} + +interface IDirectiveLinkFn { +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithInvokablesInUnions01.ts, 2, 1)) +>TScope : Symbol(TScope, Decl(errorsWithInvokablesInUnions01.ts, 4, 27)) + + (scope: TScope): void; +>scope : Symbol(scope, Decl(errorsWithInvokablesInUnions01.ts, 5, 5)) +>TScope : Symbol(TScope, Decl(errorsWithInvokablesInUnions01.ts, 4, 27)) +} + +interface IDirectivePrePost { +>IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithInvokablesInUnions01.ts, 6, 1)) +>TScope : Symbol(TScope, Decl(errorsWithInvokablesInUnions01.ts, 8, 28)) + + pre?: IDirectiveLinkFn; +>pre : Symbol(IDirectivePrePost.pre, Decl(errorsWithInvokablesInUnions01.ts, 8, 37)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithInvokablesInUnions01.ts, 2, 1)) +>TScope : Symbol(TScope, Decl(errorsWithInvokablesInUnions01.ts, 8, 28)) + + post?: IDirectiveLinkFn; +>post : Symbol(IDirectivePrePost.post, Decl(errorsWithInvokablesInUnions01.ts, 9, 35)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithInvokablesInUnions01.ts, 2, 1)) +>TScope : Symbol(TScope, Decl(errorsWithInvokablesInUnions01.ts, 8, 28)) +} + +export let blah: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = (x: string) => {} +>blah : Symbol(blah, Decl(errorsWithInvokablesInUnions01.ts, 13, 10)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithInvokablesInUnions01.ts, 2, 1)) +>ConstructableA : Symbol(ConstructableA, Decl(errorsWithInvokablesInUnions01.ts, 0, 0)) +>IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithInvokablesInUnions01.ts, 6, 1)) +>x : Symbol(x, Decl(errorsWithInvokablesInUnions01.ts, 13, 90)) + +export let ctor: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = class { +>ctor : Symbol(ctor, Decl(errorsWithInvokablesInUnions01.ts, 15, 10)) +>IDirectiveLinkFn : Symbol(IDirectiveLinkFn, Decl(errorsWithInvokablesInUnions01.ts, 2, 1)) +>ConstructableA : Symbol(ConstructableA, Decl(errorsWithInvokablesInUnions01.ts, 0, 0)) +>IDirectivePrePost : Symbol(IDirectivePrePost, Decl(errorsWithInvokablesInUnions01.ts, 6, 1)) + + someUnaccountedProp: any; +>someUnaccountedProp : Symbol(ctor.someUnaccountedProp, Decl(errorsWithInvokablesInUnions01.ts, 15, 96)) +} + diff --git a/tests/baselines/reference/errorsWithInvokablesInUnions01.types b/tests/baselines/reference/errorsWithInvokablesInUnions01.types new file mode 100644 index 00000000000..3497a71cad8 --- /dev/null +++ b/tests/baselines/reference/errorsWithInvokablesInUnions01.types @@ -0,0 +1,32 @@ +=== tests/cases/compiler/errorsWithInvokablesInUnions01.ts === +interface ConstructableA { + new(): { somePropA: any }; +>somePropA : any +} + +interface IDirectiveLinkFn { + (scope: TScope): void; +>scope : TScope +} + +interface IDirectivePrePost { + pre?: IDirectiveLinkFn; +>pre : IDirectiveLinkFn + + post?: IDirectiveLinkFn; +>post : IDirectiveLinkFn +} + +export let blah: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = (x: string) => {} +>blah : ConstructableA | IDirectiveLinkFn | IDirectivePrePost +>(x: string) => {} : (x: string) => void +>x : string + +export let ctor: IDirectiveLinkFn | ConstructableA | IDirectivePrePost = class { +>ctor : ConstructableA | IDirectiveLinkFn | IDirectivePrePost +>class { someUnaccountedProp: any;} : typeof ctor + + someUnaccountedProp: any; +>someUnaccountedProp : any +} + From ddedfd44f7a743d8766277920a154a6834fa4a80 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Wed, 5 Sep 2018 15:22:39 -0700 Subject: [PATCH 051/146] Update user baselines (#26903) --- .../user/chrome-devtools-frontend.log | 143 ++++++------------ tests/baselines/reference/user/npm.log | 3 + 2 files changed, 48 insertions(+), 98 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 1331e636ac0..6085bb91b9e 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -11,7 +11,6 @@ Standard output: ../../../../built/local/lib.dom.d.ts(11899,13): error TS2300: Duplicate identifier 'Request'. ../../../../built/local/lib.dom.d.ts(16316,11): error TS2300: Duplicate identifier 'Window'. ../../../../built/local/lib.dom.d.ts(16447,13): error TS2300: Duplicate identifier 'Window'. -../../../../built/local/lib.dom.d.ts(17190,15): error TS2451: Cannot redeclare block-scoped variable 'name'. ../../../../built/local/lib.es5.d.ts(1346,11): error TS2300: Duplicate identifier 'ArrayLike'. ../../../../built/local/lib.es5.d.ts(1382,6): error TS2300: Duplicate identifier 'Record'. ../../../../node_modules/@types/node/index.d.ts(150,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type '{}', but here has type 'NodeModule'. @@ -555,7 +554,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/cate node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/category-renderer.js(483,32): error TS2503: Cannot find namespace 'ReportRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/category-renderer.js(507,24): error TS2339: Property 'open' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/category-renderer.js(554,8): error TS2339: Property 'CategoryRenderer' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/category-renderer.js(560,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/category-renderer.js(566,18): error TS2339: Property 'PerfHintExtendedInfo' does not exist on type 'typeof CategoryRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(43,45): error TS2694: Namespace 'CriticalRequestChainRenderer' has no exported member 'CRCSegment'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(71,15): error TS2304: Cannot find name 'DOM'. @@ -571,12 +569,9 @@ node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc- node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(158,9): error TS2304: Cannot find name 'Util'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(161,9): error TS2304: Cannot find name 'Util'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(184,8): error TS2339: Property 'CriticalRequestChainRenderer' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(188,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(194,30): error TS2339: Property 'CRCDetailsJSON' does not exist on type 'typeof CriticalRequestChainRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(197,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(204,30): error TS2339: Property 'CRCRequest' does not exist on type 'typeof CriticalRequestChainRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(216,42): error TS2694: Namespace 'CriticalRequestChainRenderer' has no exported member 'CRCRequest'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(220,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/crc-details-renderer.js(228,30): error TS2339: Property 'CRCSegment' does not exist on type 'typeof CriticalRequestChainRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(12,15): error TS2304: Cannot find name 'DOM'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(29,31): error TS2694: Namespace 'DetailsRenderer' has no exported member 'DetailsJSON'. @@ -603,35 +598,19 @@ node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/deta node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(268,18): error TS2304: Cannot find name 'Util'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(285,31): error TS2694: Namespace 'DetailsRenderer' has no exported member 'DetailsJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(298,8): error TS2339: Property 'DetailsRenderer' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(303,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(303,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(307,17): error TS2339: Property 'DetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(311,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(311,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(316,17): error TS2339: Property 'ListDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(320,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(320,8): error TS2300: Duplicate identifier 'type'. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(327,17): error TS2300: Duplicate identifier 'NodeDetailsJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(327,17): error TS2339: Property 'NodeDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(330,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(330,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(335,17): error TS2339: Property 'CardsDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(339,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(339,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(344,17): error TS2339: Property 'TableHeaderJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(348,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(348,8): error TS2300: Duplicate identifier 'type'. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(355,17): error TS2300: Duplicate identifier 'NodeDetailsJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(355,17): error TS2339: Property 'NodeDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(358,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(358,8): error TS2300: Duplicate identifier 'type'. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(360,46): error TS2694: Namespace 'DetailsRenderer' has no exported member 'DetailsJSON'. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(361,45): error TS2694: Namespace 'DetailsRenderer' has no exported member 'TableHeaderJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(364,17): error TS2339: Property 'TableDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(367,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(367,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(372,17): error TS2339: Property 'ThumbnailDetails' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(375,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(375,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(380,17): error TS2339: Property 'LinkDetailsJSON' does not exist on type 'typeof DetailsRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(383,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(383,8): error TS2300: Duplicate identifier 'type'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/details-renderer.js(388,17): error TS2339: Property 'FilmstripDetails' does not exist on type 'typeof DetailsRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/dom.js(63,67): error TS2339: Property 'querySelector' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/dom.js(76,43): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string'. @@ -650,13 +629,13 @@ node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/repo node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(119,30): error TS2694: Namespace 'ReportRenderer' has no exported member 'ReportJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(138,30): error TS2694: Namespace 'ReportRenderer' has no exported member 'ReportJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(172,8): error TS2339: Property 'ReportRenderer' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(177,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(193,21): error TS2503: Cannot find namespace 'DetailsRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(197,16): error TS2339: Property 'AuditJSON' does not exist on type 'typeof ReportRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(201,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(206,39): error TS2694: Namespace 'ReportRenderer' has no exported member 'AuditJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(209,16): error TS2339: Property 'CategoryJSON' does not exist on type 'typeof ReportRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(213,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(217,16): error TS2339: Property 'GroupJSON' does not exist on type 'typeof ReportRenderer'. -node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(221,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(229,49): error TS2694: Namespace 'ReportRenderer' has no exported member 'CategoryJSON'. +node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(230,54): error TS2694: Namespace 'ReportRenderer' has no exported member 'GroupJSON'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/report-renderer.js(237,16): error TS2339: Property 'ReportJSON' does not exist on type 'typeof ReportRenderer'. node_modules/chrome-devtools-frontend/front_end/audits2/lighthouse/renderer/util.js(124,5): error TS2322: Type '{}' is not assignable to type '{ numPathParts: number; preserveQuery: boolean; preserveHost: boolean; }'. Property 'numPathParts' is missing in type '{}'. @@ -3182,7 +3161,6 @@ node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(85,5): erro node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(91,25): error TS2304: Cannot find name 'FileError'. node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(96,42): error TS2304: Cannot find name 'FileError'. node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(176,25): error TS2304: Cannot find name 'FileError'. -node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(185,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/bindings/TempFile.js(189,33): error TS2339: Property 'Chunk' does not exist on type 'typeof TempFileBackingStorage'. node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/AutomappingTestRunner.js(48,26): error TS2554: Expected 5 arguments, but got 4. node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/AutomappingTestRunner.js(71,80): error TS2345: Argument of type 'Promise' is not assignable to parameter of type '() => Promise'. @@ -3209,7 +3187,11 @@ node_modules/chrome-devtools-frontend/front_end/bindings_test_runner/Persistence Type 'TestMapping' is not assignable to type '{ dispose: () => void; }'. Property '_onBindingAdded' does not exist on type '{ dispose: () => void; }'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(7,51): error TS2694: Namespace 'Changes.ChangesView' has no exported member 'Row'. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(9,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(9,56): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(10,75): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(11,53): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(12,53): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(12,91): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(22,42): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(47,11): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(47,11): error TS1345: An expression of type 'void' cannot be tested for truthiness @@ -3228,8 +3210,7 @@ node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(14 node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(155,44): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(156,45): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(162,53): error TS2694: Namespace 'Changes.ChangesHighlighter' has no exported member 'DiffState'. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(169,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(181,28): error TS2339: Property 'DiffState' does not exist on type '(config: any, parserConfig: { diffRows: any[]; baselineLines: string[]; currentLines: string[]; mimeType: string; }) => {}'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesHighlighter.js(181,28): error TS2339: Property 'DiffState' does not exist on type '(config: any, parserConfig: { diffRows: any[]; baselineLines: string[]; currentLines: string[]; mimeType: string; }) => { startState: () => any; token: (arg0: { backUp: (n: any) => void; column: () => void; current: () => void; ... 10 more ...; sol: () => void; } & StringStream, arg1: any) => string; blankLine: (arg...'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesSidebar.js(30,90): error TS2339: Property 'uiSourceCode' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesSidebar.js(38,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(26,44): error TS2694: Namespace 'Changes.ChangesView' has no exported member 'Row'. @@ -3256,7 +3237,6 @@ node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(215,15): node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(216,19): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(239,45): error TS2694: Namespace 'Changes.ChangesView' has no exported member 'Row'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(270,38): error TS2694: Namespace 'Changes.ChangesView' has no exported member 'Row'. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(308,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(314,21): error TS2339: Property 'Row' does not exist on type 'typeof ChangesView'. node_modules/chrome-devtools-frontend/front_end/cm/activeline.js(6,17): error TS2307: Cannot find module '../../lib/codemirror'. node_modules/chrome-devtools-frontend/front_end/cm/activeline.js(7,19): error TS2304: Cannot find name 'define'. @@ -3659,7 +3639,7 @@ node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(13,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(20,29): error TS2694: Namespace 'Common.Renderer' has no exported member 'Options'. node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(27,15): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(39,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(40,17): error TS2300: Duplicate identifier 'Options'. node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(40,17): error TS2339: Property 'Options' does not exist on type '{ (): void; prototype: { render(object: any, options: any): Promise; }; renderPromise(object: any, options?: any): Promise; }'. node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(63,15): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/common/ModuleExtensionInterfaces.js(81,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -3815,8 +3795,6 @@ node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(572,16): node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(580,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(587,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(616,5): error TS2322: Type '({ section: string; title: any; handler: () => void; } | { section: string; title: string; handler: any; })[]' is not assignable to type '{ title: string; handler: () => any; }[]'. -node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(631,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(646,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(666,22): error TS2551: Property 'LinkHandler' does not exist on type 'typeof Linkifier'. Did you mean '_linkHandlers'? node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(668,47): error TS2694: Namespace 'Components.Linkifier' has no exported member 'LinkHandler'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(675,1): error TS8022: JSDoc '@extends' is not attached to a class. @@ -4392,8 +4370,6 @@ node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(416 node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(461,42): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(470,51): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/cookie_table/CookiesTable.js(489,49): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(7,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(7,7): error TS2300: Duplicate identifier 'id'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(50,68): error TS2339: Property 'get' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(115,45): error TS2339: Property 'set' does not exist on type 'Multimap'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageDecorationManager.js(135,32): error TS2694: Namespace 'Coverage' has no exported member 'RawLocation'. @@ -4642,8 +4618,6 @@ node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1162,54): node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1170,23): error TS2339: Property 'offsetWidth' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1175,40): error TS2339: Property '__position' does not exist on type 'Element | { __index: number; __position: number; }'. Property '__position' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1200,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1200,6): error TS2300: Duplicate identifier 'id'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1214,19): error TS2339: Property 'ColumnDescriptor' does not exist on type 'typeof DataGrid'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1324,19): error TS2339: Property '_dataGridNode' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(1334,14): error TS2551: Property 'dirty' does not exist on type 'DataGridNode'. Did you mean '_dirty'? @@ -6213,14 +6187,10 @@ node_modules/chrome-devtools-frontend/front_end/externs.js(79,17): error TS2551: node_modules/chrome-devtools-frontend/front_end/externs.js(82,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(86,17): error TS2339: Property 'rotate' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/externs.js(90,17): error TS2339: Property 'sortNumbers' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/externs.js(92,13): error TS2304: Cannot find name 'S'. node_modules/chrome-devtools-frontend/front_end/externs.js(96,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(100,17): error TS2339: Property 'lowerBound' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/externs.js(102,13): error TS2304: Cannot find name 'S'. node_modules/chrome-devtools-frontend/front_end/externs.js(106,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(110,17): error TS2339: Property 'upperBound' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/externs.js(112,13): error TS2304: Cannot find name 'S'. -node_modules/chrome-devtools-frontend/front_end/externs.js(113,22): error TS2304: Cannot find name 'S'. node_modules/chrome-devtools-frontend/front_end/externs.js(114,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(118,17): error TS2339: Property 'binaryIndexOf' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/externs.js(125,13): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -6258,7 +6228,8 @@ node_modules/chrome-devtools-frontend/front_end/externs.js(278,13): error TS2355 node_modules/chrome-devtools-frontend/front_end/externs.js(328,175): error TS2694: Namespace 'Adb' has no exported member 'Page'. node_modules/chrome-devtools-frontend/front_end/externs.js(330,88): error TS2694: Namespace 'Adb' has no exported member 'Browser'. node_modules/chrome-devtools-frontend/front_end/externs.js(338,36): error TS2694: Namespace 'Adb' has no exported member 'DevicePortForwardingStatus'. -node_modules/chrome-devtools-frontend/front_end/externs.js(344,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/externs.js(346,33): error TS2694: Namespace 'Adb' has no exported member 'PortForwardingConfig'. +node_modules/chrome-devtools-frontend/front_end/externs.js(348,35): error TS2694: Namespace 'Adb' has no exported member 'NetworkDiscoveryConfig'. node_modules/chrome-devtools-frontend/front_end/externs.js(366,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(395,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/externs.js(443,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -6524,7 +6495,6 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1083,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1086,14): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1143,31): error TS2339: Property 'key' does not exist on type '(arg0: HeapSnapshotNode) => boolean'. -node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1195,53): error TS2551: Property 'aggregatesByClassIndex' does not exist on type '{ aggregatesByClassName: { [x: string]: any; }; }'. Did you mean 'aggregatesByClassName'? node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1230,33): error TS2339: Property 'traceNodeId' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1253,14): error TS2339: Property 'nodeIndex' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1254,23): error TS2339: Property 'id' does not exist on type 'void'. @@ -6532,9 +6502,7 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1345,12): error TS2339: Property 'nodeIndex' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1355,31): error TS2345: Argument of type 'void' is not assignable to parameter of type 'HeapSnapshotNode'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1369,89): error TS2694: Namespace 'HeapSnapshotWorker.HeapSnapshot' has no exported member 'AggregatedInfo'. -node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1370,4): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1424,59): error TS2322: Type '{ aggregatesByClassName: {}; aggregatesByClassIndex: {}; }' is not assignable to type '{ aggregatesByClassName: { [x: string]: any; }; }'. - Object literal may only specify known properties, but 'aggregatesByClassIndex' does not exist in type '{ aggregatesByClassName: { [x: string]: any; }; }'. Did you mean to write 'aggregatesByClassName'? +node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1370,83): error TS2694: Namespace 'HeapSnapshotWorker.HeapSnapshot' has no exported member 'AggregatedInfo'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1428,63): error TS2694: Namespace 'HeapSnapshotWorker.HeapSnapshot' has no exported member 'AggregatedInfo'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1447,12): error TS2339: Property 'nodeIndex' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(1448,29): error TS2339: Property 'classIndex' does not exist on type 'void'. @@ -6579,7 +6547,6 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapsho Type '(index: number) => HeapSnapshotRetainerEdge' is not assignable to type '(newIndex: number) => { itemIndex(): number; serialize(): any; }'. Type 'HeapSnapshotRetainerEdge' is not assignable to type '{ itemIndex(): number; serialize(): any; }'. Property '_snapshot' does not exist on type '{ itemIndex(): number; serialize(): any; }'. -node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2118,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2126,33): error TS2339: Property 'AggregatedInfo' does not exist on type 'typeof HeapSnapshot'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2205,12): error TS2339: Property 'sort' does not exist on type 'HeapSnapshotItemProvider'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(2244,13): error TS2345: Argument of type 'HeapSnapshotEdgeIterator' is not assignable to parameter of type '{ hasNext(): boolean; item(): { itemIndex(): number; serialize(): any; }; next(): void; }'. @@ -6637,7 +6604,6 @@ node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker.js(6,8): er node_modules/chrome-devtools-frontend/front_end/help/Help.js(6,19): error TS2694: Namespace 'Help' has no exported member 'ReleaseNote'. node_modules/chrome-devtools-frontend/front_end/help/Help.js(10,22): error TS2694: Namespace 'Help' has no exported member 'ReleaseNote'. node_modules/chrome-devtools-frontend/front_end/help/Help.js(61,74): error TS2694: Namespace 'Help' has no exported member 'ReleaseNoteHighlight'. -node_modules/chrome-devtools-frontend/front_end/help/Help.js(62,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/help/ReleaseNoteText.js(12,25): error TS2694: Namespace 'Help' has no exported member 'ReleaseNote'. node_modules/chrome-devtools-frontend/front_end/help/ReleaseNoteView.js(10,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/help/ReleaseNoteView.js(11,30): error TS2555: Expected at least 2 arguments, but got 1. @@ -6662,6 +6628,7 @@ node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(27 Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(407,19): error TS2694: Namespace 'Adb' has no exported member 'Config'. node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(445,48): error TS2694: Namespace 'InspectorFrontendHostAPI' has no exported member 'ContextMenuDescriptor'. +node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(471,12): error TS2538: Type 'string[]' cannot be used as an index type. node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(521,8): error TS2339: Property 'InspectorFrontendHost' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(527,14): error TS2339: Property 'InspectorFrontendHost' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/host/InspectorFrontendHost.js(557,10): error TS2339: Property 'InspectorFrontendAPI' does not exist on type 'Window'. @@ -7155,9 +7122,9 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingMana node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(218,82): error TS2339: Property 'selectedIndex' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(224,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(266,15): error TS2339: Property 'singleton' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(14,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(14,6): error TS2300: Duplicate identifier 'title'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(14,6): error TS2300: Duplicate identifier 'title'. +node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(16,35): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. +node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(17,43): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. +node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(20,18): error TS2300: Duplicate identifier 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(22,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(25,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(30,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. @@ -7168,8 +7135,6 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPres node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(46,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(48,10): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(49,16): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(56,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(56,6): error TS2300: Duplicate identifier 'title'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(62,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'PlaceholderConditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(64,10): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(65,16): error TS2555: Expected at least 2 arguments, but got 1. @@ -7456,8 +7421,7 @@ node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(481,66): error TS2694: Namespace 'Network.NetworkLogViewColumns' has no exported member 'Descriptor'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(522,19): error TS2694: Namespace 'UI' has no exported member 'PopoverRequest'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(531,31): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. -node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(601,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(601,8): error TS2300: Duplicate identifier 'id'. +node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(616,31): error TS2300: Duplicate identifier 'Descriptor'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(616,31): error TS2339: Property 'Descriptor' does not exist on type 'typeof NetworkLogViewColumns'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(640,50): error TS2694: Namespace 'Network.NetworkLogViewColumns' has no exported member 'Descriptor'. node_modules/chrome-devtools-frontend/front_end/network/NetworkLogViewColumns.js(645,12): error TS2555: Expected at least 2 arguments, but got 1. @@ -8021,10 +7985,8 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1167,15): node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1169,70): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1273,25): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1286,19): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1387,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1387,8): error TS2451: Cannot redeclare block-scoped variable 'name'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1390,34): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'GroupStyle'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1393,19): error TS2339: Property 'Group' does not exist on type 'typeof FlameChart'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1397,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1410,19): error TS2339: Property 'GroupStyle' does not exist on type 'typeof FlameChart'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1420,40): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'Group'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(1438,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8219,7 +8181,7 @@ node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemMa node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(154,72): error TS2694: Namespace 'Persistence.IsolatedFileSystemManager' has no exported member 'FileSystem'. node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(171,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(185,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(211,37): error TS2345: Argument of type 'string' is not assignable to parameter of type 'V'. +node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(211,21): error TS2345: Argument of type 'string' is not assignable to parameter of type 'K'. node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(222,30): error TS2339: Property 'valuesArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(284,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/persistence/IsolatedFileSystemManager.js(297,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -8326,13 +8288,6 @@ node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1164,15): node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1169,24): error TS2304: Cannot find name 'KEY'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1169,30): error TS2304: Cannot find name 'VALUE'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1171,15): error TS2339: Property 'inverse' does not exist on type 'Map'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1191,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1204,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1215,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1223,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1242,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1257,14): error TS2304: Cannot find name 'K'. -node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1264,23): error TS2304: Cannot find name 'K'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1277,14): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1277,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(1299,35): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. @@ -8983,7 +8938,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/TopDownProfileDataGrid. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(168,40): error TS2345: Argument of type 'S' is not assignable to parameter of type 'S'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(170,24): error TS2345: Argument of type 'S' is not assignable to parameter of type 'T'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(194,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. -node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(201,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(205,38): error TS2339: Property 'Params' does not exist on type '{ (): void; prototype: { sendMessage(message: string): void; disconnect(): Promise; }; }'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(208,61): error TS2694: Namespace 'Protocol.InspectorBackend.Connection' has no exported member 'Params'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(210,38): error TS2339: Property 'Factory' does not exist on type '{ (): void; prototype: { sendMessage(message: string): void; disconnect(): Promise; }; }'. @@ -9232,7 +9186,7 @@ node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(1 node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(41,12): error TS2339: Property 'registerStorageDispatcher' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(43,35): error TS2339: Property 'indexedDBAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(44,33): error TS2339: Property 'storageAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(58,4): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(62,24): error TS2694: Namespace 'Protocol' has no exported member 'IndexedDB'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(94,37): error TS2694: Namespace 'Protocol' has no exported member 'IndexedDB'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(100,25): error TS2694: Namespace 'Protocol' has no exported member 'IndexedDB'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(112,24): error TS2694: Namespace 'Protocol' has no exported member 'IndexedDB'. @@ -9818,7 +9772,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(838,24): er node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(839,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(899,22): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(908,19): error TS2339: Property 'FunctionDetails' does not exist on type 'typeof DebuggerModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(967,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(967,31): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(971,19): error TS2339: Property 'SetBreakpointResult' does not exist on type 'typeof DebuggerModel'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(987,32): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(991,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -9918,7 +9872,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(154,5): er Index signature is missing in type '{}'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(166,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(199,20): error TS2339: Property 'Message' does not exist on type 'typeof NetworkManager'. -node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(214,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(220,20): error TS2300: Duplicate identifier 'Conditions'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(220,20): error TS2339: Property 'Conditions' does not exist on type 'typeof NetworkManager'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(222,32): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(224,10): error TS2555: Expected at least 2 arguments, but got 1. @@ -10300,16 +10254,17 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(449,24): err node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(458,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(484,54): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(485,18): error TS2339: Property 'ExceptionWithTimestamp' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(488,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(488,27): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(489,36): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(492,18): error TS2339: Property 'CompileScriptResult' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(495,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(503,18): error TS2339: Property 'EvaluationOptions' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(506,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(506,7): error TS2457: Type alias name cannot be 'object'. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(507,36): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(508,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(511,18): error TS2339: Property 'EvaluationResult' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(514,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(515,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(518,18): error TS2339: Property 'QueryObjectResult' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(522,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(523,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(526,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(529,18): error TS2339: Property 'ConsoleAPICall' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(545,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(553,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -11006,7 +10961,8 @@ node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js( node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(379,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(382,13): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(415,52): error TS2694: Namespace 'UI.KeyboardShortcut' has no exported member 'Descriptor'. -node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(429,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(431,36): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(435,30): error TS2300: Duplicate identifier 'Item'. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(435,30): error TS2339: Property 'Item' does not exist on type 'typeof CallStackSidebarPane'. node_modules/chrome-devtools-frontend/front_end/sources/DebuggerPausedMessage.js(11,33): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/sources/DebuggerPausedMessage.js(54,37): error TS2555: Expected at least 2 arguments, but got 1. @@ -11720,11 +11676,10 @@ node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(337,33 node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(338,37): error TS2339: Property 'profilerAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(339,36): error TS2339: Property 'runtimeAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(340,35): error TS2339: Property 'targetAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(363,62): error TS2339: Property 'result' does not exist on type '{ response: RemoteObject; }'. +node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(363,62): error TS2339: Property 'result' does not exist on type '{ response: RemoteObject; exceptionDetails: any; }'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(368,34): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(372,42): error TS2339: Property 'result' does not exist on type '{ response: RemoteObject; }'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(372,65): error TS2339: Property 'exceptionDetails' does not exist on type '{ response: RemoteObject; }'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(381,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(372,42): error TS2339: Property 'result' does not exist on type '{ response: RemoteObject; exceptionDetails: any; }'. +node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(381,35): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(503,30): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(value: [any, any, any, any, any, any, any, any, any, any]) => [any, any, any, any, any, any, any, any, any, any] | PromiseLike<[any, any, any, any, any, any, any, any, any, any]>'. Type 'Function' provides no match for the signature '(value: [any, any, any, any, any, any, any, any, any, any]): [any, any, any, any, any, any, any, any, any, any] | PromiseLike<[any, any, any, any, any, any, any, any, any, any]>'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(641,59): error TS2339: Property 'testRunner' does not exist on type 'Window'. @@ -11845,7 +11800,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1637,12): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1637,61): error TS2339: Property 'line' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1637,71): error TS2339: Property 'ch' does not exist on type 'void'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1645,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1650,33): error TS2339: Property 'Decoration' does not exist on type 'typeof CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1659,29): error TS2694: Namespace 'UI.TextEditor' has no exported member 'Options'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorUtils.js(53,24): error TS2694: Namespace 'CodeMirror' has no exported member 'ChangeObject'. @@ -11987,11 +11941,8 @@ node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(2 node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(295,43): error TS2694: Namespace 'Timeline.PerformanceMonitor' has no exported member 'MetricInfo'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(320,41): error TS2339: Property 'peekLast' does not exist on type '{ timestamp: number; metrics: Map; }[]'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(330,24): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(394,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(394,6): error TS2300: Duplicate identifier 'title'. +node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(395,51): error TS2694: Namespace 'Timeline.PerformanceMonitor' has no exported member 'MetricInfo'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(402,29): error TS2339: Property 'ChartInfo' does not exist on type 'typeof PerformanceMonitor'. -node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(406,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(406,6): error TS2451: Cannot redeclare block-scoped variable 'name'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(411,29): error TS2339: Property 'MetricInfo' does not exist on type 'typeof PerformanceMonitor'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(419,27): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/PerformanceMonitor.js(427,52): error TS2694: Namespace 'Timeline.PerformanceMonitor' has no exported member 'ChartInfo'. @@ -12016,7 +11967,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(2 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(214,58): error TS2694: Namespace 'SDK.TracingManager' has no exported member 'EventPayload'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(233,96): error TS2339: Property 'peekLast' does not exist on type 'Event[]'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(272,1): error TS8022: JSDoc '@extends' is not attached to a class. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(283,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineController.js(288,29): error TS2339: Property 'RecordingOptions' does not exist on type 'typeof TimelineController'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineDetailsView.js(29,44): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineDetailsView.js(31,37): error TS2555: Expected at least 2 arguments, but got 1. @@ -12657,8 +12607,6 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2057 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2059,21): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2078,23): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2078,39): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2146,2): error TS1131: Property or signature expected. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2146,8): error TS2300: Duplicate identifier 'title'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2167,15): error TS2339: Property 'colSpan' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2186,10): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(2191,5): error TS2322: Type 'string | number' is not assignable to type 'string'. @@ -12898,11 +12846,10 @@ node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(171,22): error TS node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(174,21): error TS2339: Property 'remove' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(179,27): error TS2694: Namespace 'UI.Fragment' has no exported member '_Template'. node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(247,24): error TS2488: Type 'NodeListOf' must have a '[Symbol.iterator]()' method that returns an iterator. -node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(272,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(273,33): error TS2694: Namespace 'UI.Fragment' has no exported member '_Bind'. node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(276,13): error TS2551: Property '_Template' does not exist on type 'typeof Fragment'. Did you mean '_template'? -node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(280,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(286,13): error TS2339: Property '_State' does not exist on type 'typeof Fragment'. -node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(290,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(292,2): error TS1131: Property or signature expected. node_modules/chrome-devtools-frontend/front_end/ui/Fragment.js(307,13): error TS2339: Property '_Bind' does not exist on type 'typeof Fragment'. node_modules/chrome-devtools-frontend/front_end/ui/Geometry.js(210,15): error TS2304: Cannot find name 'CSSMatrix'. node_modules/chrome-devtools-frontend/front_end/ui/Geometry.js(272,13): error TS2304: Cannot find name 'CSSMatrix'. @@ -13346,9 +13293,9 @@ node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(47,15): error T node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(58,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(70,18): error TS2694: Namespace 'UI' has no exported member 'AutocompleteConfig'. node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(79,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. -node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(91,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(101,15): error TS2300: Duplicate identifier 'Options'. node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(101,15): error TS2339: Property 'Options' does not exist on type '{ (): void; prototype: { widget(): Widget; fullRange(): TextRange; selection(): TextRange; setSelection(selection: TextRange): void; text(textRange?: TextRange): string; setText(text: string): void; ... 5 more ...; tokenAtTextPosition(lineNumber: number, columnNumber: number): { ...; }; }; Events: { ...; }; }'. -node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(105,2): error TS1131: Property or signature expected. +node_modules/chrome-devtools-frontend/front_end/ui/TextEditor.js(106,119): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(52,74): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(113,39): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(115,24): error TS2339: Property 'style' does not exist on type 'Element'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index d808deab385..f2db4a09546 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -498,6 +498,9 @@ node_modules/npm/lib/ls.js(260,16): error TS2339: Property 'problems' does not e Property 'problems' does not exist on type 'string'. node_modules/npm/lib/ls.js(262,54): error TS2339: Property 'problems' does not exist on type 'string | { name: any; version: any; extraneous: boolean; problems: any; invalid: boolean; from: any; resolved: any; peerInvalid: boolean; dependencies: {}; } | { required: any; missing: boolean; } | { ...; }'. Property 'problems' does not exist on type 'string'. +node_modules/npm/lib/ls.js(264,12): error TS2538: Type '{ name: any; version: any; extraneous: boolean; problems: any; invalid: boolean; from: any; resolved: any; peerInvalid: boolean; dependencies: {}; }' cannot be used as an index type. +node_modules/npm/lib/ls.js(264,12): error TS2538: Type '{ required: any; missing: boolean; }' cannot be used as an index type. +node_modules/npm/lib/ls.js(264,12): error TS2538: Type '{ required: any; peerMissing: boolean; }' cannot be used as an index type. node_modules/npm/lib/ls.js(357,40): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/ls.js(362,26): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/ls.js(365,15): error TS2339: Property 'color' does not exist on type 'typeof EventEmitter'. From 5a72da76c28044e7b19e22bda98dcaa09d108762 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Wed, 5 Sep 2018 16:26:20 -0700 Subject: [PATCH 052/146] Only perform async refactor if it won't delete code --- .../codefixes/convertToAsyncFunction.ts | 11 +- .../unittests/convertToAsyncFunction.ts | 210 +++++++----------- ...yncFunction_NestedFunctionRightLocation.js | 24 ++ ...yncFunction_NestedFunctionRightLocation.ts | 24 ++ .../convertToAsyncFunction_NoRes4.js | 16 ++ .../convertToAsyncFunction_NoRes4.ts | 16 ++ 6 files changed, 176 insertions(+), 125 deletions(-) create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.js create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.ts create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.js create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.ts diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 76cdf471466..944bb06505d 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -2,11 +2,13 @@ namespace ts.codefix { const fixId = "convertToAsyncFunction"; const errorCodes = [Diagnostics.This_may_be_converted_to_an_async_function.code]; + let codeActionSucceeded = true; registerCodeFix({ errorCodes, getCodeActions(context: CodeFixContext) { + codeActionSucceeded = true; const changes = textChanges.ChangeTracker.with(context, (t) => convertToAsyncFunction(t, context.sourceFile, context.span.start, context.program.getTypeChecker(), context)); - return [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)]; + return codeActionSucceeded ? [createCodeFixAction(fixId, changes, Diagnostics.Convert_to_async_function, fixId, Diagnostics.Convert_all_to_async_functions)] : []; }, fixIds: [fixId], getAllCodeActions: context => codeFixAll(context, errorCodes, (changes, err) => convertToAsyncFunction(changes, err.file, err.start, context.program.getTypeChecker(), context)), @@ -387,6 +389,10 @@ namespace ts.codefix { const hasArgName = argName && argName.identifier.text.length > 0; const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { + case SyntaxKind.NullKeyword: + case SyntaxKind.UndefinedKeyword: + // do not produce a transformed statement for a null or undefined argument + break; case SyntaxKind.Identifier: if (!hasArgName) break; @@ -443,6 +449,9 @@ namespace ts.codefix { return createNodeArray([createReturn(getSynthesizedDeepClone(funcBody) as Expression)]); } } + default: + // We've found a transformation body we don't know how to handle, so the refactoring should no-op to avoid deleting code. + codeActionSucceeded = false; break; } return createNodeArray([]); diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 99788e1310e..9fac9e59e92 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1,66 +1,8 @@ namespace ts { - interface Range { - pos: number; - end: number; - name: string; - } - - interface Test { - source: string; - ranges: Map; - } - - function getTest(source: string): Test { - const activeRanges: Range[] = []; - let text = ""; - let lastPos = 0; - let pos = 0; - const ranges = createMap(); - - while (pos < source.length) { - if (source.charCodeAt(pos) === CharacterCodes.openBracket && - (source.charCodeAt(pos + 1) === CharacterCodes.hash || source.charCodeAt(pos + 1) === CharacterCodes.$)) { - const saved = pos; - pos += 2; - const s = pos; - consumeIdentifier(); - const e = pos; - if (source.charCodeAt(pos) === CharacterCodes.bar) { - pos++; - text += source.substring(lastPos, saved); - const name = s === e - ? source.charCodeAt(saved + 1) === CharacterCodes.hash ? "selection" : "extracted" - : source.substring(s, e); - activeRanges.push({ name, pos: text.length, end: undefined! }); - lastPos = pos; - continue; - } - else { - pos = saved; - } - } - else if (source.charCodeAt(pos) === CharacterCodes.bar && source.charCodeAt(pos + 1) === CharacterCodes.closeBracket) { - text += source.substring(lastPos, pos); - activeRanges[activeRanges.length - 1].end = text.length; - const range = activeRanges.pop()!; - if (range.name in ranges) { - throw new Error(`Duplicate name of range ${range.name}`); - } - ranges.set(range.name, range); - pos += 2; - lastPos = pos; - continue; - } - pos++; - } - text += source.substring(lastPos, pos); - - function consumeIdentifier() { - while (isIdentifierPart(source.charCodeAt(pos), ScriptTarget.Latest)) { - pos++; - } - } - return { source: text, ranges }; + const enum TestExpectation { + Normal, + NoDiagnostic, + NoAction } const libFile: TestFSWithWatch.File = { @@ -319,19 +261,22 @@ interface String { charAt: any; } interface Array {}` }; - function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, diagnosticDescription: DiagnosticMessage, codeFixDescription: DiagnosticMessage, includeLib?: boolean) { - const t = getTest(text); + function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectedResult: TestExpectation = TestExpectation.Normal) { + const t = extractTest(text); const selectionRange = t.ranges.get("selection")!; if (!selectionRange) { throw new Error(`Test ${caption} does not specify selection range`); } - [Extension.Ts, Extension.Js].forEach(extension => + const extensions = expectedResult === TestExpectation.Normal ? [Extension.Ts, Extension.Js] : [Extension.Ts]; + + extensions.forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); function runBaseline(extension: Extension) { const path = "/a" + extension; - const program = makeProgram({ path, content: t.source }, includeLib)!; + const languageService = makeLanguageService({ path, content: t.source }, includeLib); + const program = languageService.getProgram()!; if (hasSyntacticDiagnostics(program)) { // Don't bother generating JS baselines for inputs that aren't valid JS. @@ -345,10 +290,6 @@ interface Array {}` }; const sourceFile = program.getSourceFile(path)!; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); const context: CodeFixContext = { errorCode: 80006, span: { start: selectionRange.pos, length: selectionRange.end - selectionRange.pos }, @@ -361,37 +302,45 @@ interface Array {}` }; const diagnostics = languageService.getSuggestionDiagnostics(f.path); - const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === diagnosticDescription.message); + const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === Diagnostics.This_may_be_converted_to_an_async_function.message && + diagnostic.start === context.span.start && diagnostic.length === context.span.length); + if (expectedResult === TestExpectation.NoDiagnostic) { + assert.isUndefined(diagnostic); + return; + } + assert.exists(diagnostic); - assert.equal(diagnostic!.start, context.span.start); - assert.equal(diagnostic!.length, context.span.length); const actions = codefix.getFixes(context); - const action = find(actions, action => action.description === codeFixDescription.message)!; + const action = find(actions, action => action.description === Diagnostics.Convert_to_async_function.message); + if (expectedResult === TestExpectation.NoAction) { + assert.isUndefined(action); + return; + } + assert.exists(action); const data: string[] = []; data.push(`// ==ORIGINAL==`); data.push(text.replace("[#|", "/*[#|*/").replace("|]", "/*|]*/")); - const changes = action.changes; + const changes = action!.changes; assert.lengthOf(changes, 1); - data.push(`// ==ASYNC FUNCTION::${action.description}==`); + data.push(`// ==ASYNC FUNCTION::${action!.description}==`); const newText = textChanges.applyChanges(sourceFile.text, changes[0].textChanges); data.push(newText); - const diagProgram = makeProgram({ path, content: newText }, includeLib)!; + const diagProgram = makeLanguageService({ path, content: newText }, includeLib).getProgram()!; assert.isFalse(hasSyntacticDiagnostics(diagProgram)); Harness.Baseline.runBaseline(`${baselineFolder}/${caption}${extension}`, data.join(newLineCharacter)); } - function makeProgram(f: { path: string, content: string }, includeLib?: boolean) { + function makeLanguageService(f: { path: string, content: string }, includeLib?: boolean) { const host = projectSystem.createServerHost(includeLib ? [f, libFile] : [f]); // libFile is expensive to parse repeatedly - only test when required const projectService = projectSystem.createProjectService(host); projectService.openClientFile(f.path); - const program = projectService.inferredProjects[0].getLanguageService().getProgram(); - return program; + return projectService.inferredProjects[0].getLanguageService(); } function hasSyntacticDiagnostics(program: Program) { @@ -400,27 +349,6 @@ interface Array {}` } } - function testConvertToAsyncFunctionFailed(caption: string, text: string, description: DiagnosticMessage) { - it(caption, () => { - const t = extractTest(text); - const selectionRange = t.ranges.get("selection"); - if (!selectionRange) { - throw new Error(`Test ${caption} does not specify selection range`); - } - const f = { - path: "/a.ts", - content: t.source - }; - const host = projectSystem.createServerHost([f, libFile]); - const projectService = projectSystem.createProjectService(host); - projectService.openClientFile(f.path); - const languageService = projectService.inferredProjects[0].getLanguageService(); - - const actions = languageService.getSuggestionDiagnostics(f.path); - assert.isUndefined(find(actions, action => action.messageText === description.message)); - }); - } - describe("convertToAsyncFunctions", () => { _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` function [#|f|](): Promise{ @@ -547,7 +475,13 @@ function [#|f|]():Promise { } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", ` + _testConvertToAsyncFunction("convertToAsyncFunction_NoRes4", ` +function [#|f|]() { + return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); +} +` + ); + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NoSuggestion", ` function [#|f|]():Promise { return fetch('https://typescriptlang.org'); } @@ -561,7 +495,7 @@ function [#|f|]():Promise{ } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionNoPromise", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NoSuggestionNoPromise", ` function [#|f|]():void{ } ` @@ -614,21 +548,21 @@ function [#|f|]():Promise { } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally1", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally1", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).catch(rej => console.log("error", rej)).finally(console.log("finally!")); } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally2", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally2", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).finally(console.log("finally!")); } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally3", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally3", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").finally(console.log("finally!")); } @@ -656,14 +590,14 @@ function [#|innerPromise|](): Promise { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn01", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn01", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org").then(resp => console.log(resp)); return blob; } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn02", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn02", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); blob.then(resp => console.log(resp)); @@ -671,7 +605,7 @@ function [#|f|]() { } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn03", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn03", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org") let blob2 = blob.then(resp => console.log(resp)); @@ -684,7 +618,7 @@ function err (rej) { } ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn04", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn04", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)), blob2 = fetch("https://microsoft.com").then(res => res.ok).catch(err); return blob; @@ -695,7 +629,7 @@ function err (rej) { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn05", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn05", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)); blob.then(x => x); @@ -704,7 +638,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn06", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn06", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org"); return blob; @@ -712,7 +646,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn07", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn07", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); let blob2 = fetch("https://microsoft.com"); @@ -723,7 +657,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn08", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn08", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); if (!blob.ok){ @@ -735,7 +669,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn09", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn09", ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -749,7 +683,7 @@ function [#|f|]() { ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn10", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn10", ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -763,7 +697,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn11", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn11", ` function [#|f|]() { let blob; return blob; @@ -773,7 +707,7 @@ function [#|f|]() { - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Param1", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Param1", ` function [#|f|]() { return my_print(fetch("https://typescriptlang.org").then(res => console.log(res))); } @@ -830,7 +764,7 @@ function [#|f|](): Promise { ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_SeperateLines", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_SeperateLines", ` function [#|f|](): Promise { var blob = fetch("https://typescriptlang.org") blob.then(resp => { @@ -1093,7 +1027,7 @@ function [#|f|]() { } `); -_testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", ` +_testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_CatchFollowedByCall", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).toString(); } @@ -1157,7 +1091,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunction", ` + _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NestedFunctionWrongLocation", ` function [#|f|]() { function fn2(){ function fn3(){ @@ -1167,6 +1101,18 @@ function [#|f|]() { } return fn2(); } +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_NestedFunctionRightLocation", ` +function f() { + function fn2(){ + function [#|fn3|](){ + return fetch("https://typescriptlang.org").then(res => console.log(res)); + } + return fn3(); + } + return fn2(); +} `); _testConvertToAsyncFunction("convertToAsyncFunction_UntypedFunction", ` @@ -1194,14 +1140,30 @@ const [#|foo|] = function () { } `); + _testConvertToAsyncFunctionNoAction("convertToAsyncFunction_thenArgumentNotFunction", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)); +} +`); + +_testConvertToAsyncFunctionNoAction("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` +function [#|f|]() { + return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q); +} +`); + }); function _testConvertToAsyncFunction(caption: string, text: string) { - testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", Diagnostics.This_may_be_converted_to_an_async_function, Diagnostics.Convert_to_async_function, /*includeLib*/ true); + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true); } - function _testConvertToAsyncFunctionFailed(caption: string, text: string) { - testConvertToAsyncFunctionFailed(caption, text, Diagnostics.Convert_to_async_function); + function _testConvertToAsyncFunctionNoDiagnostic(caption: string, text: string) { + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, TestExpectation.NoDiagnostic); + } + + function _testConvertToAsyncFunctionNoAction(caption: string, text: string) { + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, TestExpectation.NoAction); } } \ No newline at end of file diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.js new file mode 100644 index 00000000000..fa55fb8ca22 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.js @@ -0,0 +1,24 @@ +// ==ORIGINAL== + +function f() { + function fn2(){ + function /*[#|*/fn3/*|]*/(){ + return fetch("https://typescriptlang.org").then(res => console.log(res)); + } + return fn3(); + } + return fn2(); +} + +// ==ASYNC FUNCTION::Convert to async function== + +function f() { + function fn2(){ + async function fn3(){ + const res = await fetch("https://typescriptlang.org"); + return console.log(res); + } + return fn3(); + } + return fn2(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.ts new file mode 100644 index 00000000000..fa55fb8ca22 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NestedFunctionRightLocation.ts @@ -0,0 +1,24 @@ +// ==ORIGINAL== + +function f() { + function fn2(){ + function /*[#|*/fn3/*|]*/(){ + return fetch("https://typescriptlang.org").then(res => console.log(res)); + } + return fn3(); + } + return fn2(); +} + +// ==ASYNC FUNCTION::Convert to async function== + +function f() { + function fn2(){ + async function fn3(){ + const res = await fetch("https://typescriptlang.org"); + return console.log(res); + } + return fn3(); + } + return fn2(); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.js new file mode 100644 index 00000000000..2bbf32e46a6 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.js @@ -0,0 +1,16 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + try { + await fetch('https://typescriptlang.org'); + } + catch (rejection) { + return console.log("rejected:", rejection); + } +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.ts new file mode 100644 index 00000000000..2bbf32e46a6 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_NoRes4.ts @@ -0,0 +1,16 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return fetch('https://typescriptlang.org').then(undefined, rejection => console.log("rejected:", rejection)); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + try { + await fetch('https://typescriptlang.org'); + } + catch (rejection) { + return console.log("rejected:", rejection); + } +} From f7f5b1ac87e88ba3a3b809de606b2eaf269e7136 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Wed, 5 Sep 2018 16:28:53 -0700 Subject: [PATCH 053/146] Don't case on type node --- src/services/codefixes/convertToAsyncFunction.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 944bb06505d..61e142a8a08 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -390,7 +390,6 @@ namespace ts.codefix { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { case SyntaxKind.NullKeyword: - case SyntaxKind.UndefinedKeyword: // do not produce a transformed statement for a null or undefined argument break; case SyntaxKind.Identifier: From ea984d7b64fc7b57d643ffc2792eac01baccddc2 Mon Sep 17 00:00:00 2001 From: christian Date: Wed, 5 Sep 2018 23:18:39 -0400 Subject: [PATCH 054/146] Centralize diagnostic reporting for empty files diagnostic --- src/compiler/commandLineParser.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 5d87525073f..a2dac4e7d33 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1846,7 +1846,7 @@ namespace ts { const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; if (filesSpecs.length === 0 && hasZeroOrNoReferences) { - createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); } } else { @@ -2078,12 +2078,6 @@ namespace ts { } }; const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator); - const hasZeroFiles = json && json.files && json.files.length === 0; - const hasZeroOrNoReferences = !(json && json.references) || json.references.length === 0; - - if (hasZeroFiles && hasZeroOrNoReferences) { - errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, sourceFile.fileName)); - } if (!typeAcquisition) { if (typingOptionstypeAcquisition) { From d8f736d319aead69fcf9541877ac2919638103b9 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 6 Sep 2018 00:41:09 -0700 Subject: [PATCH 055/146] Change `typeof` narrowing to narrow selected union members (#25243) * For typeof narrow all union members prior to filtering * Revise narrowTypeByTypeof to both narrow unions and applicable union members * Add repros from issue --- src/compiler/checker.ts | 46 ++++++------ .../reference/controlFlowIfStatement.types | 2 +- .../reference/recursiveTypeRelations.types | 4 +- .../reference/strictTypeofUnionNarrowing.js | 32 +++++++++ .../strictTypeofUnionNarrowing.symbols | 47 ++++++++++++ .../strictTypeofUnionNarrowing.types | 71 +++++++++++++++++++ ...ypeGuardOfFormTypeOfPrimitiveSubtype.types | 12 ++-- .../reference/typeGuardTypeOfUndefined.types | 36 +++++----- .../compiler/strictTypeofUnionNarrowing.ts | 16 +++++ 9 files changed, 218 insertions(+), 48 deletions(-) create mode 100644 tests/baselines/reference/strictTypeofUnionNarrowing.js create mode 100644 tests/baselines/reference/strictTypeofUnionNarrowing.symbols create mode 100644 tests/baselines/reference/strictTypeofUnionNarrowing.types create mode 100644 tests/cases/compiler/strictTypeofUnionNarrowing.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ef173a2c667..5709b1b1616 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14963,30 +14963,34 @@ namespace ts { if (type.flags & TypeFlags.Any && literal.text === "function") { return type; } - if (assumeTrue && !(type.flags & TypeFlags.Union)) { - if (type.flags & TypeFlags.Unknown && literal.text === "object") { - return getUnionType([nonPrimitiveType, nullType]); - } - // We narrow a non-union type to an exact primitive type if the non-union type - // is a supertype of that primitive type. For example, type 'any' can be narrowed - // to one of the primitive types. - const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); - if (targetType) { - if (isTypeSubtypeOf(targetType, type)) { - return targetType; - } - if (type.flags & TypeFlags.Instantiable) { - const constraint = getBaseConstraintOfType(type) || anyType; - if (isTypeSubtypeOf(targetType, constraint)) { - return getIntersectionType([type, targetType]); - } - } - } - } const facts = assumeTrue ? typeofEQFacts.get(literal.text) || TypeFacts.TypeofEQHostObject : typeofNEFacts.get(literal.text) || TypeFacts.TypeofNEHostObject; - return getTypeWithFacts(type, facts); + return getTypeWithFacts(assumeTrue ? mapType(type, narrowTypeForTypeof) : type, facts); + + function narrowTypeForTypeof(type: Type) { + if (assumeTrue && !(type.flags & TypeFlags.Union)) { + if (type.flags & TypeFlags.Unknown && literal.text === "object") { + return getUnionType([nonPrimitiveType, nullType]); + } + // We narrow a non-union type to an exact primitive type if the non-union type + // is a supertype of that primitive type. For example, type 'any' can be narrowed + // to one of the primitive types. + const targetType = literal.text === "function" ? globalFunctionType : typeofTypesByName.get(literal.text); + if (targetType) { + if (isTypeSubtypeOf(targetType, type)) { + return isTypeAny(type) ? targetType : getIntersectionType([type, targetType]); // Intersection to handle `string` being a subtype of `keyof T` + } + if (type.flags & TypeFlags.Instantiable) { + const constraint = getBaseConstraintOfType(type) || anyType; + if (isTypeSubtypeOf(targetType, constraint)) { + return getIntersectionType([type, targetType]); + } + } + } + } + return type; + } } function narrowTypeBySwitchOnDiscriminant(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number) { diff --git a/tests/baselines/reference/controlFlowIfStatement.types b/tests/baselines/reference/controlFlowIfStatement.types index 39083598ee2..03141e26185 100644 --- a/tests/baselines/reference/controlFlowIfStatement.types +++ b/tests/baselines/reference/controlFlowIfStatement.types @@ -104,7 +104,7 @@ function c(data: string | T): T { >JSON.parse : (text: string, reviver?: (key: any, value: any) => any) => any >JSON : JSON >parse : (text: string, reviver?: (key: any, value: any) => any) => any ->data : string +>data : string | (T & string) } else { return data; diff --git a/tests/baselines/reference/recursiveTypeRelations.types b/tests/baselines/reference/recursiveTypeRelations.types index 893986d2dab..3ca21ccd8e5 100644 --- a/tests/baselines/reference/recursiveTypeRelations.types +++ b/tests/baselines/reference/recursiveTypeRelations.types @@ -58,9 +58,9 @@ export function css(styles: S, ...classNam >"string" : "string" return styles[arg]; ->styles[arg] : S[keyof S] +>styles[arg] : S[keyof S & string] >styles : S ->arg : keyof S +>arg : keyof S & string } if (typeof arg == "object") { >typeof arg == "object" : boolean diff --git a/tests/baselines/reference/strictTypeofUnionNarrowing.js b/tests/baselines/reference/strictTypeofUnionNarrowing.js new file mode 100644 index 00000000000..93b9c7d4330 --- /dev/null +++ b/tests/baselines/reference/strictTypeofUnionNarrowing.js @@ -0,0 +1,32 @@ +//// [strictTypeofUnionNarrowing.ts] +function stringify1(anything: { toString(): string } | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify2(anything: {} | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify3(anything: unknown | undefined): string { // should simplify to just `unknown` which should narrow fine + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify4(anything: { toString?(): string } | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + + +//// [strictTypeofUnionNarrowing.js] +"use strict"; +function stringify1(anything) { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} +function stringify2(anything) { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} +function stringify3(anything) { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} +function stringify4(anything) { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} diff --git a/tests/baselines/reference/strictTypeofUnionNarrowing.symbols b/tests/baselines/reference/strictTypeofUnionNarrowing.symbols new file mode 100644 index 00000000000..83a602eeaf1 --- /dev/null +++ b/tests/baselines/reference/strictTypeofUnionNarrowing.symbols @@ -0,0 +1,47 @@ +=== tests/cases/compiler/strictTypeofUnionNarrowing.ts === +function stringify1(anything: { toString(): string } | undefined): string { +>stringify1 : Symbol(stringify1, Decl(strictTypeofUnionNarrowing.ts, 0, 0)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 0, 20)) +>toString : Symbol(toString, Decl(strictTypeofUnionNarrowing.ts, 0, 31)) + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 0, 20)) +>anything.toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 0, 20)) +>toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +} + +function stringify2(anything: {} | undefined): string { +>stringify2 : Symbol(stringify2, Decl(strictTypeofUnionNarrowing.ts, 2, 1)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 4, 20)) + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 4, 20)) +>anything.toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 4, 20)) +>toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +} + +function stringify3(anything: unknown | undefined): string { // should simplify to just `unknown` which should narrow fine +>stringify3 : Symbol(stringify3, Decl(strictTypeofUnionNarrowing.ts, 6, 1)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 8, 20)) + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 8, 20)) +>anything.toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 8, 20)) +>toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +} + +function stringify4(anything: { toString?(): string } | undefined): string { +>stringify4 : Symbol(stringify4, Decl(strictTypeofUnionNarrowing.ts, 10, 1)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 12, 20)) +>toString : Symbol(toString, Decl(strictTypeofUnionNarrowing.ts, 12, 31)) + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 12, 20)) +>anything.toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +>anything : Symbol(anything, Decl(strictTypeofUnionNarrowing.ts, 12, 20)) +>toUpperCase : Symbol(String.toUpperCase, Decl(lib.es5.d.ts, --, --)) +} + diff --git a/tests/baselines/reference/strictTypeofUnionNarrowing.types b/tests/baselines/reference/strictTypeofUnionNarrowing.types new file mode 100644 index 00000000000..3039ece15d6 --- /dev/null +++ b/tests/baselines/reference/strictTypeofUnionNarrowing.types @@ -0,0 +1,71 @@ +=== tests/cases/compiler/strictTypeofUnionNarrowing.ts === +function stringify1(anything: { toString(): string } | undefined): string { +>stringify1 : (anything: { toString(): string; } | undefined) => string +>anything : { toString(): string; } | undefined +>toString : () => string + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>typeof anything === "string" ? anything.toUpperCase() : "" : string +>typeof anything === "string" : boolean +>typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>anything : { toString(): string; } | undefined +>"string" : "string" +>anything.toUpperCase() : string +>anything.toUpperCase : () => string +>anything : { toString(): string; } & string +>toUpperCase : () => string +>"" : "" +} + +function stringify2(anything: {} | undefined): string { +>stringify2 : (anything: {} | undefined) => string +>anything : {} | undefined + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>typeof anything === "string" ? anything.toUpperCase() : "" : string +>typeof anything === "string" : boolean +>typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>anything : {} | undefined +>"string" : "string" +>anything.toUpperCase() : string +>anything.toUpperCase : () => string +>anything : string & {} +>toUpperCase : () => string +>"" : "" +} + +function stringify3(anything: unknown | undefined): string { // should simplify to just `unknown` which should narrow fine +>stringify3 : (anything: unknown) => string +>anything : unknown + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>typeof anything === "string" ? anything.toUpperCase() : "" : string +>typeof anything === "string" : boolean +>typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>anything : unknown +>"string" : "string" +>anything.toUpperCase() : string +>anything.toUpperCase : () => string +>anything : string +>toUpperCase : () => string +>"" : "" +} + +function stringify4(anything: { toString?(): string } | undefined): string { +>stringify4 : (anything: {} | undefined) => string +>anything : {} | undefined +>toString : (() => string) | undefined + + return typeof anything === "string" ? anything.toUpperCase() : ""; +>typeof anything === "string" ? anything.toUpperCase() : "" : string +>typeof anything === "string" : boolean +>typeof anything : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>anything : {} | undefined +>"string" : "string" +>anything.toUpperCase() : string +>anything.toUpperCase : () => string +>anything : {} & string +>toUpperCase : () => string +>"" : "" +} + diff --git a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types index 4787c07d758..6510b73d44d 100644 --- a/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types +++ b/tests/baselines/reference/typeGuardOfFormTypeOfPrimitiveSubtype.types @@ -14,7 +14,7 @@ if (typeof a === "number") { let c: number = a; >c : number ->a : number +>a : number & {} } if (typeof a === "string") { >typeof a === "string" : boolean @@ -24,7 +24,7 @@ if (typeof a === "string") { let c: string = a; >c : string ->a : string +>a : string & {} } if (typeof a === "boolean") { >typeof a === "boolean" : boolean @@ -34,7 +34,7 @@ if (typeof a === "boolean") { let c: boolean = a; >c : boolean ->a : boolean +>a : (false & {}) | (true & {}) } if (typeof b === "number") { @@ -45,7 +45,7 @@ if (typeof b === "number") { let c: number = b; >c : number ->b : number +>b : { toString(): string; } & number } if (typeof b === "string") { >typeof b === "string" : boolean @@ -55,7 +55,7 @@ if (typeof b === "string") { let c: string = b; >c : string ->b : string +>b : { toString(): string; } & string } if (typeof b === "boolean") { >typeof b === "boolean" : boolean @@ -65,6 +65,6 @@ if (typeof b === "boolean") { let c: boolean = b; >c : boolean ->b : boolean +>b : ({ toString(): string; } & false) | ({ toString(): string; } & true) } diff --git a/tests/baselines/reference/typeGuardTypeOfUndefined.types b/tests/baselines/reference/typeGuardTypeOfUndefined.types index a28dab04490..00777ac0eae 100644 --- a/tests/baselines/reference/typeGuardTypeOfUndefined.types +++ b/tests/baselines/reference/typeGuardTypeOfUndefined.types @@ -134,7 +134,7 @@ function test5(a: boolean | void) { } else { a; ->a : boolean | void +>a : undefined } } @@ -151,15 +151,15 @@ function test6(a: boolean | void) { if (typeof a === "boolean") { >typeof a === "boolean" : boolean >typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->a : boolean | void +>a : undefined >"boolean" : "boolean" a; ->a : boolean +>a : never } else { a; ->a : void +>a : undefined } } else { @@ -184,7 +184,7 @@ function test7(a: boolean | void) { >"boolean" : "boolean" a; ->a : boolean | void +>a : boolean } else { a; @@ -212,7 +212,7 @@ function test8(a: boolean | void) { } else { a; ->a : boolean | void +>a : undefined } } @@ -242,7 +242,7 @@ function test9(a: boolean | number) { } else { a; ->a : number | boolean +>a : undefined } } @@ -259,15 +259,15 @@ function test10(a: boolean | number) { if (typeof a === "boolean") { >typeof a === "boolean" : boolean >typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->a : number | boolean +>a : undefined >"boolean" : "boolean" a; ->a : boolean +>a : never } else { a; ->a : number +>a : undefined } } else { @@ -292,7 +292,7 @@ function test11(a: boolean | number) { >"boolean" : "boolean" a; ->a : number | boolean +>a : boolean } else { a; @@ -320,7 +320,7 @@ function test12(a: boolean | number) { } else { a; ->a : number | boolean +>a : number } } @@ -350,7 +350,7 @@ function test13(a: boolean | number | void) { } else { a; ->a : number | boolean | void +>a : undefined } } @@ -367,15 +367,15 @@ function test14(a: boolean | number | void) { if (typeof a === "boolean") { >typeof a === "boolean" : boolean >typeof a : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->a : number | boolean | void +>a : undefined >"boolean" : "boolean" a; ->a : boolean +>a : never } else { a; ->a : number | void +>a : undefined } } else { @@ -400,7 +400,7 @@ function test15(a: boolean | number | void) { >"boolean" : "boolean" a; ->a : number | boolean | void +>a : boolean } else { a; @@ -428,7 +428,7 @@ function test16(a: boolean | number | void) { } else { a; ->a : number | boolean | void +>a : number } } diff --git a/tests/cases/compiler/strictTypeofUnionNarrowing.ts b/tests/cases/compiler/strictTypeofUnionNarrowing.ts new file mode 100644 index 00000000000..f2bddf3f939 --- /dev/null +++ b/tests/cases/compiler/strictTypeofUnionNarrowing.ts @@ -0,0 +1,16 @@ +// @strict: true +function stringify1(anything: { toString(): string } | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify2(anything: {} | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify3(anything: unknown | undefined): string { // should simplify to just `unknown` which should narrow fine + return typeof anything === "string" ? anything.toUpperCase() : ""; +} + +function stringify4(anything: { toString?(): string } | undefined): string { + return typeof anything === "string" ? anything.toUpperCase() : ""; +} From 3173cfee97529ea9b4e5a93df33b243c108c7609 Mon Sep 17 00:00:00 2001 From: Jack Williams Date: Thu, 6 Sep 2018 09:45:22 +0100 Subject: [PATCH 056/146] Update narrowing baseline --- .../reference/narrowingByTypeofInSwitch.types | 49 ------------------- 1 file changed, 49 deletions(-) diff --git a/tests/baselines/reference/narrowingByTypeofInSwitch.types b/tests/baselines/reference/narrowingByTypeofInSwitch.types index a2aef98feb4..000eea75f79 100644 --- a/tests/baselines/reference/narrowingByTypeofInSwitch.types +++ b/tests/baselines/reference/narrowingByTypeofInSwitch.types @@ -42,7 +42,6 @@ function assertSymbol(x: symbol) { function assertFunction(x: Function) { >assertFunction : (x: Function) => Function >x : Function ->Function : Function return x; >x : Function @@ -67,7 +66,6 @@ function assertUndefined(x: undefined) { function assertAll(x: Basic) { >assertAll : (x: Basic) => Basic >x : Basic ->Basic : Basic return x; >x : Basic @@ -91,12 +89,10 @@ function assertBooleanOrObject(x: boolean | object) { type Basic = number | boolean | string | symbol | object | Function | undefined; >Basic : Basic ->Function : Function function testUnion(x: Basic) { >testUnion : (x: Basic) => void >x : Basic ->Basic : Basic switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -152,10 +148,7 @@ function testUnion(x: Basic) { function testExtendsUnion(x: T) { >testExtendsUnion : (x: T) => void ->T : T ->Basic : Basic >x : T ->T : T switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -276,7 +269,6 @@ function a1(x: string | object | undefined) { function testUnionExplicitDefault(x: Basic) { >testUnionExplicitDefault : (x: Basic) => void >x : Basic ->Basic : Basic switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -316,7 +308,6 @@ function testUnionExplicitDefault(x: Basic) { function testUnionImplicitDefault(x: Basic) { >testUnionImplicitDefault : (x: Basic) => string | object | undefined >x : Basic ->Basic : Basic switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -354,10 +345,7 @@ function testUnionImplicitDefault(x: Basic) { function testExtendsExplicitDefault(x: T) { >testExtendsExplicitDefault : (x: T) => void ->T : T ->Basic : Basic >x : T ->T : T switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -397,10 +385,7 @@ function testExtendsExplicitDefault(x: T) { function testExtendsImplicitDefault(x: T) { >testExtendsImplicitDefault : (x: T) => string | number | boolean | symbol | object | undefined ->T : T ->Basic : Basic >x : T ->T : T switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -448,8 +433,6 @@ type R = { x: string, y: number } function exhaustiveChecks(x: number | string | L | R): string { >exhaustiveChecks : (x: string | number | R | L) => string >x : string | number | R | L ->L : L ->R : R switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -483,11 +466,7 @@ function exhaustiveChecks(x: number | string | L | R): string { function exhaustiveChecksGenerics(x: T): string { >exhaustiveChecksGenerics : (x: T) => string ->T : T ->L : L ->R : R >x : T ->T : T switch (typeof x) { >typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -511,7 +490,6 @@ function exhaustiveChecksGenerics(x: T): stri >(x as L) : L >x as L : L >x : T ->L : L >42 : 42 case 'object': return (x as R).x; // Can't narrow generic @@ -520,22 +498,13 @@ function exhaustiveChecksGenerics(x: T): stri >(x as R) : R >x as R : R >x : T ->R : R >x : string } } function multipleGeneric(xy: X | Y): [X, string] | [Y, number] { >multipleGeneric : (xy: X | Y) => [X, string] | [Y, number] ->X : X ->L : L ->Y : Y ->R : R >xy : X | Y ->X : X ->Y : Y ->X : X ->Y : Y switch (typeof xy) { >typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -566,17 +535,7 @@ function multipleGeneric(xy: X | Y): [X, string] | [Y, function multipleGenericFuse(xy: X | Y): [X, number] | [Y, string] | [(X | Y)] { >multipleGenericFuse : (xy: X | Y) => [X, number] | [Y, string] | [X | Y] ->X : X ->L : L ->Y : Y ->R : R >xy : X | Y ->X : X ->Y : Y ->X : X ->Y : Y ->X : X ->Y : Y switch (typeof xy) { >typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" @@ -603,15 +562,7 @@ function multipleGenericFuse(xy: X | function multipleGenericExhaustive(xy: X | Y): [X, string] | [Y, number] { >multipleGenericExhaustive : (xy: X | Y) => [X, string] | [Y, number] ->X : X ->L : L ->Y : Y ->R : R >xy : X | Y ->X : X ->Y : Y ->X : X ->Y : Y switch (typeof xy) { >typeof xy : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" From 8c22770ea8ce739faf6deb25e2ba022cd1c9af6e Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 6 Sep 2018 10:44:32 -0700 Subject: [PATCH 057/146] Improve 'isWriteAccess' for findAllReferences (#26889) --- src/compiler/types.ts | 1 + src/compiler/utilities.ts | 28 +++++---- src/services/findAllReferences.ts | 62 ++++++++++++++++++- .../reference/api/tsserverlibrary.d.ts | 1 + tests/baselines/reference/api/typescript.d.ts | 1 + .../findAllReferencesJsDocTypeLiteral.ts | 2 +- .../findAllRefsDestructureGeneric.ts | 2 +- .../findAllRefsForComputedProperties.ts | 2 +- .../findAllRefsForComputedProperties2.ts | 2 +- .../fourslash/findAllRefsForMappedType.ts | 2 +- .../fourslash/findAllRefsForObjectSpread.ts | 4 +- tests/cases/fourslash/findAllRefsForRest.ts | 2 +- .../fourslash/findAllRefsInClassExpression.ts | 2 +- .../findAllRefsIndexedAccessTypes.ts | 4 +- .../findAllRefsInheritedProperties1.ts | 2 +- .../findAllRefsInheritedProperties2.ts | 4 +- .../findAllRefsInheritedProperties3.ts | 8 +-- .../findAllRefsInheritedProperties4.ts | 6 +- .../findAllRefsInheritedProperties5.ts | 6 +- .../cases/fourslash/findAllRefsMappedType.ts | 2 +- ...lRefsObjectBindingElementPropertyName01.ts | 2 +- ...lRefsObjectBindingElementPropertyName02.ts | 2 +- ...lRefsObjectBindingElementPropertyName03.ts | 2 +- ...lRefsObjectBindingElementPropertyName04.ts | 2 +- ...lRefsObjectBindingElementPropertyName06.ts | 2 +- ...lRefsObjectBindingElementPropertyName10.ts | 2 +- ...sPropertyContextuallyTypedByTypeParam01.ts | 2 +- .../fourslash/findAllRefsReExportLocal.ts | 2 +- ...efsRedeclaredPropertyInDerivedInterface.ts | 4 +- .../cases/fourslash/findAllRefsRootSymbols.ts | 4 +- tests/cases/fourslash/findAllRefsTypedef.ts | 2 +- .../fourslash/findAllRefsUnionProperty.ts | 4 +- .../findAllRefsWithLeadingUnderscoreNames5.ts | 2 +- .../findAllRefsWithLeadingUnderscoreNames6.ts | 2 +- ...AllRefsWithShorthandPropertyAssignment2.ts | 2 +- .../findReferencesAcrossMultipleProjects.ts | 2 +- .../fourslash/findReferencesAfterEdit.ts | 2 +- .../fourslash/findReferencesJSXTagName3.ts | 2 +- ...currencesIsDefinitionOfComputedProperty.ts | 2 +- .../fourslash/referencesForClassMembers.ts | 4 +- ...esForClassMembersExtendingAbstractClass.ts | 6 +- ...cesForClassMembersExtendingGenericClass.ts | 4 +- ...ontextuallyTypedObjectLiteralProperties.ts | 2 +- ...ncesForContextuallyTypedUnionProperties.ts | 4 +- ...cesForContextuallyTypedUnionProperties2.ts | 2 +- .../referencesForFunctionOverloads.ts | 2 +- .../fourslash/referencesForIndexProperty.ts | 2 +- .../fourslash/referencesForIndexProperty3.ts | 2 +- .../referencesForInheritedProperties.ts | 4 +- .../referencesForInheritedProperties2.ts | 4 +- .../referencesForInheritedProperties3.ts | 4 +- .../referencesForInheritedProperties4.ts | 2 +- .../referencesForInheritedProperties5.ts | 8 +-- .../referencesForInheritedProperties7.ts | 8 +-- .../referencesForInheritedProperties8.ts | 6 +- .../referencesForInheritedProperties9.ts | 4 +- ...eferencesForNumericLiteralPropertyNames.ts | 2 +- .../cases/fourslash/referencesForOverrides.ts | 20 +++--- .../referencesForPropertiesOfGenericType.ts | 2 +- ...rencesForStaticsAndMembersWithSameNames.ts | 4 +- ...referencesForStringLiteralPropertyNames.ts | 2 +- .../fourslash/referencesForUnionProperties.ts | 6 +- .../renameImportAndExportInDiffFiles.ts | 2 +- .../cases/fourslash/tsxFindAllReferences10.ts | 2 +- .../cases/fourslash/tsxFindAllReferences3.ts | 2 +- .../cases/fourslash/tsxFindAllReferences7.ts | 2 +- .../cases/fourslash/tsxFindAllReferences9.ts | 2 +- 67 files changed, 183 insertions(+), 118 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f6927925428..279fef73d5e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -739,6 +739,7 @@ namespace ts { } export interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 47bf4193bd6..7a128a41c69 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -2384,29 +2384,33 @@ namespace ts { } // See GH#16030 - export function isAnyDeclarationName(name: Node): boolean { + export function getDeclarationFromName(name: Node): Declaration | undefined { + const parent = name.parent; switch (name.kind) { - case SyntaxKind.Identifier: case SyntaxKind.StringLiteral: - case SyntaxKind.NumericLiteral: { - const parent = name.parent; + case SyntaxKind.NumericLiteral: + if (isComputedPropertyName(parent)) return parent.parent; + // falls through + + case SyntaxKind.Identifier: if (isDeclaration(parent)) { - return parent.name === name; + return parent.name === name ? parent : undefined; } - else if (isQualifiedName(name.parent)) { - const tag = name.parent.parent; - return isJSDocParameterTag(tag) && tag.name === name.parent; + else if (isQualifiedName(parent)) { + const tag = parent.parent; + return isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined; } else { - const binExp = name.parent.parent; + const binExp = parent.parent; return isBinaryExpression(binExp) && getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && (binExp.left.symbol || binExp.symbol) && - getNameOfDeclaration(binExp) === name; + getNameOfDeclaration(binExp) === name + ? binExp + : undefined; } - } default: - return false; + return undefined; } } diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 81da5a0d82f..bcc68162746 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -154,7 +154,7 @@ namespace ts.FindAllReferences { textSpan: getTextSpan(node, sourceFile), isWriteAccess: isWriteAccessForReference(node), isDefinition: node.kind === SyntaxKind.DefaultKeyword - || isAnyDeclarationName(node) + || !!getDeclarationFromName(node) || isLiteralComputedPropertyDeclarationName(node), isInString, }; @@ -223,7 +223,65 @@ namespace ts.FindAllReferences { /** A node is considered a writeAccess iff it is a name of a declaration or a target of an assignment */ function isWriteAccessForReference(node: Node): boolean { - return node.kind === SyntaxKind.DefaultKeyword || isAnyDeclarationName(node) || isWriteAccess(node); + const decl = getDeclarationFromName(node); + return !!decl && declarationIsWriteAccess(decl) || node.kind === SyntaxKind.DefaultKeyword || isWriteAccess(node); + } + + /** + * True if 'decl' provides a value, as in `function f() {}`; + * false if 'decl' is just a location for a future write, as in 'let x;' + */ + function declarationIsWriteAccess(decl: Declaration): boolean { + // Consider anything in an ambient declaration to be a write access since it may be coming from JS. + if (!!(decl.flags & NodeFlags.Ambient)) return true; + + switch (decl.kind) { + case SyntaxKind.BinaryExpression: + case SyntaxKind.BindingElement: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.ClassExpression: + case SyntaxKind.DefaultKeyword: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.EnumMember: + case SyntaxKind.ExportSpecifier: + case SyntaxKind.ImportClause: // default import + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.ImportSpecifier: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.JSDocCallbackTag: + case SyntaxKind.JSDocTypedefTag: + case SyntaxKind.JsxAttribute: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.NamespaceExportDeclaration: + case SyntaxKind.NamespaceImport: + case SyntaxKind.Parameter: + case SyntaxKind.PropertyAssignment: + case SyntaxKind.ShorthandPropertyAssignment: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.TypeParameter: + return true; + + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.Constructor: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + return !!(decl as FunctionDeclaration | FunctionExpression | ConstructorDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration).body; + + case SyntaxKind.VariableDeclaration: + case SyntaxKind.PropertyDeclaration: + return !!(decl as VariableDeclaration | PropertyDeclaration).initializer || isCatchClause(decl.parent); + + case SyntaxKind.MethodSignature: + case SyntaxKind.PropertySignature: + case SyntaxKind.JSDocPropertyTag: + case SyntaxKind.JSDocParameterTag: + return false; + + default: + return Debug.failBadSyntaxKind(decl); + } } } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 3e54190429b..2fa23f14a7b 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -536,6 +536,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 8d8690781d0..8290cb96236 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -536,6 +536,7 @@ declare namespace ts { name?: Identifier | StringLiteral | NumericLiteral; } interface ComputedPropertyName extends Node { + parent: Declaration; kind: SyntaxKind.ComputedPropertyName; expression: Expression; } diff --git a/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts b/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts index 48befe13442..25059d028ed 100644 --- a/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts +++ b/tests/cases/fourslash/findAllReferencesJsDocTypeLiteral.ts @@ -8,7 +8,7 @@ //// * @param {string} o.x - a thing, its ok //// * @param {number} o.y - another thing //// * @param {Object} o.nested - very nested -//// * @param {boolean} o.nested.[|{| "isWriteAccess": true, "isDefinition": true |}great|] - much greatness +//// * @param {boolean} o.nested.[|{| "isDefinition": true |}great|] - much greatness //// * @param {number} o.nested.times - twice? probably!?? //// */ //// function f(o) { return o.nested.[|great|]; } diff --git a/tests/cases/fourslash/findAllRefsDestructureGeneric.ts b/tests/cases/fourslash/findAllRefsDestructureGeneric.ts index f3d4635cebd..3d7a84cb35a 100644 --- a/tests/cases/fourslash/findAllRefsDestructureGeneric.ts +++ b/tests/cases/fourslash/findAllRefsDestructureGeneric.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}x|]: boolean; +//// [|{| "isDefinition": true |}x|]: boolean; ////} ////declare const i: I; ////const { [|{| "isWriteAccess": true, "isDefinition": true |}x|] } = i; diff --git a/tests/cases/fourslash/findAllRefsForComputedProperties.ts b/tests/cases/fourslash/findAllRefsForComputedProperties.ts index 7dac0432e94..3c442b8b63a 100644 --- a/tests/cases/fourslash/findAllRefsForComputedProperties.ts +++ b/tests/cases/fourslash/findAllRefsForComputedProperties.ts @@ -9,7 +9,7 @@ ////} //// ////var x: I = { -//// ["[|{| "isDefinition": true |}prop1|]"]: function () { }, +//// ["[|{| "isWriteAccess": true, "isDefinition": true |}prop1|]"]: function () { }, ////} const ranges = test.ranges(); diff --git a/tests/cases/fourslash/findAllRefsForComputedProperties2.ts b/tests/cases/fourslash/findAllRefsForComputedProperties2.ts index 81abd714d32..21f9d2c92ba 100644 --- a/tests/cases/fourslash/findAllRefsForComputedProperties2.ts +++ b/tests/cases/fourslash/findAllRefsForComputedProperties2.ts @@ -9,7 +9,7 @@ ////} //// ////var x: I = { -//// ["[|{| "isDefinition": true |}42|]"]: function () { } +//// ["[|{| "isWriteAccess": true, "isDefinition": true |}42|]"]: function () { } ////} const ranges = test.ranges(); diff --git a/tests/cases/fourslash/findAllRefsForMappedType.ts b/tests/cases/fourslash/findAllRefsForMappedType.ts index 904dc8c42c7..8965fa046ea 100644 --- a/tests/cases/fourslash/findAllRefsForMappedType.ts +++ b/tests/cases/fourslash/findAllRefsForMappedType.ts @@ -1,6 +1,6 @@ /// -////interface T { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number }; +////interface T { [|{| "isDefinition": true |}a|]: number }; ////type U = { [K in keyof T]: string }; ////type V = { [K in keyof U]: boolean }; ////const u: U = { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: "" } diff --git a/tests/cases/fourslash/findAllRefsForObjectSpread.ts b/tests/cases/fourslash/findAllRefsForObjectSpread.ts index c6f111672c8..12c338ca529 100644 --- a/tests/cases/fourslash/findAllRefsForObjectSpread.ts +++ b/tests/cases/fourslash/findAllRefsForObjectSpread.ts @@ -1,7 +1,7 @@ /// -////interface A1 { readonly [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string }; -////interface A2 { [|{| "isWriteAccess": true, "isDefinition": true |}a|]?: number }; +////interface A1 { readonly [|{| "isDefinition": true |}a|]: string }; +////interface A2 { [|{| "isDefinition": true |}a|]?: number }; ////let a1: A1; ////let a2: A2; ////let a12 = { ...a1, ...a2 }; diff --git a/tests/cases/fourslash/findAllRefsForRest.ts b/tests/cases/fourslash/findAllRefsForRest.ts index 026451d68b8..3dac71374f0 100644 --- a/tests/cases/fourslash/findAllRefsForRest.ts +++ b/tests/cases/fourslash/findAllRefsForRest.ts @@ -1,7 +1,7 @@ /// ////interface Gen { //// x: number -//// [|{| "isWriteAccess": true, "isDefinition": true |}parent|]: Gen; +//// [|{| "isDefinition": true |}parent|]: Gen; //// millenial: string; ////} ////let t: Gen; diff --git a/tests/cases/fourslash/findAllRefsInClassExpression.ts b/tests/cases/fourslash/findAllRefsInClassExpression.ts index 19ec2df35d2..8adc64e8e6d 100644 --- a/tests/cases/fourslash/findAllRefsInClassExpression.ts +++ b/tests/cases/fourslash/findAllRefsInClassExpression.ts @@ -1,6 +1,6 @@ /// -////interface I { [|{| "isWriteAccess": true, "isDefinition": true |}boom|](): void; } +////interface I { [|{| "isDefinition": true |}boom|](): void; } ////new class C implements I { //// [|{| "isWriteAccess": true, "isDefinition": true |}boom|](){} ////} diff --git a/tests/cases/fourslash/findAllRefsIndexedAccessTypes.ts b/tests/cases/fourslash/findAllRefsIndexedAccessTypes.ts index fdfb00439f6..49dac247294 100644 --- a/tests/cases/fourslash/findAllRefsIndexedAccessTypes.ts +++ b/tests/cases/fourslash/findAllRefsIndexedAccessTypes.ts @@ -1,8 +1,8 @@ /// ////interface I { -//// [|{| "isDefinition": true, "isWriteAccess": true |}0|]: number; -//// [|{| "isDefinition": true, "isWriteAccess": true |}s|]: string; +//// [|{| "isDefinition": true |}0|]: number; +//// [|{| "isDefinition": true |}s|]: string; ////} ////interface J { //// a: I[[|0|]], diff --git a/tests/cases/fourslash/findAllRefsInheritedProperties1.ts b/tests/cases/fourslash/findAllRefsInheritedProperties1.ts index 3b14e686cc6..9e58a37c589 100644 --- a/tests/cases/fourslash/findAllRefsInheritedProperties1.ts +++ b/tests/cases/fourslash/findAllRefsInheritedProperties1.ts @@ -2,7 +2,7 @@ //// class class1 extends class1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// //// var v: class1; diff --git a/tests/cases/fourslash/findAllRefsInheritedProperties2.ts b/tests/cases/fourslash/findAllRefsInheritedProperties2.ts index 23badd64d48..2e776e48acd 100644 --- a/tests/cases/fourslash/findAllRefsInheritedProperties2.ts +++ b/tests/cases/fourslash/findAllRefsInheritedProperties2.ts @@ -1,8 +1,8 @@ /// //// interface interface1 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; // r0 -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; // r1 +//// [|{| "isDefinition": true |}doStuff|](): void; // r0 +//// [|{| "isDefinition": true |}propName|]: string; // r1 //// } //// //// var v: interface1; diff --git a/tests/cases/fourslash/findAllRefsInheritedProperties3.ts b/tests/cases/fourslash/findAllRefsInheritedProperties3.ts index 2c929a559fb..ea5b1ce7bf4 100644 --- a/tests/cases/fourslash/findAllRefsInheritedProperties3.ts +++ b/tests/cases/fourslash/findAllRefsInheritedProperties3.ts @@ -2,15 +2,15 @@ //// class class1 extends class1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } // r0 -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; // r1 +//// [|{| "isDefinition": true |}propName|]: string; // r1 //// } //// interface interface1 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; // r2 -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; // r3 +//// [|{| "isDefinition": true |}doStuff|](): void; // r2 +//// [|{| "isDefinition": true |}propName|]: string; // r3 //// } //// class class2 extends class1 implements interface1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } // r4 -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; // r5 +//// [|{| "isDefinition": true |}propName|]: string; // r5 //// } //// //// var v: class2; diff --git a/tests/cases/fourslash/findAllRefsInheritedProperties4.ts b/tests/cases/fourslash/findAllRefsInheritedProperties4.ts index e2d8887bbe8..2528fef1939 100644 --- a/tests/cases/fourslash/findAllRefsInheritedProperties4.ts +++ b/tests/cases/fourslash/findAllRefsInheritedProperties4.ts @@ -1,12 +1,12 @@ /// //// interface C extends D { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop0|]: string; // r0 -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop1|]: number; // r1 +//// [|{| "isDefinition": true |}prop0|]: string; // r0 +//// [|{| "isDefinition": true |}prop1|]: number; // r1 //// } //// //// interface D extends C { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop0|]: string; // r2 +//// [|{| "isDefinition": true |}prop0|]: string; // r2 //// } //// //// var d: D; diff --git a/tests/cases/fourslash/findAllRefsInheritedProperties5.ts b/tests/cases/fourslash/findAllRefsInheritedProperties5.ts index c534a9d6aab..343328405d5 100644 --- a/tests/cases/fourslash/findAllRefsInheritedProperties5.ts +++ b/tests/cases/fourslash/findAllRefsInheritedProperties5.ts @@ -1,12 +1,12 @@ /// //// class C extends D { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop0|]: string; // r0 -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop1|]: number; // r1 +//// [|{| "isDefinition": true |}prop0|]: string; // r0 +//// [|{| "isDefinition": true |}prop1|]: number; // r1 //// } //// //// class D extends C { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop0|]: string; // r2 +//// [|{| "isDefinition": true |}prop0|]: string; // r2 //// } //// //// var d: D; diff --git a/tests/cases/fourslash/findAllRefsMappedType.ts b/tests/cases/fourslash/findAllRefsMappedType.ts index 97658da08c1..8c6c59150af 100644 --- a/tests/cases/fourslash/findAllRefsMappedType.ts +++ b/tests/cases/fourslash/findAllRefsMappedType.ts @@ -1,6 +1,6 @@ /// -////interface T { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; } +////interface T { [|{| "isDefinition": true |}a|]: number; } ////type U = { readonly [K in keyof T]?: string }; ////declare const t: T; ////t.[|a|]; diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName01.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName01.ts index d11bcee506f..5a72ca1c1ec 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName01.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName01.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property1|]: number; +//// [|{| "isDefinition": true |}property1|]: number; //// property2: string; ////} //// diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName02.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName02.ts index 6ad98df9cd8..76b6d046b8e 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName02.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName02.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property1|]: number; +//// [|{| "isDefinition": true |}property1|]: number; //// property2: string; ////} //// diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName03.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName03.ts index 520dbc8e1e4..f82eca087bb 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName03.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName03.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property1|]: number; +//// [|{| "isDefinition": true |}property1|]: number; //// property2: string; ////} //// diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts index f25fff9da23..fe0d659f0ec 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName04.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property1|]: number; +//// [|{| "isDefinition": true |}property1|]: number; //// property2: string; ////} //// diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName06.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName06.ts index a8dd5bda227..62d1637f3b3 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName06.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName06.ts @@ -1,7 +1,7 @@ /// ////interface I { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property1|]: number; +//// [|{| "isDefinition": true |}property1|]: number; //// property2: string; ////} //// diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName10.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName10.ts index 500ca7fe3cf..7d31cfd4345 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName10.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName10.ts @@ -1,7 +1,7 @@ /// ////interface Recursive { -//// [|{| "isWriteAccess": true, "isDefinition": true |}next|]?: Recursive; +//// [|{| "isDefinition": true |}next|]?: Recursive; //// value: any; ////} //// diff --git a/tests/cases/fourslash/findAllRefsPropertyContextuallyTypedByTypeParam01.ts b/tests/cases/fourslash/findAllRefsPropertyContextuallyTypedByTypeParam01.ts index e4e9b830510..d4aefb58ac3 100644 --- a/tests/cases/fourslash/findAllRefsPropertyContextuallyTypedByTypeParam01.ts +++ b/tests/cases/fourslash/findAllRefsPropertyContextuallyTypedByTypeParam01.ts @@ -1,7 +1,7 @@ /// ////interface IFoo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string; +//// [|{| "isDefinition": true |}a|]: string; ////} ////class C { //// method() { diff --git a/tests/cases/fourslash/findAllRefsReExportLocal.ts b/tests/cases/fourslash/findAllRefsReExportLocal.ts index ed1d0b105b6..603971a2294 100644 --- a/tests/cases/fourslash/findAllRefsReExportLocal.ts +++ b/tests/cases/fourslash/findAllRefsReExportLocal.ts @@ -3,7 +3,7 @@ // @noLib: true // @Filename: /a.ts -////var [|{| "isWriteAccess": true, "isDefinition": true |}x|]; +////var [|{| "isDefinition": true |}x|]; ////export { [|{| "isWriteAccess": true, "isDefinition": true |}x|] }; ////export { [|x|] as [|{| "isWriteAccess": true, "isDefinition": true |}y|] }; diff --git a/tests/cases/fourslash/findAllRefsRedeclaredPropertyInDerivedInterface.ts b/tests/cases/fourslash/findAllRefsRedeclaredPropertyInDerivedInterface.ts index 1964ebf2c2c..dff05b219be 100644 --- a/tests/cases/fourslash/findAllRefsRedeclaredPropertyInDerivedInterface.ts +++ b/tests/cases/fourslash/findAllRefsRedeclaredPropertyInDerivedInterface.ts @@ -3,10 +3,10 @@ // @noLib: true ////interface A { -//// readonly [|{| "isWriteAccess": true, "isDefinition": true |}x|]: number | string; +//// readonly [|{| "isDefinition": true |}x|]: number | string; ////} ////interface B extends A { -//// readonly [|{| "isWriteAccess": true, "isDefinition": true |}x|]: number; +//// readonly [|{| "isDefinition": true |}x|]: number; ////} ////const a: A = { [|{| "isWriteAccess": true, "isDefinition": true |}x|]: 0 }; ////const b: B = { [|{| "isWriteAccess": true, "isDefinition": true |}x|]: 0 }; diff --git a/tests/cases/fourslash/findAllRefsRootSymbols.ts b/tests/cases/fourslash/findAllRefsRootSymbols.ts index 77eea3b46b0..0e209765b37 100644 --- a/tests/cases/fourslash/findAllRefsRootSymbols.ts +++ b/tests/cases/fourslash/findAllRefsRootSymbols.ts @@ -1,7 +1,7 @@ /// -////interface I { [|{| "isWriteAccess": true, "isDefinition": true |}x|]: {}; } -////interface J { [|{| "isWriteAccess": true, "isDefinition": true |}x|]: {}; } +////interface I { [|{| "isDefinition": true |}x|]: {}; } +////interface J { [|{| "isDefinition": true |}x|]: {}; } ////declare const o: (I | J) & { [|{| "isWriteAccess": true, "isDefinition": true |}x|]: string }; ////o.[|x|]; diff --git a/tests/cases/fourslash/findAllRefsTypedef.ts b/tests/cases/fourslash/findAllRefsTypedef.ts index ecd690c10e5..2e7d8601656 100644 --- a/tests/cases/fourslash/findAllRefsTypedef.ts +++ b/tests/cases/fourslash/findAllRefsTypedef.ts @@ -5,7 +5,7 @@ // @Filename: /a.js /////** //// * @typedef I {Object} -//// * @prop [|{| "isWriteAccess": true, "isDefinition": true |}p|] {number} +//// * @prop [|{| "isDefinition": true |}p|] {number} //// */ //// /////** @type {I} */ diff --git a/tests/cases/fourslash/findAllRefsUnionProperty.ts b/tests/cases/fourslash/findAllRefsUnionProperty.ts index 97b8972c457..3b7813f638b 100644 --- a/tests/cases/fourslash/findAllRefsUnionProperty.ts +++ b/tests/cases/fourslash/findAllRefsUnionProperty.ts @@ -1,8 +1,8 @@ /// ////type T = -//// | { [|{| "isWriteAccess": true, "isDefinition": true |}type|]: "a", [|{| "isWriteAccess": true, "isDefinition": true |}prop|]: number } -//// | { [|{| "isWriteAccess": true, "isDefinition": true |}type|]: "b", [|{| "isWriteAccess": true, "isDefinition": true |}prop|]: string }; +//// | { [|{| "isDefinition": true |}type|]: "a", [|{| "isDefinition": true |}prop|]: number } +//// | { [|{| "isDefinition": true |}type|]: "b", [|{| "isDefinition": true |}prop|]: string }; ////const tt: T = { //// [|{| "isWriteAccess": true, "isDefinition": true |}type|]: "a", //// [|{| "isWriteAccess": true, "isDefinition": true |}prop|]: 0, diff --git a/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames5.ts b/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames5.ts index d54b48bf662..cf171662596 100644 --- a/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames5.ts +++ b/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames5.ts @@ -3,7 +3,7 @@ ////class Foo { //// public _bar; //// public __bar; -//// public [|{| "isWriteAccess": true, "isDefinition": true |}___bar|]; +//// public [|{| "isDefinition": true |}___bar|]; //// public ____bar; ////} //// diff --git a/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames6.ts b/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames6.ts index 39bc1d73ca3..77197480eb1 100644 --- a/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames6.ts +++ b/tests/cases/fourslash/findAllRefsWithLeadingUnderscoreNames6.ts @@ -2,7 +2,7 @@ ////class Foo { //// public _bar; -//// public [|{| "isWriteAccess": true, "isDefinition": true |}__bar|]; +//// public [|{| "isDefinition": true |}__bar|]; //// public ___bar; //// public ____bar; ////} diff --git a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts index 6dbbf9e613b..f19640698cd 100644 --- a/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts +++ b/tests/cases/fourslash/findAllRefsWithShorthandPropertyAssignment2.ts @@ -2,7 +2,7 @@ //// var [|{| "isWriteAccess": true, "isDefinition": true |}dx|] = "Foo"; //// -//// module M { export var [|{| "isWriteAccess": true, "isDefinition": true |}dx|]; } +//// module M { export var [|{| "isDefinition": true |}dx|]; } //// module M { //// var z = 100; //// export var y = { [|{| "isWriteAccess": true, "isDefinition": true |}dx|], z }; diff --git a/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts b/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts index f9feb5ddb62..2141399705f 100644 --- a/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts +++ b/tests/cases/fourslash/findReferencesAcrossMultipleProjects.ts @@ -1,7 +1,7 @@ /// //@Filename: a.ts -////var [|{| "isWriteAccess": true, "isDefinition": true |}x|]: number; +////var [|{| "isDefinition": true |}x|]: number; //@Filename: b.ts /////// diff --git a/tests/cases/fourslash/findReferencesAfterEdit.ts b/tests/cases/fourslash/findReferencesAfterEdit.ts index 599be2255a3..3787617692a 100644 --- a/tests/cases/fourslash/findReferencesAfterEdit.ts +++ b/tests/cases/fourslash/findReferencesAfterEdit.ts @@ -2,7 +2,7 @@ // @Filename: a.ts ////interface A { -//// [|{| "isWriteAccess": true, "isDefinition": true |}foo|]: string; +//// [|{| "isDefinition": true |}foo|]: string; ////} // @Filename: b.ts diff --git a/tests/cases/fourslash/findReferencesJSXTagName3.ts b/tests/cases/fourslash/findReferencesJSXTagName3.ts index 0d5d74b6e2e..58715ade2fa 100644 --- a/tests/cases/fourslash/findReferencesJSXTagName3.ts +++ b/tests/cases/fourslash/findReferencesJSXTagName3.ts @@ -6,7 +6,7 @@ ////namespace JSX { //// export interface Element { } //// export interface IntrinsicElements { -//// [|{| "isWriteAccess": true, "isDefinition": true |}div|]: any; +//// [|{| "isDefinition": true |}div|]: any; //// } ////} //// diff --git a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts index e4c3c93d0e1..88ab38e5428 100644 --- a/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts +++ b/tests/cases/fourslash/getOccurrencesIsDefinitionOfComputedProperty.ts @@ -1,5 +1,5 @@ /// -////let o = { ["[|{| "isDefinition": true |}foo|]"]: 12 }; +////let o = { ["[|{| "isWriteAccess": true, "isDefinition": true |}foo|]"]: 12 }; ////let y = o.[|foo|]; ////let z = o['[|foo|]']; diff --git a/tests/cases/fourslash/referencesForClassMembers.ts b/tests/cases/fourslash/referencesForClassMembers.ts index c2eb8706f59..e60c03524a1 100644 --- a/tests/cases/fourslash/referencesForClassMembers.ts +++ b/tests/cases/fourslash/referencesForClassMembers.ts @@ -1,11 +1,11 @@ /// ////class Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; +//// [|{| "isDefinition": true |}a|]: number; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void { } ////} ////class MyClass extends Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]; +//// [|{| "isDefinition": true |}a|]; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|]() { } ////} //// diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts index 5aaee38d205..12df996629d 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingAbstractClass.ts @@ -1,11 +1,11 @@ /// ////abstract class Base { -//// abstract [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; -//// abstract [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void; +//// abstract [|{| "isDefinition": true |}a|]: number; +//// abstract [|{| "isDefinition": true |}method|](): void; ////} ////class MyClass extends Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]; +//// [|{| "isDefinition": true |}a|]; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|]() { } ////} //// diff --git a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts index 6082033b078..103b66ff74b 100644 --- a/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts +++ b/tests/cases/fourslash/referencesForClassMembersExtendingGenericClass.ts @@ -1,11 +1,11 @@ /// ////class Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: this; +//// [|{| "isDefinition": true |}a|]: this; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|](a?:T, b?:U): this { } ////} ////class MyClass extends Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]; +//// [|{| "isDefinition": true |}a|]; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|]() { } ////} //// diff --git a/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts b/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts index f4e0daaab00..67f09a9dcd1 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedObjectLiteralProperties.ts @@ -1,6 +1,6 @@ /// -////interface IFoo { [|{| "isWriteAccess": true, "isDefinition": true |}xy|]: number; } +////interface IFoo { [|{| "isDefinition": true |}xy|]: number; } //// ////// Assignment ////var a1: IFoo = { [|{| "isWriteAccess": true, "isDefinition": true |}xy|]: 0 }; diff --git a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts index 9ddd31f2fbb..b0bb5d62b4d 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties.ts @@ -2,12 +2,12 @@ ////interface A { //// a: number; -//// [|{| "isWriteAccess": true, "isDefinition": true |}common|]: string; +//// [|{| "isDefinition": true |}common|]: string; ////} //// ////interface B { //// b: number; -//// [|{| "isWriteAccess": true, "isDefinition": true |}common|]: number; +//// [|{| "isDefinition": true |}common|]: number; ////} //// ////// Assignment diff --git a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts index 3ea7cd9b275..a9741d3e39d 100644 --- a/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts +++ b/tests/cases/fourslash/referencesForContextuallyTypedUnionProperties2.ts @@ -6,7 +6,7 @@ ////} //// ////interface B { -//// [|{| "isWriteAccess": true, "isDefinition": true |}b|]: number; +//// [|{| "isDefinition": true |}b|]: number; //// common: number; ////} //// diff --git a/tests/cases/fourslash/referencesForFunctionOverloads.ts b/tests/cases/fourslash/referencesForFunctionOverloads.ts index 7afa5a20133..2a1ea032e20 100644 --- a/tests/cases/fourslash/referencesForFunctionOverloads.ts +++ b/tests/cases/fourslash/referencesForFunctionOverloads.ts @@ -2,7 +2,7 @@ // Function overloads should be highlighted together. -////function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](x: string); +////function [|{| "isDefinition": true |}foo|](x: string); ////function [|{| "isWriteAccess": true, "isDefinition": true |}foo|](x: string, y: number) { //// [|foo|]('', 43); ////} diff --git a/tests/cases/fourslash/referencesForIndexProperty.ts b/tests/cases/fourslash/referencesForIndexProperty.ts index dba2549e414..4bc0b3620ea 100644 --- a/tests/cases/fourslash/referencesForIndexProperty.ts +++ b/tests/cases/fourslash/referencesForIndexProperty.ts @@ -3,7 +3,7 @@ // References a class property using string index access ////class Foo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}property|]: number; +//// [|{| "isDefinition": true |}property|]: number; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void { } ////} //// diff --git a/tests/cases/fourslash/referencesForIndexProperty3.ts b/tests/cases/fourslash/referencesForIndexProperty3.ts index a2e008c937e..69417700ed0 100644 --- a/tests/cases/fourslash/referencesForIndexProperty3.ts +++ b/tests/cases/fourslash/referencesForIndexProperty3.ts @@ -3,7 +3,7 @@ // References to a property of the apparent type using string indexer ////interface Object { -//// [|{| "isWriteAccess": true, "isDefinition": true |}toMyString|](); +//// [|{| "isDefinition": true |}toMyString|](); ////} //// ////var y: Object; diff --git a/tests/cases/fourslash/referencesForInheritedProperties.ts b/tests/cases/fourslash/referencesForInheritedProperties.ts index 808387d18f7..88d7ea7537d 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties.ts @@ -1,11 +1,11 @@ /// ////interface interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}doStuff|](): void; ////} //// ////interface interface2 extends interface1{ -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}doStuff|](): void; ////} //// ////class class1 implements interface2 { diff --git a/tests/cases/fourslash/referencesForInheritedProperties2.ts b/tests/cases/fourslash/referencesForInheritedProperties2.ts index f41fbb7f8db..712c7f2ecf2 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties2.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties2.ts @@ -3,11 +3,11 @@ // extends statement in a diffrent declaration ////interface interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}doStuff|](): void; ////} //// ////interface interface2 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}doStuff|](): void; ////} //// ////interface interface2 extends interface1 { diff --git a/tests/cases/fourslash/referencesForInheritedProperties3.ts b/tests/cases/fourslash/referencesForInheritedProperties3.ts index c6c870ca350..0eabc6cda9e 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties3.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties3.ts @@ -1,8 +1,8 @@ /// //// interface interface1 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// //// var v: interface1; diff --git a/tests/cases/fourslash/referencesForInheritedProperties4.ts b/tests/cases/fourslash/referencesForInheritedProperties4.ts index adf8240ea31..f6a7d48f9d1 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties4.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties4.ts @@ -2,7 +2,7 @@ //// class class1 extends class1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// //// var c: class1; diff --git a/tests/cases/fourslash/referencesForInheritedProperties5.ts b/tests/cases/fourslash/referencesForInheritedProperties5.ts index 12fe3919a1d..232b654c63f 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties5.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties5.ts @@ -1,12 +1,12 @@ /// //// interface interface1 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// interface interface2 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// //// var v: interface1; diff --git a/tests/cases/fourslash/referencesForInheritedProperties7.ts b/tests/cases/fourslash/referencesForInheritedProperties7.ts index 44cf510182a..25402d36b6e 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties7.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties7.ts @@ -2,15 +2,15 @@ //// class class1 extends class1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// interface interface1 extends interface1 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|](): void; -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}doStuff|](): void; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// class class2 extends class1 implements interface1 { //// [|{| "isWriteAccess": true, "isDefinition": true |}doStuff|]() { } -//// [|{| "isWriteAccess": true, "isDefinition": true |}propName|]: string; +//// [|{| "isDefinition": true |}propName|]: string; //// } //// //// var v: class2; diff --git a/tests/cases/fourslash/referencesForInheritedProperties8.ts b/tests/cases/fourslash/referencesForInheritedProperties8.ts index d0d94b49b57..331a90f9181 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties8.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties8.ts @@ -1,11 +1,11 @@ /// //// interface C extends D { -//// [|{| "isWriteAccess": true, "isDefinition": true |}propD|]: number; +//// [|{| "isDefinition": true |}propD|]: number; //// } //// interface D extends C { -//// [|{| "isWriteAccess": true, "isDefinition": true |}propD|]: string; -//// [|{| "isWriteAccess": true, "isDefinition": true |}propC|]: number; +//// [|{| "isDefinition": true |}propD|]: string; +//// [|{| "isDefinition": true |}propC|]: number; //// } //// var d: D; //// d.[|propD|]; diff --git a/tests/cases/fourslash/referencesForInheritedProperties9.ts b/tests/cases/fourslash/referencesForInheritedProperties9.ts index 27bc164a8fc..3648be2f989 100644 --- a/tests/cases/fourslash/referencesForInheritedProperties9.ts +++ b/tests/cases/fourslash/referencesForInheritedProperties9.ts @@ -1,11 +1,11 @@ /// //// class D extends C { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop1|]: string; +//// [|{| "isDefinition": true |}prop1|]: string; //// } //// //// class C extends D { -//// [|{| "isWriteAccess": true, "isDefinition": true |}prop1|]: string; +//// [|{| "isDefinition": true |}prop1|]: string; //// } //// //// var c: C; diff --git a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts index 79dc04ecaee..1f28714daa1 100644 --- a/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForNumericLiteralPropertyNames.ts @@ -1,7 +1,7 @@ /// ////class Foo { -//// public [|{| "isWriteAccess": true, "isDefinition": true |}12|]: any; +//// public [|{| "isDefinition": true |}12|]: any; ////} //// ////var x: Foo; diff --git a/tests/cases/fourslash/referencesForOverrides.ts b/tests/cases/fourslash/referencesForOverrides.ts index ab3d60f1b86..d5d9ea0a6b6 100644 --- a/tests/cases/fourslash/referencesForOverrides.ts +++ b/tests/cases/fourslash/referencesForOverrides.ts @@ -14,16 +14,16 @@ //// //// module SimpleInterfaceTest { //// export interface IFoo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}ifoo|](): void; +//// [|{| "isDefinition": true |}ifoo|](): void; //// } //// export interface IBar extends IFoo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}ifoo|](): void; +//// [|{| "isDefinition": true |}ifoo|](): void; //// } //// } //// //// module SimpleClassInterfaceTest { //// export interface IFoo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}icfoo|](): void; +//// [|{| "isDefinition": true |}icfoo|](): void; //// } //// export class Bar implements IFoo { //// public [|{| "isWriteAccess": true, "isDefinition": true |}icfoo|](): void { @@ -33,29 +33,29 @@ //// //// module Test { //// export interface IBase { -//// [|{| "isWriteAccess": true, "isDefinition": true |}field|]: string; -//// [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void; +//// [|{| "isDefinition": true |}field|]: string; +//// [|{| "isDefinition": true |}method|](): void; //// } //// //// export interface IBlah extends IBase { -//// [|{| "isWriteAccess": true, "isDefinition": true |}field|]: string; +//// [|{| "isDefinition": true |}field|]: string; //// } //// //// export interface IBlah2 extends IBlah { -//// [|{| "isWriteAccess": true, "isDefinition": true |}field|]: string; +//// [|{| "isDefinition": true |}field|]: string; //// } //// //// export interface IDerived extends IBlah2 { -//// [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void; +//// [|{| "isDefinition": true |}method|](): void; //// } //// //// export class Bar implements IDerived { -//// public [|{| "isWriteAccess": true, "isDefinition": true |}field|]: string; +//// public [|{| "isDefinition": true |}field|]: string; //// public [|{| "isWriteAccess": true, "isDefinition": true |}method|](): void { } //// } //// //// export class BarBlah extends Bar { -//// public [|{| "isWriteAccess": true, "isDefinition": true |}field|]: string; +//// public [|{| "isDefinition": true |}field|]: string; //// } //// } //// diff --git a/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts b/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts index a84bdc6315a..be00bb7593f 100644 --- a/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts +++ b/tests/cases/fourslash/referencesForPropertiesOfGenericType.ts @@ -1,7 +1,7 @@ /// ////interface IFoo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}doSomething|](v: T): T; +//// [|{| "isDefinition": true |}doSomething|](v: T): T; ////} //// ////var x: IFoo; diff --git a/tests/cases/fourslash/referencesForStaticsAndMembersWithSameNames.ts b/tests/cases/fourslash/referencesForStaticsAndMembersWithSameNames.ts index 9e7f30f4c49..816b866421a 100644 --- a/tests/cases/fourslash/referencesForStaticsAndMembersWithSameNames.ts +++ b/tests/cases/fourslash/referencesForStaticsAndMembersWithSameNames.ts @@ -3,8 +3,8 @@ ////module FindRef4 { //// module MixedStaticsClassTest { //// export class Foo { -//// [|{| "isWriteAccess": true, "isDefinition": true |}bar|]: Foo; -//// static [|{| "isWriteAccess": true, "isDefinition": true |}bar|]: Foo; +//// [|{| "isDefinition": true |}bar|]: Foo; +//// static [|{| "isDefinition": true |}bar|]: Foo; //// //// public [|{| "isWriteAccess": true, "isDefinition": true |}foo|](): void { //// } diff --git a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts index 5c98eddadce..88c9a74bc6e 100644 --- a/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts +++ b/tests/cases/fourslash/referencesForStringLiteralPropertyNames.ts @@ -1,7 +1,7 @@ /// ////class Foo { -//// public "[|{| "isWriteAccess": true, "isDefinition": true |}ss|]": any; +//// public "[|{| "isDefinition": true |}ss|]": any; ////} //// ////var x: Foo; diff --git a/tests/cases/fourslash/referencesForUnionProperties.ts b/tests/cases/fourslash/referencesForUnionProperties.ts index b8e24dfae1c..7efff1aabd0 100644 --- a/tests/cases/fourslash/referencesForUnionProperties.ts +++ b/tests/cases/fourslash/referencesForUnionProperties.ts @@ -1,16 +1,16 @@ /// ////interface One { -//// common: { [|{| "isWriteAccess": true, "isDefinition": true |}a|]: number; }; +//// common: { [|{| "isDefinition": true |}a|]: number; }; ////} //// ////interface Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string; +//// [|{| "isDefinition": true |}a|]: string; //// b: string; ////} //// ////interface HasAOrB extends Base { -//// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: string; +//// [|{| "isDefinition": true |}a|]: string; //// b: string; ////} //// diff --git a/tests/cases/fourslash/renameImportAndExportInDiffFiles.ts b/tests/cases/fourslash/renameImportAndExportInDiffFiles.ts index a961ebf2411..96d423529c2 100644 --- a/tests/cases/fourslash/renameImportAndExportInDiffFiles.ts +++ b/tests/cases/fourslash/renameImportAndExportInDiffFiles.ts @@ -1,7 +1,7 @@ /// // @Filename: a.ts -////export var [|{| "isWriteAccess": true, "isDefinition": true |}a|]; +////export var [|{| "isDefinition": true |}a|]; // @Filename: b.ts ////import { [|{| "isWriteAccess": true, "isDefinition": true |}a|] } from './a'; diff --git a/tests/cases/fourslash/tsxFindAllReferences10.ts b/tests/cases/fourslash/tsxFindAllReferences10.ts index 04ac864e4f2..58459c7df1f 100644 --- a/tests/cases/fourslash/tsxFindAllReferences10.ts +++ b/tests/cases/fourslash/tsxFindAllReferences10.ts @@ -15,7 +15,7 @@ //// className?: string; //// } //// interface ButtonProps extends ClickableProps { -//// [|{| "isWriteAccess": true, "isDefinition": true |}onClick|](event?: React.MouseEvent): void; +//// [|{| "isDefinition": true |}onClick|](event?: React.MouseEvent): void; //// } //// interface LinkProps extends ClickableProps { //// goTo: string; diff --git a/tests/cases/fourslash/tsxFindAllReferences3.ts b/tests/cases/fourslash/tsxFindAllReferences3.ts index 2682e01e7d1..e2f9215466a 100644 --- a/tests/cases/fourslash/tsxFindAllReferences3.ts +++ b/tests/cases/fourslash/tsxFindAllReferences3.ts @@ -9,7 +9,7 @@ //// } //// class MyClass { //// props: { -//// [|{| "isWriteAccess": true, "isDefinition": true |}name|]?: string; +//// [|{| "isDefinition": true |}name|]?: string; //// size?: number; //// } //// diff --git a/tests/cases/fourslash/tsxFindAllReferences7.ts b/tests/cases/fourslash/tsxFindAllReferences7.ts index 37ea60c7a38..471cf747258 100644 --- a/tests/cases/fourslash/tsxFindAllReferences7.ts +++ b/tests/cases/fourslash/tsxFindAllReferences7.ts @@ -11,7 +11,7 @@ //// interface ElementAttributesProperty { props; } //// } //// interface OptionPropBag { -//// [|{| "isWriteAccess": true, "isDefinition": true |}propx|]: number +//// [|{| "isDefinition": true |}propx|]: number //// propString: string //// optional?: boolean //// } diff --git a/tests/cases/fourslash/tsxFindAllReferences9.ts b/tests/cases/fourslash/tsxFindAllReferences9.ts index 9fe02500ad9..bb45ce590cf 100644 --- a/tests/cases/fourslash/tsxFindAllReferences9.ts +++ b/tests/cases/fourslash/tsxFindAllReferences9.ts @@ -18,7 +18,7 @@ //// onClick(event?: React.MouseEvent): void; //// } //// interface LinkProps extends ClickableProps { -//// [|{| "isWriteAccess": true, "isDefinition": true |}goTo|]: string; +//// [|{| "isDefinition": true |}goTo|]: string; //// } //// declare function MainButton(buttonProps: ButtonProps): JSX.Element; //// declare function MainButton(linkProps: LinkProps): JSX.Element; From 88d5b04c70cb41c10dad41183eb3235e8fcc4d2f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 6 Sep 2018 13:26:44 -0700 Subject: [PATCH 058/146] Lowercase type reference directives when determining to reuse program structure (just like when we create new program) --- src/compiler/program.ts | 3 +- .../unittests/tsserverProjectSystem.ts | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c129d75f156..c97f1a61d27 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1178,7 +1178,8 @@ namespace ts { } } if (resolveTypeReferenceDirectiveNamesWorker) { - const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, x => x.fileName); + // We lower-case all type references because npm automatically lowercases all packages. See GH#9824. + const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => ref.fileName.toLocaleLowerCase()); const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath); // ensure that types resolutions are still correct const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index a1e0c0932b2..7114759b097 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -9555,6 +9555,65 @@ export function Test2() { }); }); + describe("tsserverProjectSystem typeReferenceDirectives", () => { + it("when typeReferenceDirective contains UpperCasePackage", () => { + const projectLocation = "/user/username/projects/myproject"; + const libProjectLocation = `${projectLocation}/lib`; + const typeLib: File = { + path: `${libProjectLocation}/@types/UpperCasePackage/index.d.ts`, + content: `declare class BrokenTest { + constructor(name: string, width: number, height: number, onSelect: Function); + Name: string; + SelectedFile: string; +}` + }; + const appLib: File = { + path: `${libProjectLocation}/@app/lib/index.d.ts`, + content: `/// +declare class TestLib { + issue: BrokenTest; + constructor(); + test(): void; +}` + }; + const testProjectLocation = `${projectLocation}/test`; + const testFile: File = { + path: `${testProjectLocation}/test.ts`, + content: `class TestClass1 { + + constructor() { + var l = new TestLib(); + + } + + public test2() { + var x = new BrokenTest('',0,0,null); + + } +}` + }; + const testConfig: File = { + path: `${testProjectLocation}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "amd", + typeRoots: ["../lib/@types", "../lib/@app"] + } + }) + }; + + const files = [typeLib, appLib, testFile, testConfig, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(testFile.path); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project = service.configuredProjects.get(testConfig.path)!; + checkProjectActualFiles(project, files.map(f => f.path)); + host.writeFile(appLib.path, appLib.content.replace("test()", "test2()")); + host.checkTimeoutQueueLengthAndRun(2); + }); + }); + describe("tsserverProjectSystem project references", () => { const aTs: File = { path: "/a/a.ts", From a0ebbfb8f06a9e5648555d0eaa7c2541ba1e7cc1 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 6 Sep 2018 14:15:12 -0700 Subject: [PATCH 059/146] Fix JSX completions after boolean property (#26943) --- src/services/completions.ts | 5 ++++- .../cases/fourslash/completionsJsxAttribute.ts | 17 ++++++++++++----- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 1e74ea3bbf1..3edc1cc4f56 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -986,7 +986,10 @@ namespace ts.Completions { break; case SyntaxKind.Identifier: // For `
` we don't want to treat this as a jsx inializer, instead it's the attribute name. + if (parent !== previousToken.parent && + !(parent as JsxAttribute).initializer && + findChildOfKind(parent, SyntaxKind.EqualsToken, sourceFile)) { isJsxInitializer = previousToken as Identifier; } } diff --git a/tests/cases/fourslash/completionsJsxAttribute.ts b/tests/cases/fourslash/completionsJsxAttribute.ts index 75bf20c7488..c4d1513a6ee 100644 --- a/tests/cases/fourslash/completionsJsxAttribute.ts +++ b/tests/cases/fourslash/completionsJsxAttribute.ts @@ -8,15 +8,22 @@ //// interface IntrinsicElements { //// div: { //// /** Doc */ -//// foo: string +//// foo: boolean; +//// bar: string; //// } //// } ////} //// ////
; -goTo.marker(); -verify.completionEntryDetailIs("foo", "(JSX attribute) foo: string", "Doc", "JSX attribute", []); +const exact: ReadonlyArray = [ + { name: "foo", kind: "JSX attribute", text: "(JSX attribute) foo: boolean", documentation: "Doc" }, + { name: "bar", kind: "JSX attribute", text: "(JSX attribute) bar: string" }, +]; +verify.completions({ marker: "", exact }); edit.insert("f"); -verify.completionEntryDetailIs("foo", "(JSX attribute) foo: string", "Doc", "JSX attribute", []); - +verify.completions({ exact }); +edit.insert("oo "); +verify.completions({ exact: exact[1] }); +edit.insert("b"); +verify.completions({ exact: exact[1] }); From c401d63c5f0fb937ce53f499ba3872b24470b0fc Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 6 Sep 2018 15:24:07 -0700 Subject: [PATCH 060/146] findAllReferences: Fix declarationIsWriteAccess for PropertyAssignment in destructuring (#26949) --- src/services/findAllReferences.ts | 5 ++++- .../findAllRefsObjectBindingElementPropertyName07.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index bcc68162746..81970322c21 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -255,12 +255,15 @@ namespace ts.FindAllReferences { case SyntaxKind.NamespaceExportDeclaration: case SyntaxKind.NamespaceImport: case SyntaxKind.Parameter: - case SyntaxKind.PropertyAssignment: case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.TypeAliasDeclaration: case SyntaxKind.TypeParameter: return true; + case SyntaxKind.PropertyAssignment: + // In `({ x: y } = 0);`, `x` is not a write access. (Won't call this function for `y`.) + return !isArrayLiteralOrObjectLiteralDestructuringPattern((decl as PropertyAssignment).parent); + case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.Constructor: diff --git a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName07.ts b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName07.ts index 69d1f6ac2ff..18fa4e43273 100644 --- a/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName07.ts +++ b/tests/cases/fourslash/findAllRefsObjectBindingElementPropertyName07.ts @@ -2,6 +2,6 @@ ////let p, b; //// -////p, [{ [|{| "isWriteAccess": true, "isDefinition": true |}a|]: p, b }] = [{ [|{| "isWriteAccess": true, "isDefinition": true |}a|]: 10, b: true }]; +////p, [{ [|{| "isDefinition": true |}a|]: p, b }] = [{ [|{| "isWriteAccess": true, "isDefinition": true |}a|]: 10, b: true }]; verify.singleReferenceGroup("(property) a: any"); From d31973b905c1021374442221064b828eb5154b82 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 6 Sep 2018 17:06:50 -0700 Subject: [PATCH 061/146] findAllReferences: Consistently use 'this' parameter as definition site (#26950) --- src/services/findAllReferences.ts | 36 ++++++++++--------- .../cases/fourslash/findAllRefsThisKeyword.ts | 6 ++-- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 81970322c21..b857a05dffb 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -5,12 +5,13 @@ namespace ts.FindAllReferences { references: Entry[]; } + export const enum DefinitionKind { Symbol, Label, Keyword, This, String } export type Definition = - | { type: "symbol"; symbol: Symbol } - | { type: "label"; node: Identifier } - | { type: "keyword"; node: Node } - | { type: "this"; node: Node } - | { type: "string"; node: StringLiteral }; + | { readonly type: DefinitionKind.Symbol; readonly symbol: Symbol } + | { readonly type: DefinitionKind.Label; readonly node: Identifier } + | { readonly type: DefinitionKind.Keyword; readonly node: Node } + | { readonly type: DefinitionKind.This; readonly node: Node } + | { readonly type: DefinitionKind.String; readonly node: StringLiteral }; export type Entry = NodeEntry | SpanEntry; export interface NodeEntry { @@ -98,29 +99,29 @@ namespace ts.FindAllReferences { function definitionToReferencedSymbolDefinitionInfo(def: Definition, checker: TypeChecker, originalNode: Node): ReferencedSymbolDefinitionInfo { const info = (() => { switch (def.type) { - case "symbol": { + case DefinitionKind.Symbol: { const { symbol } = def; const { displayParts, kind } = getDefinitionKindAndDisplayParts(symbol, checker, originalNode); const name = displayParts.map(p => p.text).join(""); return { node: symbol.declarations ? getNameOfDeclaration(first(symbol.declarations)) || first(symbol.declarations) : originalNode, name, kind, displayParts }; } - case "label": { + case DefinitionKind.Label: { const { node } = def; return { node, name: node.text, kind: ScriptElementKind.label, displayParts: [displayPart(node.text, SymbolDisplayPartKind.text)] }; } - case "keyword": { + case DefinitionKind.Keyword: { const { node } = def; const name = tokenToString(node.kind)!; return { node, name, kind: ScriptElementKind.keyword, displayParts: [{ text: name, kind: ScriptElementKind.keyword }] }; } - case "this": { + case DefinitionKind.This: { const { node } = def; const symbol = checker.getSymbolAtLocation(node); const displayParts = symbol && SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind( checker, symbol, node.getSourceFile(), getContainerNode(node), node).displayParts || [textPart("this")]; return { node, name: "this", kind: ScriptElementKind.variableElement, displayParts }; } - case "string": { + case DefinitionKind.String: { const { node } = def; return { node, name: node.text, kind: ScriptElementKind.variableElement, displayParts: [displayPart(getTextOfNode(node), SymbolDisplayPartKind.stringLiteral)] }; } @@ -374,7 +375,7 @@ namespace ts.FindAllReferences.Core { } } - return references.length ? [{ definition: { type: "symbol", symbol }, references }] : emptyArray; + return references.length ? [{ definition: { type: DefinitionKind.Symbol, symbol }, references }] : emptyArray; } /** getReferencedSymbols for special node kinds. */ @@ -585,7 +586,7 @@ namespace ts.FindAllReferences.Core { let references = this.symbolIdToReferences[symbolId]; if (!references) { references = this.symbolIdToReferences[symbolId] = []; - this.result.push({ definition: { type: "symbol", symbol: searchSymbol }, references }); + this.result.push({ definition: { type: DefinitionKind.Symbol, symbol: searchSymbol }, references }); } return node => references.push(nodeEntry(node)); } @@ -879,7 +880,7 @@ namespace ts.FindAllReferences.Core { const references = mapDefined(getPossibleSymbolReferenceNodes(sourceFile, labelName, container), node => // Only pick labels that are either the target label, or have a target that is the target label node === targetLabel || (isJumpStatementTarget(node) && getTargetLabel(node, labelName) === targetLabel) ? nodeEntry(node) : undefined); - return [{ definition: { type: "label", node: targetLabel }, references }]; + return [{ definition: { type: DefinitionKind.Label, node: targetLabel }, references }]; } function isValidReferencePosition(node: Node, searchSymbolName: string): boolean { @@ -911,7 +912,7 @@ namespace ts.FindAllReferences.Core { return mapDefined(getPossibleSymbolReferenceNodes(sourceFile, tokenToString(keywordKind)!, sourceFile), referenceLocation => referenceLocation.kind === keywordKind ? nodeEntry(referenceLocation) : undefined); }); - return references.length ? [{ definition: { type: "keyword", node: references[0].node }, references }] : undefined; + return references.length ? [{ definition: { type: DefinitionKind.Keyword, node: references[0].node }, references }] : undefined; } function getReferencesInSourceFile(sourceFile: SourceFile, search: Search, state: State, addReferencesHere = true): void { @@ -1353,7 +1354,7 @@ namespace ts.FindAllReferences.Core { return container && (ModifierFlags.Static & getModifierFlags(container)) === staticFlag && container.parent.symbol === searchSpaceNode.symbol ? nodeEntry(node) : undefined; }); - return [{ definition: { type: "symbol", symbol: searchSpaceNode.symbol }, references }]; + return [{ definition: { type: DefinitionKind.Symbol, symbol: searchSpaceNode.symbol }, references }]; } function getReferencesForThisKeyword(thisOrSuperKeyword: Node, sourceFiles: ReadonlyArray, cancellationToken: CancellationToken): SymbolAndEntries[] | undefined { @@ -1416,8 +1417,9 @@ namespace ts.FindAllReferences.Core { }); }).map(n => nodeEntry(n)); + const thisParameter = firstDefined(references, r => isParameter(r.node.parent) ? r.node : undefined); return [{ - definition: { type: "this", node: thisOrSuperKeyword }, + definition: { type: DefinitionKind.This, node: thisParameter || thisOrSuperKeyword }, references }]; } @@ -1430,7 +1432,7 @@ namespace ts.FindAllReferences.Core { }); return [{ - definition: { type: "string", node }, + definition: { type: DefinitionKind.String, node }, references }]; } diff --git a/tests/cases/fourslash/findAllRefsThisKeyword.ts b/tests/cases/fourslash/findAllRefsThisKeyword.ts index 975b4b37ac2..34995467a27 100644 --- a/tests/cases/fourslash/findAllRefsThisKeyword.ts +++ b/tests/cases/fourslash/findAllRefsThisKeyword.ts @@ -26,10 +26,8 @@ const [global, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); verify.singleReferenceGroup("this", [global]); -verify.referenceGroups(f0, [{ definition: "(parameter) this: any", ranges: [f0, f1] }]); -verify.referenceGroups(f1, [{ definition: "this: any", ranges: [f0, f1] }]); -verify.referenceGroups(g0, [{ definition: "(parameter) this: any", ranges: [g0, g1] }]); -verify.referenceGroups(g1, [{ definition: "this: any", ranges: [g0, g1] }]); +verify.singleReferenceGroup("(parameter) this: any", [f0, f1]); +verify.singleReferenceGroup("(parameter) this: any", [g0, g1]); verify.singleReferenceGroup("this: typeof C", [x, y]); verify.singleReferenceGroup("this: this", [constructor, method]); verify.singleReferenceGroup("(property) this: number", [propDef, propUse]); From ec72f4751d0986690440dad7be2d6b8d86a65da9 Mon Sep 17 00:00:00 2001 From: christian Date: Thu, 6 Sep 2018 20:40:02 -0400 Subject: [PATCH 062/146] Add location info to empty lists diagnostics when tsconfig file exists --- src/compiler/commandLineParser.ts | 9 ++++++++- src/testRunner/unittests/tsconfigParsing.ts | 6 ++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index a2dac4e7d33..ecc69fccf86 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1846,7 +1846,14 @@ namespace ts { const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; if (filesSpecs.length === 0 && hasZeroOrNoReferences) { - errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json")); + if (sourceFile) { + const nodeValue = firstDefined(getTsConfigPropArray(sourceFile, "files"), property => property.initializer); + const error = createDiagnosticForNodeInSourceFile(sourceFile, nodeValue!, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + errors.push(error); + } + else { + createCompilerDiagnosticOnlyIfJson(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + } } } else { diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/tsconfigParsing.ts index c2e8f0eb10d..6909e260d2a 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/tsconfigParsing.ts @@ -290,8 +290,7 @@ namespace ts { "/apath/tsconfig.json", "tests/cases/unittests", ["/apath/a.ts"], - Diagnostics.The_files_list_in_config_file_0_is_empty.code, - /*noLocation*/ true); + Diagnostics.The_files_list_in_config_file_0_is_empty.code); }); it("generates errors for empty files list when no references are provided", () => { @@ -303,8 +302,7 @@ namespace ts { "/apath/tsconfig.json", "tests/cases/unittests", ["/apath/a.ts"], - Diagnostics.The_files_list_in_config_file_0_is_empty.code, - /*noLocation*/ true); + Diagnostics.The_files_list_in_config_file_0_is_empty.code); }); it("does not generate errors for empty files list when one or more references are provided", () => { From f8b6a8fc8d5a1196981d9929429f0c18cd78ac41 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 7 Sep 2018 12:09:07 -0700 Subject: [PATCH 063/146] Introduce literal freshness for literal enum member types (#26556) * Introduce literal freshness for literal enum members, allow enum references in ambient const initializers * Merge statements * Add enum literal readonly property test case * Accept better baselines post-merge --- src/compiler/checker.ts | 26 +++++--- src/compiler/diagnosticMessages.json | 2 +- .../reference/ambientConstLiterals.js | 11 +++- .../reference/ambientConstLiterals.symbols | 22 ++++--- .../reference/ambientConstLiterals.types | 9 ++- tests/baselines/reference/ambientEnum1.types | 2 +- .../ambientEnumElementInitializer1.types | 2 +- .../ambientEnumElementInitializer2.types | 2 +- .../ambientEnumElementInitializer3.types | 2 +- .../ambientEnumElementInitializer4.types | 2 +- .../ambientEnumElementInitializer5.types | 2 +- .../ambientEnumElementInitializer6.types | 2 +- tests/baselines/reference/ambientErrors.types | 2 +- .../anyAssignabilityInInheritance.types | 2 +- .../reference/anyAssignableToEveryType.types | 2 +- .../reference/anyAssignableToEveryType2.types | 2 +- .../reference/assignAnyToEveryType.types | 2 +- .../reference/assignEveryTypeToAny.types | 2 +- ...assignmentToParenthesizedIdentifiers.types | 2 +- tests/baselines/reference/assignments.types | 2 +- tests/baselines/reference/asyncEnum_es5.types | 2 +- tests/baselines/reference/asyncEnum_es6.types | 2 +- .../reference/augmentedTypesClass.types | 2 +- .../reference/augmentedTypesClass2.types | 2 +- .../reference/augmentedTypesEnum.types | 22 +++---- .../reference/augmentedTypesEnum2.types | 4 +- .../reference/augmentedTypesEnum3.types | 4 +- .../reference/augmentedTypesFunction.types | 2 +- .../reference/augmentedTypesInterface.types | 2 +- .../reference/augmentedTypesModules.types | 8 +-- .../reference/augmentedTypesModules4.types | 8 +-- .../reference/augmentedTypesVar.types | 2 +- .../reference/bestCommonTypeOfTuple.types | 12 ++-- ...blockScopedEnumVariablesUseBeforeDef.types | 4 +- ...edEnumVariablesUseBeforeDef_preserve.types | 4 +- ...WithoutReturnTypeAnnotationInference.types | 2 +- tests/baselines/reference/castingTuple.types | 6 +- .../reference/classExtendingPrimitive.types | 2 +- ...lizersUsePropertiesBeforeDeclaration.types | 2 +- ...ionCodeGenEnumWithEnumMemberConflict.types | 4 +- ...nCodeGenModuleWithEnumMemberConflict.types | 4 +- .../computedPropertyNames47_ES5.types | 4 +- .../computedPropertyNames47_ES6.types | 4 +- .../computedPropertyNames48_ES5.types | 2 +- .../computedPropertyNames48_ES6.types | 2 +- .../computedPropertyNames7_ES5.types | 2 +- .../computedPropertyNames7_ES6.types | 2 +- ...onstDeclarations-ambient-errors.errors.txt | 4 +- .../reference/constEnumBadPropertyNames.types | 2 +- .../baselines/reference/constEnumErrors.types | 4 +- .../reference/constEnumExternalModule.types | 2 +- .../constEnumMergingWithValues1.types | 2 +- .../constEnumMergingWithValues2.types | 2 +- .../constEnumMergingWithValues3.types | 4 +- .../constEnumMergingWithValues4.types | 2 +- .../constEnumMergingWithValues5.types | 2 +- .../constEnumOnlyModuleMerging.types | 2 +- ...larationEmitClassMemberNameConflict2.types | 4 +- .../declarationEmitEnumReadonlyProperty.js | 36 +++++++++++ ...eclarationEmitEnumReadonlyProperty.symbols | 29 +++++++++ .../declarationEmitEnumReadonlyProperty.types | 31 ++++++++++ .../declarationEmitNameConflicts3.types | 2 +- ...estructuringParameterDeclaration1ES5.types | 2 +- ...ringParameterDeclaration1ES5iterable.types | 2 +- ...estructuringParameterDeclaration1ES6.types | 2 +- .../reference/duplicateIdentifierEnum.types | 8 +-- .../reference/duplicateLocalVariable4.types | 2 +- .../duplicatePackage_withErrors.errors.txt | 4 +- .../reference/enumAssignability.types | 4 +- .../enumAssignabilityInInheritance.types | 4 +- .../reference/enumAssignmentCompat4.types | 4 +- tests/baselines/reference/enumBasics.types | 4 +- .../reference/enumClassification.types | 6 +- .../enumConflictsWithGlobalIdentifier.types | 2 +- .../enumConstantMemberWithString.types | 4 +- ...stantMemberWithStringEmitDeclaration.types | 4 +- tests/baselines/reference/enumErrors.types | 4 +- .../reference/enumFromExternalModule.types | 2 +- .../reference/enumGenericTypeClash.types | 2 +- ...enumIsNotASubtypeOfAnythingButNumber.types | 4 +- .../reference/enumLiteralUnionNotWidened.js | 48 +++++++++++++++ .../enumLiteralUnionNotWidened.symbols | 61 +++++++++++++++++++ .../enumLiteralUnionNotWidened.types | 54 ++++++++++++++++ .../reference/enumMemberResolution.types | 2 +- .../reference/enumMergingErrors.types | 12 ++-- .../baselines/reference/enumOperations.types | 2 +- .../reference/enumWithInfinityProperty.types | 2 +- .../reference/enumWithNaNProperty.types | 2 +- .../enumWithNegativeInfinityProperty.types | 2 +- .../enumWithQuotedElementName1.types | 2 +- .../enumWithQuotedElementName2.types | 2 +- .../reference/enumWithUnicodeEscape1.types | 2 +- .../enumsWithMultipleDeclarations1.types | 6 +- .../enumsWithMultipleDeclarations3.types | 2 +- .../es6modulekindWithES5Target5.types | 4 +- .../esnextmodulekindWithES5Target5.types | 4 +- .../reference/everyTypeAssignableToAny.types | 2 +- tests/baselines/reference/exportCodeGen.types | 4 +- tests/baselines/reference/for-of47.types | 2 +- tests/baselines/reference/for-of48.types | 2 +- ...icCallWithGenericSignatureArguments2.types | 8 +-- ...icCallWithGenericSignatureArguments3.types | 4 +- .../inOperatorWithInvalidOperands.types | 2 +- .../interfaceWithPropertyOfEveryType.types | 6 +- .../reference/invalidBooleanAssignments.types | 2 +- .../reference/invalidStringAssignments.types | 2 +- .../invalidUndefinedAssignments.types | 2 +- .../reference/invalidUndefinedValues.types | 2 +- .../reference/invalidVoidAssignments.types | 2 +- .../reference/invalidVoidValues.types | 2 +- .../isolatedModulesAmbientConstEnum.types | 2 +- .../isolatedModulesNonAmbientConstEnum.types | 2 +- .../reference/jsdocAccessEnumType.types | 2 +- .../logicalOrOperatorWithEveryType.types | 14 ++--- .../reference/mergeWithImportedType.types | 2 +- .../reference/mergedDeclarations2.types | 4 +- .../mergedEnumDeclarationCodeGen.types | 6 +- .../reference/moduleCodeGenTest5.types | 4 +- .../reference/noImplicitAnyIndexing.types | 2 +- .../noImplicitAnyIndexingSuppressed.types | 2 +- .../nonExportedElementsOfMergedModules.types | 4 +- .../reference/nullAssignableToEveryType.types | 2 +- ...ullIsSubtypeOfEverythingButUndefined.types | 2 +- .../reference/numberAssignableToEnum.types | 2 +- .../reference/objectTypesIdentity2.types | 2 +- .../operatorAddNullUndefined.errors.txt | 16 ++--- .../reference/operatorAddNullUndefined.types | 2 +- .../parseEntityNameWithReservedWord.types | 2 +- .../parserComputedPropertyName16.types | 2 +- .../parserES5ComputedPropertyName6.types | 2 +- tests/baselines/reference/parserEnum5.types | 2 +- .../reference/parserEnumDeclaration3.d.types | 2 +- .../reference/parserEnumDeclaration3.types | 2 +- .../parserInterfaceKeywordInEnum.types | 2 +- .../parserInterfaceKeywordInEnum1.types | 2 +- .../reference/preserveConstEnums.types | 4 +- .../reference/primtiveTypesAreIdentical.types | 2 +- .../reference/reachabilityChecks1.types | 6 +- .../reference/reachabilityChecks2.types | 4 +- .../strictModeEnumMemberNameReserved.types | 2 +- .../stringLiteralTypeIsSubtypeOfString.types | 2 +- tests/baselines/reference/subtypesOfAny.types | 2 +- .../reference/subtypesOfTypeParameter.types | 2 +- ...typesOfTypeParameterWithConstraints2.types | 2 +- .../systemModuleAmbientDeclarations.types | 4 +- .../reference/systemModuleConstEnums.types | 4 +- ...mModuleConstEnumsSeparateCompilation.types | 4 +- ...systemModuleNonTopLevelModuleMembers.types | 4 +- .../reference/tsxDefaultImports.types | 2 +- tests/baselines/reference/typeAliases.types | 2 +- ...peArgumentInferenceWithObjectLiteral.types | 12 ++-- .../reference/typeofANonExportedType.types | 2 +- .../reference/typeofAnExportedType.types | 2 +- .../undefinedAssignableToEveryType.types | 2 +- .../undefinedIsSubtypeOfEverything.types | 2 +- ...btypeIfEveryConstituentTypeIsSubtype.types | 2 +- .../reference/validNullAssignments.types | 2 +- .../reference/validNumberAssignments.types | 2 +- tests/cases/compiler/ambientConstLiterals.ts | 3 +- .../declarationEmitEnumReadonlyProperty.ts | 11 ++++ .../compiler/enumLiteralUnionNotWidened.ts | 20 ++++++ 161 files changed, 583 insertions(+), 266 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitEnumReadonlyProperty.js create mode 100644 tests/baselines/reference/declarationEmitEnumReadonlyProperty.symbols create mode 100644 tests/baselines/reference/declarationEmitEnumReadonlyProperty.types create mode 100644 tests/baselines/reference/enumLiteralUnionNotWidened.js create mode 100644 tests/baselines/reference/enumLiteralUnionNotWidened.symbols create mode 100644 tests/baselines/reference/enumLiteralUnionNotWidened.types create mode 100644 tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts create mode 100644 tests/cases/compiler/enumLiteralUnionNotWidened.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e24984a6340..bf7bb9a811f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5907,9 +5907,9 @@ namespace ts { for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.EnumDeclaration) { for (const member of (declaration).members) { - const memberType = getLiteralType(getEnumMemberValue(member)!, enumCount, getSymbolOfNode(member)); // TODO: GH#18217 + const memberType = getFreshTypeOfLiteralType(getLiteralType(getEnumMemberValue(member)!, enumCount, getSymbolOfNode(member))); // TODO: GH#18217 getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType; - memberTypeList.push(memberType); + memberTypeList.push(getRegularTypeOfLiteralType(memberType)); } } } @@ -8242,7 +8242,7 @@ namespace ts { const res = tryGetDeclaredTypeOfSymbol(symbol); if (res) { return checkNoTypeArguments(node, symbol) ? - res.flags & TypeFlags.TypeParameter ? getConstrainedTypeVariable(res, node) : res : + res.flags & TypeFlags.TypeParameter ? getConstrainedTypeVariable(res, node) : getRegularTypeOfLiteralType(res) : errorType; } @@ -12736,7 +12736,7 @@ namespace ts { } function getWidenedLiteralType(type: Type): Type { - return type.flags & TypeFlags.EnumLiteral ? getBaseTypeOfEnumLiteralType(type) : + return type.flags & TypeFlags.EnumLiteral && type.flags & TypeFlags.FreshLiteral ? getBaseTypeOfEnumLiteralType(type) : type.flags & TypeFlags.StringLiteral && type.flags & TypeFlags.FreshLiteral ? stringType : type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : @@ -28274,13 +28274,14 @@ namespace ts { return false; } - function literalTypeToNode(type: LiteralType): Expression { - return createLiteral(type.value); + function literalTypeToNode(type: LiteralType, enclosing: Node): Expression { + const enumResult = type.flags & TypeFlags.EnumLiteral && nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing); + return enumResult || createLiteral(type.value); } function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - return literalTypeToNode(type); + return literalTypeToNode(type, node); } function createResolver(): EmitResolver { @@ -29643,13 +29644,20 @@ namespace ts { (expr).operand.kind === SyntaxKind.NumericLiteral; } + function isSimpleLiteralEnumReference(expr: Expression) { + if ( + (isPropertyAccessExpression(expr) || (isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) && + isEntityNameExpression(expr.expression) + ) return !!(checkExpressionCached(expr).flags & TypeFlags.EnumLiteral); + } + function checkAmbientInitializer(node: VariableDeclaration | PropertyDeclaration | PropertySignature) { if (node.initializer) { - const isInvalidInitializer = !isStringOrNumberLiteralExpression(node.initializer); + const isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(node.initializer)); const isConstOrReadonly = isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConst(node); if (isConstOrReadonly && !node.type) { if (isInvalidInitializer) { - return grammarErrorOnNode(node.initializer!, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal); + return grammarErrorOnNode(node.initializer!, Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference); } } else { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4057a5528aa..d3824361090 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -835,7 +835,7 @@ "category": "Error", "code": 1253 }, - "A 'const' initializer in an ambient context must be a string or numeric literal.": { + "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.": { "category": "Error", "code": 1254 }, diff --git a/tests/baselines/reference/ambientConstLiterals.js b/tests/baselines/reference/ambientConstLiterals.js index 7c7da7321c3..b0b222128ac 100644 --- a/tests/baselines/reference/ambientConstLiterals.js +++ b/tests/baselines/reference/ambientConstLiterals.js @@ -3,7 +3,7 @@ function f(x: T): T { return x; } -enum E { A, B, C } +enum E { A, B, C, "non identifier" } const c1 = "abc"; const c2 = 123; @@ -13,6 +13,7 @@ const c5 = f(123); const c6 = f(-123); const c7 = true; const c8 = E.A; +const c8b = E["non identifier"]; const c9 = { x: "abc" }; const c10 = [123]; const c11 = "abc" + "def"; @@ -29,6 +30,7 @@ var E; E[E["A"] = 0] = "A"; E[E["B"] = 1] = "B"; E[E["C"] = 2] = "C"; + E[E["non identifier"] = 3] = "non identifier"; })(E || (E = {})); var c1 = "abc"; var c2 = 123; @@ -38,6 +40,7 @@ var c5 = f(123); var c6 = f(-123); var c7 = true; var c8 = E.A; +var c8b = E["non identifier"]; var c9 = { x: "abc" }; var c10 = [123]; var c11 = "abc" + "def"; @@ -51,7 +54,8 @@ declare function f(x: T): T; declare enum E { A = 0, B = 1, - C = 2 + C = 2, + "non identifier" = 3 } declare const c1 = "abc"; declare const c2 = 123; @@ -60,7 +64,8 @@ declare const c4 = 123; declare const c5 = 123; declare const c6 = -123; declare const c7: boolean; -declare const c8: E; +declare const c8 = E.A; +declare const c8b = E["non identifier"]; declare const c9: { x: string; }; diff --git a/tests/baselines/reference/ambientConstLiterals.symbols b/tests/baselines/reference/ambientConstLiterals.symbols index 905ec3fd4fd..482300a3218 100644 --- a/tests/baselines/reference/ambientConstLiterals.symbols +++ b/tests/baselines/reference/ambientConstLiterals.symbols @@ -10,11 +10,12 @@ function f(x: T): T { >x : Symbol(x, Decl(ambientConstLiterals.ts, 0, 14)) } -enum E { A, B, C } +enum E { A, B, C, "non identifier" } >E : Symbol(E, Decl(ambientConstLiterals.ts, 2, 1)) >A : Symbol(E.A, Decl(ambientConstLiterals.ts, 4, 8)) >B : Symbol(E.B, Decl(ambientConstLiterals.ts, 4, 11)) >C : Symbol(E.C, Decl(ambientConstLiterals.ts, 4, 14)) +>"non identifier" : Symbol(E["non identifier"], Decl(ambientConstLiterals.ts, 4, 17)) const c1 = "abc"; >c1 : Symbol(c1, Decl(ambientConstLiterals.ts, 6, 5)) @@ -47,27 +48,32 @@ const c8 = E.A; >E : Symbol(E, Decl(ambientConstLiterals.ts, 2, 1)) >A : Symbol(E.A, Decl(ambientConstLiterals.ts, 4, 8)) +const c8b = E["non identifier"]; +>c8b : Symbol(c8b, Decl(ambientConstLiterals.ts, 14, 5)) +>E : Symbol(E, Decl(ambientConstLiterals.ts, 2, 1)) +>"non identifier" : Symbol(E["non identifier"], Decl(ambientConstLiterals.ts, 4, 17)) + const c9 = { x: "abc" }; ->c9 : Symbol(c9, Decl(ambientConstLiterals.ts, 14, 5)) ->x : Symbol(x, Decl(ambientConstLiterals.ts, 14, 12)) +>c9 : Symbol(c9, Decl(ambientConstLiterals.ts, 15, 5)) +>x : Symbol(x, Decl(ambientConstLiterals.ts, 15, 12)) const c10 = [123]; ->c10 : Symbol(c10, Decl(ambientConstLiterals.ts, 15, 5)) +>c10 : Symbol(c10, Decl(ambientConstLiterals.ts, 16, 5)) const c11 = "abc" + "def"; ->c11 : Symbol(c11, Decl(ambientConstLiterals.ts, 16, 5)) +>c11 : Symbol(c11, Decl(ambientConstLiterals.ts, 17, 5)) const c12 = 123 + 456; ->c12 : Symbol(c12, Decl(ambientConstLiterals.ts, 17, 5)) +>c12 : Symbol(c12, Decl(ambientConstLiterals.ts, 18, 5)) const c13 = Math.random() > 0.5 ? "abc" : "def"; ->c13 : Symbol(c13, Decl(ambientConstLiterals.ts, 18, 5)) +>c13 : Symbol(c13, Decl(ambientConstLiterals.ts, 19, 5)) >Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) >Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) const c14 = Math.random() > 0.5 ? 123 : 456; ->c14 : Symbol(c14, Decl(ambientConstLiterals.ts, 19, 5)) +>c14 : Symbol(c14, Decl(ambientConstLiterals.ts, 20, 5)) >Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) >Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) diff --git a/tests/baselines/reference/ambientConstLiterals.types b/tests/baselines/reference/ambientConstLiterals.types index e27776e1847..a40532f8017 100644 --- a/tests/baselines/reference/ambientConstLiterals.types +++ b/tests/baselines/reference/ambientConstLiterals.types @@ -7,11 +7,12 @@ function f(x: T): T { >x : T } -enum E { A, B, C } +enum E { A, B, C, "non identifier" } >E : E >A : E.A >B : E.B >C : E.C +>"non identifier" : E.non identifier const c1 = "abc"; >c1 : "abc" @@ -52,6 +53,12 @@ const c8 = E.A; >E : typeof E >A : E.A +const c8b = E["non identifier"]; +>c8b : E.non identifier +>E["non identifier"] : E.non identifier +>E : typeof E +>"non identifier" : "non identifier" + const c9 = { x: "abc" }; >c9 : { x: string; } >{ x: "abc" } : { x: string; } diff --git a/tests/baselines/reference/ambientEnum1.types b/tests/baselines/reference/ambientEnum1.types index 968299f4d0a..29573226568 100644 --- a/tests/baselines/reference/ambientEnum1.types +++ b/tests/baselines/reference/ambientEnum1.types @@ -3,7 +3,7 @@ >E1 : E1 y = 4.23 ->y : E1 +>y : E1.y >4.23 : 4.23 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer1.types b/tests/baselines/reference/ambientEnumElementInitializer1.types index 11ef7449504..4fa9d5efdf7 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer1.types +++ b/tests/baselines/reference/ambientEnumElementInitializer1.types @@ -3,6 +3,6 @@ declare enum E { >E : E e = 3 ->e : E +>e : E.e >3 : 3 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer2.types b/tests/baselines/reference/ambientEnumElementInitializer2.types index 47d85bf3c84..218863379d7 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer2.types +++ b/tests/baselines/reference/ambientEnumElementInitializer2.types @@ -3,7 +3,7 @@ declare enum E { >E : E e = -3 // Negative ->e : E +>e : E.e >-3 : -3 >3 : 3 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer3.types b/tests/baselines/reference/ambientEnumElementInitializer3.types index 3c099d00ede..e4cf5678d7b 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer3.types +++ b/tests/baselines/reference/ambientEnumElementInitializer3.types @@ -3,6 +3,6 @@ declare enum E { >E : E e = 3.3 // Decimal ->e : E +>e : E.e >3.3 : 3.3 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer4.types b/tests/baselines/reference/ambientEnumElementInitializer4.types index 3bef657f5bb..2cd8c75600d 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer4.types +++ b/tests/baselines/reference/ambientEnumElementInitializer4.types @@ -3,6 +3,6 @@ declare enum E { >E : E e = 0xA ->e : E +>e : E.e >0xA : 10 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer5.types b/tests/baselines/reference/ambientEnumElementInitializer5.types index b3020a6d777..71919718a6e 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer5.types +++ b/tests/baselines/reference/ambientEnumElementInitializer5.types @@ -3,7 +3,7 @@ declare enum E { >E : E e = -0xA ->e : E +>e : E.e >-0xA : -10 >0xA : 10 } diff --git a/tests/baselines/reference/ambientEnumElementInitializer6.types b/tests/baselines/reference/ambientEnumElementInitializer6.types index f093d0e2dfe..9caad2dde7a 100644 --- a/tests/baselines/reference/ambientEnumElementInitializer6.types +++ b/tests/baselines/reference/ambientEnumElementInitializer6.types @@ -6,7 +6,7 @@ declare module M { >E : E e = 3 ->e : E +>e : E.e >3 : 3 } } diff --git a/tests/baselines/reference/ambientErrors.types b/tests/baselines/reference/ambientErrors.types index 6286d4320ad..a1d33d29eeb 100644 --- a/tests/baselines/reference/ambientErrors.types +++ b/tests/baselines/reference/ambientErrors.types @@ -46,7 +46,7 @@ declare enum E1 { >E1 : E1 y = 4.23 ->y : E1 +>y : E1.y >4.23 : 4.23 } diff --git a/tests/baselines/reference/anyAssignabilityInInheritance.types b/tests/baselines/reference/anyAssignabilityInInheritance.types index f0c1684d63c..7afcf99fb2c 100644 --- a/tests/baselines/reference/anyAssignabilityInInheritance.types +++ b/tests/baselines/reference/anyAssignabilityInInheritance.types @@ -199,7 +199,7 @@ var r3 = foo3(a); // any enum E { A } >E : E ->A : E +>A : E.A declare function foo14(x: E): E; >foo14 : { (x: E): E; (x: any): any; } diff --git a/tests/baselines/reference/anyAssignableToEveryType.types b/tests/baselines/reference/anyAssignableToEveryType.types index c4ac27e5b67..17d8ddea497 100644 --- a/tests/baselines/reference/anyAssignableToEveryType.types +++ b/tests/baselines/reference/anyAssignableToEveryType.types @@ -20,7 +20,7 @@ var ai: I; enum E { A } >E : E ->A : E +>A : E.A var ae: E; >ae : E diff --git a/tests/baselines/reference/anyAssignableToEveryType2.types b/tests/baselines/reference/anyAssignableToEveryType2.types index c4c21f503b6..146251c4a7a 100644 --- a/tests/baselines/reference/anyAssignableToEveryType2.types +++ b/tests/baselines/reference/anyAssignableToEveryType2.types @@ -129,7 +129,7 @@ interface I13 { enum E { A } >E : E ->A : E +>A : E.A interface I14 { [x: string]: E; diff --git a/tests/baselines/reference/assignAnyToEveryType.types b/tests/baselines/reference/assignAnyToEveryType.types index bddd4fcb45c..11aa0e48a77 100644 --- a/tests/baselines/reference/assignAnyToEveryType.types +++ b/tests/baselines/reference/assignAnyToEveryType.types @@ -42,7 +42,7 @@ enum E { >E : E A ->A : E +>A : E.A } var g: E = x; diff --git a/tests/baselines/reference/assignEveryTypeToAny.types b/tests/baselines/reference/assignEveryTypeToAny.types index a0b397a003b..8cec100b8be 100644 --- a/tests/baselines/reference/assignEveryTypeToAny.types +++ b/tests/baselines/reference/assignEveryTypeToAny.types @@ -76,7 +76,7 @@ enum E { >E : E A ->A : E +>A : E.A } x = E.A; diff --git a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.types b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.types index ab95fb8cb2f..98083655144 100644 --- a/tests/baselines/reference/assignmentToParenthesizedIdentifiers.types +++ b/tests/baselines/reference/assignmentToParenthesizedIdentifiers.types @@ -294,7 +294,7 @@ enum E { >E : E A ->A : E +>A : E.A } E = undefined; // Error >E = undefined : undefined diff --git a/tests/baselines/reference/assignments.types b/tests/baselines/reference/assignments.types index f83b6eadbe0..03d53e22825 100644 --- a/tests/baselines/reference/assignments.types +++ b/tests/baselines/reference/assignments.types @@ -24,7 +24,7 @@ C = null; // Error enum E { A } >E : E ->A : E +>A : E.A E = null; // Error >E = null : null diff --git a/tests/baselines/reference/asyncEnum_es5.types b/tests/baselines/reference/asyncEnum_es5.types index 2f94fd33152..97d27a1a093 100644 --- a/tests/baselines/reference/asyncEnum_es5.types +++ b/tests/baselines/reference/asyncEnum_es5.types @@ -3,5 +3,5 @@ async enum E { >E : E Value ->Value : E +>Value : E.Value } diff --git a/tests/baselines/reference/asyncEnum_es6.types b/tests/baselines/reference/asyncEnum_es6.types index c28b646edf9..22a560c2ca1 100644 --- a/tests/baselines/reference/asyncEnum_es6.types +++ b/tests/baselines/reference/asyncEnum_es6.types @@ -3,5 +3,5 @@ async enum E { >E : E Value ->Value : E +>Value : E.Value } diff --git a/tests/baselines/reference/augmentedTypesClass.types b/tests/baselines/reference/augmentedTypesClass.types index 6bee329d24e..91bffcf0d2a 100644 --- a/tests/baselines/reference/augmentedTypesClass.types +++ b/tests/baselines/reference/augmentedTypesClass.types @@ -15,5 +15,5 @@ class c4 { public foo() { } } enum c4 { One } // error >c4 : c4 ->One : c4 +>One : c4.One diff --git a/tests/baselines/reference/augmentedTypesClass2.types b/tests/baselines/reference/augmentedTypesClass2.types index df4379508b8..4f80fe6d16a 100644 --- a/tests/baselines/reference/augmentedTypesClass2.types +++ b/tests/baselines/reference/augmentedTypesClass2.types @@ -32,7 +32,7 @@ class c33 { } enum c33 { One }; >c33 : c33 ->One : c33 +>One : c33.One // class then import class c44 { diff --git a/tests/baselines/reference/augmentedTypesEnum.types b/tests/baselines/reference/augmentedTypesEnum.types index d6fcf87f138..27ce4f7c400 100644 --- a/tests/baselines/reference/augmentedTypesEnum.types +++ b/tests/baselines/reference/augmentedTypesEnum.types @@ -2,7 +2,7 @@ // enum then var enum e1111 { One } // error >e1111 : e1111 ->One : e1111 +>One : e1111.One var e1111 = 1; // error >e1111 : number @@ -11,14 +11,14 @@ var e1111 = 1; // error // enum then function enum e2 { One } // error >e2 : e2 ->One : e2 +>One : e2.One function e2() { } // error >e2 : () => void enum e3 { One } // error >e3 : e3 ->One : e3 +>One : e3.One var e3 = () => { } // error >e3 : () => void @@ -27,7 +27,7 @@ var e3 = () => { } // error // enum then class enum e4 { One } // error >e4 : e4 ->One : e4 +>One : e4.One class e4 { public foo() { } } // error >e4 : e4 @@ -36,30 +36,30 @@ class e4 { public foo() { } } // error // enum then enum enum e5 { One } >e5 : e5 ->One : e5 +>One : e5.One enum e5 { Two } // error >e5 : e5 ->Two : e5 +>Two : e5.One enum e5a { One } // error >e5a : e5a ->One : e5a +>One : e5a.One enum e5a { One } // error >e5a : e5a ->One : e5a +>One : e5a.One // enum then internal module enum e6 { One } >e6 : e6 ->One : e6 +>One : e6.One module e6 { } // ok enum e6a { One } >e6a : e6a ->One : e6a +>One : e6a.One module e6a { var y = 2; } // should be error >e6a : typeof e6a @@ -68,7 +68,7 @@ module e6a { var y = 2; } // should be error enum e6b { One } >e6b : e6b ->One : e6b +>One : e6b.One module e6b { export var y = 2; } // should be error >e6b : typeof e6b diff --git a/tests/baselines/reference/augmentedTypesEnum2.types b/tests/baselines/reference/augmentedTypesEnum2.types index 4b77d0eb90b..16232e0f3ff 100644 --- a/tests/baselines/reference/augmentedTypesEnum2.types +++ b/tests/baselines/reference/augmentedTypesEnum2.types @@ -2,7 +2,7 @@ // enum then interface enum e1 { One } // error >e1 : e1 ->One : e1 +>One : e1.One interface e1 { // error foo(): void; @@ -14,7 +14,7 @@ interface e1 { // error // enum then class enum e2 { One }; // error >e2 : e2 ->One : e2 +>One : e2.One class e2 { // error >e2 : e2 diff --git a/tests/baselines/reference/augmentedTypesEnum3.types b/tests/baselines/reference/augmentedTypesEnum3.types index d3c2e933506..10e17c56d98 100644 --- a/tests/baselines/reference/augmentedTypesEnum3.types +++ b/tests/baselines/reference/augmentedTypesEnum3.types @@ -25,13 +25,13 @@ enum A { >A : A b ->b : A +>b : A.b } enum A { >A : A c ->c : A +>c : A.b } module A { >A : typeof A diff --git a/tests/baselines/reference/augmentedTypesFunction.types b/tests/baselines/reference/augmentedTypesFunction.types index b019c02d90c..e30d38179c6 100644 --- a/tests/baselines/reference/augmentedTypesFunction.types +++ b/tests/baselines/reference/augmentedTypesFunction.types @@ -41,7 +41,7 @@ function y4() { } // error enum y4 { One } // error >y4 : y4 ->One : y4 +>One : y4.One // function then internal module function y5() { } diff --git a/tests/baselines/reference/augmentedTypesInterface.types b/tests/baselines/reference/augmentedTypesInterface.types index 6b6ef88015f..1ee66d267c7 100644 --- a/tests/baselines/reference/augmentedTypesInterface.types +++ b/tests/baselines/reference/augmentedTypesInterface.types @@ -35,7 +35,7 @@ interface i3 { // error } enum i3 { One }; // error >i3 : i3 ->One : i3 +>One : i3.One // interface then import interface i4 { diff --git a/tests/baselines/reference/augmentedTypesModules.types b/tests/baselines/reference/augmentedTypesModules.types index 1a03b9991ed..c377381f769 100644 --- a/tests/baselines/reference/augmentedTypesModules.types +++ b/tests/baselines/reference/augmentedTypesModules.types @@ -174,7 +174,7 @@ module m4a { var y = 2; } enum m4a { One } >m4a : m4a ->One : m4a +>One : m4a.One module m4b { export var y = 2; } >m4b : typeof m4b @@ -183,14 +183,14 @@ module m4b { export var y = 2; } enum m4b { One } >m4b : m4b ->One : m4b +>One : m4b.One module m4c { interface I { foo(): void } } >foo : () => void enum m4c { One } >m4c : m4c ->One : m4c +>One : m4c.One module m4d { class C { foo() { } } } >m4d : typeof m4d @@ -199,7 +199,7 @@ module m4d { class C { foo() { } } } enum m4d { One } >m4d : m4d ->One : m4d +>One : m4d.One //// module then module diff --git a/tests/baselines/reference/augmentedTypesModules4.types b/tests/baselines/reference/augmentedTypesModules4.types index d1dd8fe19ec..61083db2591 100644 --- a/tests/baselines/reference/augmentedTypesModules4.types +++ b/tests/baselines/reference/augmentedTypesModules4.types @@ -12,7 +12,7 @@ module m4a { var y = 2; } enum m4a { One } >m4a : m4a ->One : m4a +>One : m4a.One module m4b { export var y = 2; } >m4b : typeof m4b @@ -21,14 +21,14 @@ module m4b { export var y = 2; } enum m4b { One } >m4b : m4b ->One : m4b +>One : m4b.One module m4c { interface I { foo(): void } } >foo : () => void enum m4c { One } >m4c : m4c ->One : m4c +>One : m4c.One module m4d { class C { foo() { } } } >m4d : typeof m4d @@ -37,7 +37,7 @@ module m4d { class C { foo() { } } } enum m4d { One } >m4d : m4d ->One : m4d +>One : m4d.One //// module then module diff --git a/tests/baselines/reference/augmentedTypesVar.types b/tests/baselines/reference/augmentedTypesVar.types index f2ced2b5426..13a9db43c08 100644 --- a/tests/baselines/reference/augmentedTypesVar.types +++ b/tests/baselines/reference/augmentedTypesVar.types @@ -47,7 +47,7 @@ var x5 = 1; enum x5 { One } // error >x5 : x5 ->One : x5 +>One : x5.One // var then module var x6 = 1; diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 67c6c08654b..612403084a5 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -16,11 +16,11 @@ function f3(x: number): boolean { return true; } enum E1 { one } >E1 : E1 ->one : E1 +>one : E1.one enum E2 { two } >E2 : E2 ->two : E2 +>two : E2.two var t1: [(x: number) => string, (x: number) => number]; @@ -46,9 +46,9 @@ t1 = [f1, f2]; >f2 : (x: number) => number t2 = [E1.one, E2.two]; ->t2 = [E1.one, E2.two] : [E1, E2] +>t2 = [E1.one, E2.two] : [E1.one, E2.two] >t2 : [E1, E2] ->[E1.one, E2.two] : [E1, E2] +>[E1.one, E2.two] : [E1.one, E2.two] >E1.one : E1 >E1 : typeof E1 >one : E1 @@ -64,9 +64,9 @@ t3 = [5, undefined]; >undefined : undefined t4 = [E1.one, E2.two, 20]; ->t4 = [E1.one, E2.two, 20] : [E1, E2, number] +>t4 = [E1.one, E2.two, 20] : [E1.one, E2.two, number] >t4 : [E1, E2, number] ->[E1.one, E2.two, 20] : [E1, E2, number] +>[E1.one, E2.two, 20] : [E1.one, E2.two, number] >E1.one : E1 >E1 : typeof E1 >one : E1 diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types index 5c4dc43f774..8b8aef0f911 100644 --- a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef.types @@ -9,7 +9,7 @@ function foo1() { enum E { A } >E : E ->A : E +>A : E.A } function foo2() { @@ -22,5 +22,5 @@ function foo2() { const enum E { A } >E : E ->A : E +>A : E.A } diff --git a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types index 5194114112e..29ca892b1d7 100644 --- a/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types +++ b/tests/baselines/reference/blockScopedEnumVariablesUseBeforeDef_preserve.types @@ -9,7 +9,7 @@ function foo1() { enum E { A } >E : E ->A : E +>A : E.A } function foo2() { @@ -22,5 +22,5 @@ function foo2() { const enum E { A } >E : E ->A : E +>A : E.A } diff --git a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types index 67b20f4bcbe..a7ccc2cd4e0 100644 --- a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types +++ b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types @@ -265,7 +265,7 @@ var r14 = foo14(); enum e1 { A } >e1 : e1 ->A : e1 +>A : e1.A module e1 { export var y = 1; } >e1 : typeof e1 diff --git a/tests/baselines/reference/castingTuple.types b/tests/baselines/reference/castingTuple.types index 5280ca4962b..729c090e1ca 100644 --- a/tests/baselines/reference/castingTuple.types +++ b/tests/baselines/reference/castingTuple.types @@ -25,11 +25,11 @@ class F extends A { f }; enum E1 { one } >E1 : E1 ->one : E1 +>one : E1.one enum E2 { one } >E2 : E2 ->one : E2 +>one : E2.one // no error var numStrTuple: [number, string] = [5, "foo"]; @@ -90,7 +90,7 @@ var eleFromCDA2 = classCDATuple[5]; // C | D | A var t10: [E1, E2] = [E1.one, E2.one]; >t10 : [E1, E2] ->[E1.one, E2.one] : [E1, E2] +>[E1.one, E2.one] : [E1.one, E2.one] >E1.one : E1 >E1 : typeof E1 >one : E1 diff --git a/tests/baselines/reference/classExtendingPrimitive.types b/tests/baselines/reference/classExtendingPrimitive.types index 99dec6c462b..7c118c092bc 100644 --- a/tests/baselines/reference/classExtendingPrimitive.types +++ b/tests/baselines/reference/classExtendingPrimitive.types @@ -40,7 +40,7 @@ class C7 extends Undefined { } enum E { A } >E : E ->A : E +>A : E.A class C8 extends E { } >C8 : C8 diff --git a/tests/baselines/reference/classStaticInitializersUsePropertiesBeforeDeclaration.types b/tests/baselines/reference/classStaticInitializersUsePropertiesBeforeDeclaration.types index 72149f11a5c..2e11087f368 100644 --- a/tests/baselines/reference/classStaticInitializersUsePropertiesBeforeDeclaration.types +++ b/tests/baselines/reference/classStaticInitializersUsePropertiesBeforeDeclaration.types @@ -25,7 +25,7 @@ enum Enum { >Enum : Enum A ->A : Enum +>A : Enum.A } const ObjLiteral = { diff --git a/tests/baselines/reference/collisionCodeGenEnumWithEnumMemberConflict.types b/tests/baselines/reference/collisionCodeGenEnumWithEnumMemberConflict.types index 398179b5cdc..b9366a0cd84 100644 --- a/tests/baselines/reference/collisionCodeGenEnumWithEnumMemberConflict.types +++ b/tests/baselines/reference/collisionCodeGenEnumWithEnumMemberConflict.types @@ -3,9 +3,9 @@ enum Color { >Color : Color Color, ->Color : Color +>Color : Color.Color Thing = Color ->Thing : Color +>Thing : Color.Color >Color : Color } diff --git a/tests/baselines/reference/collisionCodeGenModuleWithEnumMemberConflict.types b/tests/baselines/reference/collisionCodeGenModuleWithEnumMemberConflict.types index 527c8930fcb..b629abc18dd 100644 --- a/tests/baselines/reference/collisionCodeGenModuleWithEnumMemberConflict.types +++ b/tests/baselines/reference/collisionCodeGenModuleWithEnumMemberConflict.types @@ -6,10 +6,10 @@ module m1 { >e : e m1, ->m1 : e +>m1 : e.m1 m2 = m1 ->m2 : e +>m2 : e.m1 >m1 : e } } diff --git a/tests/baselines/reference/computedPropertyNames47_ES5.types b/tests/baselines/reference/computedPropertyNames47_ES5.types index 7307210cfbe..ab8ab053f6a 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES5.types +++ b/tests/baselines/reference/computedPropertyNames47_ES5.types @@ -1,11 +1,11 @@ === tests/cases/conformance/es6/computedProperties/computedPropertyNames47_ES5.ts === enum E1 { x } >E1 : E1 ->x : E1 +>x : E1.x enum E2 { x } >E2 : E2 ->x : E2 +>x : E2.x var o = { >o : { [E1.x || E2.x]: number; } diff --git a/tests/baselines/reference/computedPropertyNames47_ES6.types b/tests/baselines/reference/computedPropertyNames47_ES6.types index d630d5bba93..a11d09dd121 100644 --- a/tests/baselines/reference/computedPropertyNames47_ES6.types +++ b/tests/baselines/reference/computedPropertyNames47_ES6.types @@ -1,11 +1,11 @@ === tests/cases/conformance/es6/computedProperties/computedPropertyNames47_ES6.ts === enum E1 { x } >E1 : E1 ->x : E1 +>x : E1.x enum E2 { x } >E2 : E2 ->x : E2 +>x : E2.x var o = { >o : { [E1.x || E2.x]: number; } diff --git a/tests/baselines/reference/computedPropertyNames48_ES5.types b/tests/baselines/reference/computedPropertyNames48_ES5.types index d3e2cbd6538..c036eabf3d7 100644 --- a/tests/baselines/reference/computedPropertyNames48_ES5.types +++ b/tests/baselines/reference/computedPropertyNames48_ES5.types @@ -6,7 +6,7 @@ declare function extractIndexer(p: { [n: number]: T }): T; enum E { x } >E : E ->x : E +>x : E.x var a: any; >a : any diff --git a/tests/baselines/reference/computedPropertyNames48_ES6.types b/tests/baselines/reference/computedPropertyNames48_ES6.types index 9a1f43f3b7d..7775f6c8c7b 100644 --- a/tests/baselines/reference/computedPropertyNames48_ES6.types +++ b/tests/baselines/reference/computedPropertyNames48_ES6.types @@ -6,7 +6,7 @@ declare function extractIndexer(p: { [n: number]: T }): T; enum E { x } >E : E ->x : E +>x : E.x var a: any; >a : any diff --git a/tests/baselines/reference/computedPropertyNames7_ES5.types b/tests/baselines/reference/computedPropertyNames7_ES5.types index 55f6448127b..08d75af1cd3 100644 --- a/tests/baselines/reference/computedPropertyNames7_ES5.types +++ b/tests/baselines/reference/computedPropertyNames7_ES5.types @@ -3,7 +3,7 @@ enum E { >E : E member ->member : E +>member : E.member } var v = { >v : { [E.member]: number; } diff --git a/tests/baselines/reference/computedPropertyNames7_ES6.types b/tests/baselines/reference/computedPropertyNames7_ES6.types index 0ae55d7c1bb..6e4c85ef6f7 100644 --- a/tests/baselines/reference/computedPropertyNames7_ES6.types +++ b/tests/baselines/reference/computedPropertyNames7_ES6.types @@ -3,7 +3,7 @@ enum E { >E : E member ->member : E +>member : E.member } var v = { >v : { [E.member]: number; } diff --git a/tests/baselines/reference/constDeclarations-ambient-errors.errors.txt b/tests/baselines/reference/constDeclarations-ambient-errors.errors.txt index 8d2b9d67ed8..2eb6e22cd75 100644 --- a/tests/baselines/reference/constDeclarations-ambient-errors.errors.txt +++ b/tests/baselines/reference/constDeclarations-ambient-errors.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/constDeclarations-ambient-errors.ts(2,29): error TS1039: Initializers are not allowed in ambient contexts. tests/cases/compiler/constDeclarations-ambient-errors.ts(3,28): error TS1039: Initializers are not allowed in ambient contexts. -tests/cases/compiler/constDeclarations-ambient-errors.ts(4,20): error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal. +tests/cases/compiler/constDeclarations-ambient-errors.ts(4,20): error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference. tests/cases/compiler/constDeclarations-ambient-errors.ts(4,39): error TS1039: Initializers are not allowed in ambient contexts. tests/cases/compiler/constDeclarations-ambient-errors.ts(4,53): error TS1039: Initializers are not allowed in ambient contexts. tests/cases/compiler/constDeclarations-ambient-errors.ts(8,24): error TS1039: Initializers are not allowed in ambient contexts. @@ -16,7 +16,7 @@ tests/cases/compiler/constDeclarations-ambient-errors.ts(8,24): error TS1039: In !!! error TS1039: Initializers are not allowed in ambient contexts. declare const c3 = null, c4 :string = "", c5: any = 0; ~~~~ -!!! error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal. +!!! error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference. ~~ !!! error TS1039: Initializers are not allowed in ambient contexts. ~ diff --git a/tests/baselines/reference/constEnumBadPropertyNames.types b/tests/baselines/reference/constEnumBadPropertyNames.types index 05c45ba588e..2a640ed1462 100644 --- a/tests/baselines/reference/constEnumBadPropertyNames.types +++ b/tests/baselines/reference/constEnumBadPropertyNames.types @@ -1,7 +1,7 @@ === tests/cases/compiler/constEnumBadPropertyNames.ts === const enum E { A } >E : E ->A : E +>A : E.A var x = E["B"] >x : any diff --git a/tests/baselines/reference/constEnumErrors.types b/tests/baselines/reference/constEnumErrors.types index 187cc1dfde9..f0ebb60815c 100644 --- a/tests/baselines/reference/constEnumErrors.types +++ b/tests/baselines/reference/constEnumErrors.types @@ -3,7 +3,7 @@ const enum E { >E : E A ->A : E +>A : E.A } module E { @@ -41,7 +41,7 @@ const enum E2 { >E2 : E2 A ->A : E2 +>A : E2.A } var y0 = E2[1] diff --git a/tests/baselines/reference/constEnumExternalModule.types b/tests/baselines/reference/constEnumExternalModule.types index 2bd978a2caf..1076328445e 100644 --- a/tests/baselines/reference/constEnumExternalModule.types +++ b/tests/baselines/reference/constEnumExternalModule.types @@ -13,7 +13,7 @@ const enum E { >E : E V = 100 ->V : E +>V : E.V >100 : 100 } diff --git a/tests/baselines/reference/constEnumMergingWithValues1.types b/tests/baselines/reference/constEnumMergingWithValues1.types index 6a3777b6254..ccbf484c251 100644 --- a/tests/baselines/reference/constEnumMergingWithValues1.types +++ b/tests/baselines/reference/constEnumMergingWithValues1.types @@ -5,7 +5,7 @@ function foo() {} module foo { const enum E { X } >E : E ->X : E +>X : E.X } export = foo diff --git a/tests/baselines/reference/constEnumMergingWithValues2.types b/tests/baselines/reference/constEnumMergingWithValues2.types index aad5bb4cbc4..fa9932acc32 100644 --- a/tests/baselines/reference/constEnumMergingWithValues2.types +++ b/tests/baselines/reference/constEnumMergingWithValues2.types @@ -5,7 +5,7 @@ class foo {} module foo { const enum E { X } >E : E ->X : E +>X : E.X } export = foo diff --git a/tests/baselines/reference/constEnumMergingWithValues3.types b/tests/baselines/reference/constEnumMergingWithValues3.types index 3bb578396d4..5d9b3c16e55 100644 --- a/tests/baselines/reference/constEnumMergingWithValues3.types +++ b/tests/baselines/reference/constEnumMergingWithValues3.types @@ -1,12 +1,12 @@ === tests/cases/compiler/m1.ts === enum foo { A } >foo : foo ->A : foo +>A : foo.A module foo { const enum E { X } >E : E ->X : E +>X : E.X } export = foo diff --git a/tests/baselines/reference/constEnumMergingWithValues4.types b/tests/baselines/reference/constEnumMergingWithValues4.types index 88fa405f85d..3b0a085c70b 100644 --- a/tests/baselines/reference/constEnumMergingWithValues4.types +++ b/tests/baselines/reference/constEnumMergingWithValues4.types @@ -2,7 +2,7 @@ module foo { const enum E { X } >E : E ->X : E +>X : E.X } module foo { diff --git a/tests/baselines/reference/constEnumMergingWithValues5.types b/tests/baselines/reference/constEnumMergingWithValues5.types index efd3304ec9f..e75179d4cde 100644 --- a/tests/baselines/reference/constEnumMergingWithValues5.types +++ b/tests/baselines/reference/constEnumMergingWithValues5.types @@ -2,7 +2,7 @@ module foo { const enum E { X } >E : E ->X : E +>X : E.X } export = foo diff --git a/tests/baselines/reference/constEnumOnlyModuleMerging.types b/tests/baselines/reference/constEnumOnlyModuleMerging.types index 9c75910ece3..8e63afcaa80 100644 --- a/tests/baselines/reference/constEnumOnlyModuleMerging.types +++ b/tests/baselines/reference/constEnumOnlyModuleMerging.types @@ -10,7 +10,7 @@ module Outer { module Outer { export const enum A { X } >A : A ->X : A +>X : A.X } module B { diff --git a/tests/baselines/reference/declarationEmitClassMemberNameConflict2.types b/tests/baselines/reference/declarationEmitClassMemberNameConflict2.types index ede64818ff5..fb107e77093 100644 --- a/tests/baselines/reference/declarationEmitClassMemberNameConflict2.types +++ b/tests/baselines/reference/declarationEmitClassMemberNameConflict2.types @@ -7,14 +7,14 @@ enum Hello { >Hello : Hello World ->World : Hello +>World : Hello.World } enum Hello1 { >Hello1 : Hello1 World1 ->World1 : Hello1 +>World1 : Hello1.World1 } class Foo { diff --git a/tests/baselines/reference/declarationEmitEnumReadonlyProperty.js b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.js new file mode 100644 index 00000000000..75c4ce5139d --- /dev/null +++ b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.js @@ -0,0 +1,36 @@ +//// [declarationEmitEnumReadonlyProperty.ts] +enum E { + A = 'a', + B = 'b' +} + +class C { + readonly type = E.A; +} + +let x: E.A = new C().type; + +//// [declarationEmitEnumReadonlyProperty.js] +var E; +(function (E) { + E["A"] = "a"; + E["B"] = "b"; +})(E || (E = {})); +var C = /** @class */ (function () { + function C() { + this.type = E.A; + } + return C; +}()); +var x = new C().type; + + +//// [declarationEmitEnumReadonlyProperty.d.ts] +declare enum E { + A = "a", + B = "b" +} +declare class C { + readonly type = E.A; +} +declare let x: E.A; diff --git a/tests/baselines/reference/declarationEmitEnumReadonlyProperty.symbols b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.symbols new file mode 100644 index 00000000000..7d1425ade78 --- /dev/null +++ b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.symbols @@ -0,0 +1,29 @@ +=== tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts === +enum E { +>E : Symbol(E, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 0)) + + A = 'a', +>A : Symbol(E.A, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 8)) + + B = 'b' +>B : Symbol(E.B, Decl(declarationEmitEnumReadonlyProperty.ts, 1, 12)) +} + +class C { +>C : Symbol(C, Decl(declarationEmitEnumReadonlyProperty.ts, 3, 1)) + + readonly type = E.A; +>type : Symbol(C.type, Decl(declarationEmitEnumReadonlyProperty.ts, 5, 9)) +>E.A : Symbol(E.A, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 8)) +>E : Symbol(E, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 0)) +>A : Symbol(E.A, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 8)) +} + +let x: E.A = new C().type; +>x : Symbol(x, Decl(declarationEmitEnumReadonlyProperty.ts, 9, 3)) +>E : Symbol(E, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 0)) +>A : Symbol(E.A, Decl(declarationEmitEnumReadonlyProperty.ts, 0, 8)) +>new C().type : Symbol(C.type, Decl(declarationEmitEnumReadonlyProperty.ts, 5, 9)) +>C : Symbol(C, Decl(declarationEmitEnumReadonlyProperty.ts, 3, 1)) +>type : Symbol(C.type, Decl(declarationEmitEnumReadonlyProperty.ts, 5, 9)) + diff --git a/tests/baselines/reference/declarationEmitEnumReadonlyProperty.types b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.types new file mode 100644 index 00000000000..eb8f5528cf9 --- /dev/null +++ b/tests/baselines/reference/declarationEmitEnumReadonlyProperty.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts === +enum E { +>E : E + + A = 'a', +>A : E.A +>'a' : "a" + + B = 'b' +>B : E.B +>'b' : "b" +} + +class C { +>C : C + + readonly type = E.A; +>type : E.A +>E.A : E.A +>E : typeof E +>A : E.A +} + +let x: E.A = new C().type; +>x : E.A +>E : any +>new C().type : E.A +>new C() : C +>C : typeof C +>type : E.A + diff --git a/tests/baselines/reference/declarationEmitNameConflicts3.types b/tests/baselines/reference/declarationEmitNameConflicts3.types index 4963076d574..ea1406674de 100644 --- a/tests/baselines/reference/declarationEmitNameConflicts3.types +++ b/tests/baselines/reference/declarationEmitNameConflicts3.types @@ -41,7 +41,7 @@ module M.P { >D : D f ->f : D +>f : D.f } export var v: M.D; // ok >v : M.D diff --git a/tests/baselines/reference/destructuringParameterDeclaration1ES5.types b/tests/baselines/reference/destructuringParameterDeclaration1ES5.types index c0288afccec..a346856223a 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration1ES5.types +++ b/tests/baselines/reference/destructuringParameterDeclaration1ES5.types @@ -191,7 +191,7 @@ b7([["string"], 1, [[true, false]]]); // Shouldn't be an error // If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3) enum Foo { a } >Foo : Foo ->a : Foo +>a : Foo.a function c0({z: {x, y: {j}}}) { } >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void diff --git a/tests/baselines/reference/destructuringParameterDeclaration1ES5iterable.types b/tests/baselines/reference/destructuringParameterDeclaration1ES5iterable.types index d7d682fc048..3797a5da957 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration1ES5iterable.types +++ b/tests/baselines/reference/destructuringParameterDeclaration1ES5iterable.types @@ -191,7 +191,7 @@ b7([["string"], 1, [[true, false]]]); // Shouldn't be an error // If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3) enum Foo { a } >Foo : Foo ->a : Foo +>a : Foo.a function c0({z: {x, y: {j}}}) { } >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void diff --git a/tests/baselines/reference/destructuringParameterDeclaration1ES6.types b/tests/baselines/reference/destructuringParameterDeclaration1ES6.types index baa17d8f125..04d282c76b7 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration1ES6.types +++ b/tests/baselines/reference/destructuringParameterDeclaration1ES6.types @@ -174,7 +174,7 @@ b2("string", { x: 200, y: true }); // If the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section 5.1.3) enum Foo { a } >Foo : Foo ->a : Foo +>a : Foo.a function c0({z: {x, y: {j}}}) { } >c0 : ({ z: { x, y: { j } } }: { z: { x: any; y: { j: any; }; }; }) => void diff --git a/tests/baselines/reference/duplicateIdentifierEnum.types b/tests/baselines/reference/duplicateIdentifierEnum.types index 1555c13f3a0..4fbe1dac8cc 100644 --- a/tests/baselines/reference/duplicateIdentifierEnum.types +++ b/tests/baselines/reference/duplicateIdentifierEnum.types @@ -4,7 +4,7 @@ enum A { >A : A bar ->bar : A +>bar : A.bar } class A { >A : A @@ -21,7 +21,7 @@ const enum B { >B : B bar ->bar : B +>bar : B.bar } const enum C { @@ -39,7 +39,7 @@ enum D { >D : D bar ->bar : D +>bar : D.bar } class E { >E : E @@ -59,5 +59,5 @@ enum E { >E : E bar ->bar : E +>bar : E.bar } diff --git a/tests/baselines/reference/duplicateLocalVariable4.types b/tests/baselines/reference/duplicateLocalVariable4.types index 951f24a0b9d..57da559f7e8 100644 --- a/tests/baselines/reference/duplicateLocalVariable4.types +++ b/tests/baselines/reference/duplicateLocalVariable4.types @@ -3,7 +3,7 @@ enum E{ >E : E a ->a : E +>a : E.a } var x = E; diff --git a/tests/baselines/reference/duplicatePackage_withErrors.errors.txt b/tests/baselines/reference/duplicatePackage_withErrors.errors.txt index ad24637e983..89cc598606f 100644 --- a/tests/baselines/reference/duplicatePackage_withErrors.errors.txt +++ b/tests/baselines/reference/duplicatePackage_withErrors.errors.txt @@ -1,4 +1,4 @@ -/node_modules/a/node_modules/x/index.d.ts(1,18): error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal. +/node_modules/a/node_modules/x/index.d.ts(1,18): error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference. ==== /src/a.ts (0 errors) ==== @@ -11,7 +11,7 @@ ==== /node_modules/a/node_modules/x/index.d.ts (1 errors) ==== export const x = 1 + 1; ~~~~~ -!!! error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal. +!!! error TS1254: A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference. ==== /node_modules/a/node_modules/x/package.json (0 errors) ==== { "name": "x", "version": "1.2.3" } diff --git a/tests/baselines/reference/enumAssignability.types b/tests/baselines/reference/enumAssignability.types index 0f6446c2e51..3783a97c5ff 100644 --- a/tests/baselines/reference/enumAssignability.types +++ b/tests/baselines/reference/enumAssignability.types @@ -3,11 +3,11 @@ enum E { A } >E : E ->A : E +>A : E.A enum F { B } >F : F ->B : F +>B : F.B var e = E.A; >e : E diff --git a/tests/baselines/reference/enumAssignabilityInInheritance.types b/tests/baselines/reference/enumAssignabilityInInheritance.types index f6c2d999a2e..2c792b406df 100644 --- a/tests/baselines/reference/enumAssignabilityInInheritance.types +++ b/tests/baselines/reference/enumAssignabilityInInheritance.types @@ -4,7 +4,7 @@ enum E { A } >E : E ->A : E +>A : E.A interface I0 { [x: string]: E; @@ -243,7 +243,7 @@ var r4 = foo12(E.A); enum E2 { A } >E2 : E2 ->A : E2 +>A : E2.A declare function foo13(x: E2): E2; >foo13 : { (x: E2): E2; (x: E): E; } diff --git a/tests/baselines/reference/enumAssignmentCompat4.types b/tests/baselines/reference/enumAssignmentCompat4.types index 8d960245862..7ca5a5603b1 100644 --- a/tests/baselines/reference/enumAssignmentCompat4.types +++ b/tests/baselines/reference/enumAssignmentCompat4.types @@ -6,7 +6,7 @@ namespace M { >MyEnum : MyEnum BAR ->BAR : MyEnum +>BAR : MyEnum.BAR } export var object2 = { >object2 : { foo: MyEnum; } @@ -28,7 +28,7 @@ namespace N { >MyEnum : MyEnum FOO ->FOO : MyEnum +>FOO : MyEnum.FOO }; export var object1 = { diff --git a/tests/baselines/reference/enumBasics.types b/tests/baselines/reference/enumBasics.types index 0ca967cc258..1568212a455 100644 --- a/tests/baselines/reference/enumBasics.types +++ b/tests/baselines/reference/enumBasics.types @@ -162,10 +162,10 @@ enum E9 { >E9 : E9 A, ->A : E9 +>A : E9.A B = A ->B : E9 +>B : E9.A >A : E9 } diff --git a/tests/baselines/reference/enumClassification.types b/tests/baselines/reference/enumClassification.types index 73c8041a6b7..886d5f7342d 100644 --- a/tests/baselines/reference/enumClassification.types +++ b/tests/baselines/reference/enumClassification.types @@ -10,14 +10,14 @@ enum E01 { >E01 : E01 A ->A : E01 +>A : E01.A } enum E02 { >E02 : E02 A = 123 ->A : E02 +>A : E02.A >123 : 123 } @@ -25,7 +25,7 @@ enum E03 { >E03 : E03 A = "hello" ->A : E03 +>A : E03.A >"hello" : "hello" } diff --git a/tests/baselines/reference/enumConflictsWithGlobalIdentifier.types b/tests/baselines/reference/enumConflictsWithGlobalIdentifier.types index b593384ac34..73d1595187c 100644 --- a/tests/baselines/reference/enumConflictsWithGlobalIdentifier.types +++ b/tests/baselines/reference/enumConflictsWithGlobalIdentifier.types @@ -3,7 +3,7 @@ enum Position { >Position : Position IgnoreRulesSpecific = 0, ->IgnoreRulesSpecific : Position +>IgnoreRulesSpecific : Position.IgnoreRulesSpecific >0 : 0 } var x = IgnoreRulesSpecific. diff --git a/tests/baselines/reference/enumConstantMemberWithString.types b/tests/baselines/reference/enumConstantMemberWithString.types index 91bc2f97072..4d20d1c6f0f 100644 --- a/tests/baselines/reference/enumConstantMemberWithString.types +++ b/tests/baselines/reference/enumConstantMemberWithString.types @@ -75,7 +75,7 @@ enum T4 { >T4 : T4 a = "1" ->a : T4 +>a : T4.a >"1" : "1" } @@ -83,7 +83,7 @@ enum T5 { >T5 : T5 a = "1" + "2" ->a : T5 +>a : T5.a >"1" + "2" : string >"1" : "1" >"2" : "2" diff --git a/tests/baselines/reference/enumConstantMemberWithStringEmitDeclaration.types b/tests/baselines/reference/enumConstantMemberWithStringEmitDeclaration.types index b613ec306e4..5baed333def 100644 --- a/tests/baselines/reference/enumConstantMemberWithStringEmitDeclaration.types +++ b/tests/baselines/reference/enumConstantMemberWithStringEmitDeclaration.types @@ -53,7 +53,7 @@ enum T4 { >T4 : T4 a = "1" ->a : T4 +>a : T4.a >"1" : "1" } @@ -61,7 +61,7 @@ enum T5 { >T5 : T5 a = "1" + "2" ->a : T5 +>a : T5.a >"1" + "2" : string >"1" : "1" >"2" : "2" diff --git a/tests/baselines/reference/enumErrors.types b/tests/baselines/reference/enumErrors.types index 8c95ef133ce..a219c862233 100644 --- a/tests/baselines/reference/enumErrors.types +++ b/tests/baselines/reference/enumErrors.types @@ -27,10 +27,10 @@ enum E9 { >E9 : E9 A, ->A : E9 +>A : E9.A B = A ->B : E9 +>B : E9.A >A : E9 } diff --git a/tests/baselines/reference/enumFromExternalModule.types b/tests/baselines/reference/enumFromExternalModule.types index 05555572aa7..b4675348367 100644 --- a/tests/baselines/reference/enumFromExternalModule.types +++ b/tests/baselines/reference/enumFromExternalModule.types @@ -14,5 +14,5 @@ var x = f.Mode.Open; === tests/cases/compiler/enumFromExternalModule_0.ts === export enum Mode { Open } >Mode : Mode ->Open : Mode +>Open : Mode.Open diff --git a/tests/baselines/reference/enumGenericTypeClash.types b/tests/baselines/reference/enumGenericTypeClash.types index bb7521fa222..9e589503c2f 100644 --- a/tests/baselines/reference/enumGenericTypeClash.types +++ b/tests/baselines/reference/enumGenericTypeClash.types @@ -4,5 +4,5 @@ class X { } enum X { MyVal } >X : X ->MyVal : X +>MyVal : X.MyVal diff --git a/tests/baselines/reference/enumIsNotASubtypeOfAnythingButNumber.types b/tests/baselines/reference/enumIsNotASubtypeOfAnythingButNumber.types index a44aeee7f3d..5df80fd39bd 100644 --- a/tests/baselines/reference/enumIsNotASubtypeOfAnythingButNumber.types +++ b/tests/baselines/reference/enumIsNotASubtypeOfAnythingButNumber.types @@ -3,7 +3,7 @@ enum E { A } >E : E ->A : E +>A : E.A interface I { [x: string]: any; @@ -133,7 +133,7 @@ interface I13 { enum E2 { A } >E2 : E2 ->A : E2 +>A : E2.A interface I14 { [x: string]: E2; diff --git a/tests/baselines/reference/enumLiteralUnionNotWidened.js b/tests/baselines/reference/enumLiteralUnionNotWidened.js new file mode 100644 index 00000000000..a58e9332476 --- /dev/null +++ b/tests/baselines/reference/enumLiteralUnionNotWidened.js @@ -0,0 +1,48 @@ +//// [enumLiteralUnionNotWidened.ts] +// repro from #22093 +enum A { one = "one", two = "two" }; +enum B { foo = "foo", bar = "bar" }; + +type C = A | B.foo; +type D = A | "foo"; + +class List +{ + private readonly items: T[] = []; +} + +function asList(arg: T): List { return new List(); } + +// TypeScript incorrectly infers the return type of "asList(x)" to be "List" +// The correct type is "List" +function fn1(x: C): List { return asList(x); } + +// If we use the literal "foo" instead of B.foo, the correct type is inferred +function fn2(x: D): List { return asList(x); } + +//// [enumLiteralUnionNotWidened.js] +// repro from #22093 +var A; +(function (A) { + A["one"] = "one"; + A["two"] = "two"; +})(A || (A = {})); +; +var B; +(function (B) { + B["foo"] = "foo"; + B["bar"] = "bar"; +})(B || (B = {})); +; +var List = /** @class */ (function () { + function List() { + this.items = []; + } + return List; +}()); +function asList(arg) { return new List(); } +// TypeScript incorrectly infers the return type of "asList(x)" to be "List" +// The correct type is "List" +function fn1(x) { return asList(x); } +// If we use the literal "foo" instead of B.foo, the correct type is inferred +function fn2(x) { return asList(x); } diff --git a/tests/baselines/reference/enumLiteralUnionNotWidened.symbols b/tests/baselines/reference/enumLiteralUnionNotWidened.symbols new file mode 100644 index 00000000000..2a2eb67399a --- /dev/null +++ b/tests/baselines/reference/enumLiteralUnionNotWidened.symbols @@ -0,0 +1,61 @@ +=== tests/cases/compiler/enumLiteralUnionNotWidened.ts === +// repro from #22093 +enum A { one = "one", two = "two" }; +>A : Symbol(A, Decl(enumLiteralUnionNotWidened.ts, 0, 0)) +>one : Symbol(A.one, Decl(enumLiteralUnionNotWidened.ts, 1, 8)) +>two : Symbol(A.two, Decl(enumLiteralUnionNotWidened.ts, 1, 21)) + +enum B { foo = "foo", bar = "bar" }; +>B : Symbol(B, Decl(enumLiteralUnionNotWidened.ts, 1, 36)) +>foo : Symbol(B.foo, Decl(enumLiteralUnionNotWidened.ts, 2, 8)) +>bar : Symbol(B.bar, Decl(enumLiteralUnionNotWidened.ts, 2, 21)) + +type C = A | B.foo; +>C : Symbol(C, Decl(enumLiteralUnionNotWidened.ts, 2, 36)) +>A : Symbol(A, Decl(enumLiteralUnionNotWidened.ts, 0, 0)) +>B : Symbol(B, Decl(enumLiteralUnionNotWidened.ts, 1, 36)) +>foo : Symbol(B.foo, Decl(enumLiteralUnionNotWidened.ts, 2, 8)) + +type D = A | "foo"; +>D : Symbol(D, Decl(enumLiteralUnionNotWidened.ts, 4, 19)) +>A : Symbol(A, Decl(enumLiteralUnionNotWidened.ts, 0, 0)) + +class List +>List : Symbol(List, Decl(enumLiteralUnionNotWidened.ts, 5, 19)) +>T : Symbol(T, Decl(enumLiteralUnionNotWidened.ts, 7, 11)) +{ + private readonly items: T[] = []; +>items : Symbol(List.items, Decl(enumLiteralUnionNotWidened.ts, 8, 1)) +>T : Symbol(T, Decl(enumLiteralUnionNotWidened.ts, 7, 11)) +} + +function asList(arg: T): List { return new List(); } +>asList : Symbol(asList, Decl(enumLiteralUnionNotWidened.ts, 10, 1)) +>T : Symbol(T, Decl(enumLiteralUnionNotWidened.ts, 12, 16)) +>arg : Symbol(arg, Decl(enumLiteralUnionNotWidened.ts, 12, 19)) +>T : Symbol(T, Decl(enumLiteralUnionNotWidened.ts, 12, 16)) +>List : Symbol(List, Decl(enumLiteralUnionNotWidened.ts, 5, 19)) +>T : Symbol(T, Decl(enumLiteralUnionNotWidened.ts, 12, 16)) +>List : Symbol(List, Decl(enumLiteralUnionNotWidened.ts, 5, 19)) + +// TypeScript incorrectly infers the return type of "asList(x)" to be "List" +// The correct type is "List" +function fn1(x: C): List { return asList(x); } +>fn1 : Symbol(fn1, Decl(enumLiteralUnionNotWidened.ts, 12, 58)) +>x : Symbol(x, Decl(enumLiteralUnionNotWidened.ts, 16, 13)) +>C : Symbol(C, Decl(enumLiteralUnionNotWidened.ts, 2, 36)) +>List : Symbol(List, Decl(enumLiteralUnionNotWidened.ts, 5, 19)) +>C : Symbol(C, Decl(enumLiteralUnionNotWidened.ts, 2, 36)) +>asList : Symbol(asList, Decl(enumLiteralUnionNotWidened.ts, 10, 1)) +>x : Symbol(x, Decl(enumLiteralUnionNotWidened.ts, 16, 13)) + +// If we use the literal "foo" instead of B.foo, the correct type is inferred +function fn2(x: D): List { return asList(x); } +>fn2 : Symbol(fn2, Decl(enumLiteralUnionNotWidened.ts, 16, 49)) +>x : Symbol(x, Decl(enumLiteralUnionNotWidened.ts, 19, 13)) +>D : Symbol(D, Decl(enumLiteralUnionNotWidened.ts, 4, 19)) +>List : Symbol(List, Decl(enumLiteralUnionNotWidened.ts, 5, 19)) +>D : Symbol(D, Decl(enumLiteralUnionNotWidened.ts, 4, 19)) +>asList : Symbol(asList, Decl(enumLiteralUnionNotWidened.ts, 10, 1)) +>x : Symbol(x, Decl(enumLiteralUnionNotWidened.ts, 19, 13)) + diff --git a/tests/baselines/reference/enumLiteralUnionNotWidened.types b/tests/baselines/reference/enumLiteralUnionNotWidened.types new file mode 100644 index 00000000000..87443fbd549 --- /dev/null +++ b/tests/baselines/reference/enumLiteralUnionNotWidened.types @@ -0,0 +1,54 @@ +=== tests/cases/compiler/enumLiteralUnionNotWidened.ts === +// repro from #22093 +enum A { one = "one", two = "two" }; +>A : A +>one : A.one +>"one" : "one" +>two : A.two +>"two" : "two" + +enum B { foo = "foo", bar = "bar" }; +>B : B +>foo : B.foo +>"foo" : "foo" +>bar : B.bar +>"bar" : "bar" + +type C = A | B.foo; +>C : C +>B : any + +type D = A | "foo"; +>D : D + +class List +>List : List +{ + private readonly items: T[] = []; +>items : T[] +>[] : undefined[] +} + +function asList(arg: T): List { return new List(); } +>asList : (arg: T) => List +>arg : T +>new List() : List +>List : typeof List + +// TypeScript incorrectly infers the return type of "asList(x)" to be "List" +// The correct type is "List" +function fn1(x: C): List { return asList(x); } +>fn1 : (x: C) => List +>x : C +>asList(x) : List +>asList : (arg: T) => List +>x : C + +// If we use the literal "foo" instead of B.foo, the correct type is inferred +function fn2(x: D): List { return asList(x); } +>fn2 : (x: D) => List +>x : D +>asList(x) : List +>asList : (arg: T) => List +>x : D + diff --git a/tests/baselines/reference/enumMemberResolution.types b/tests/baselines/reference/enumMemberResolution.types index 0d761573973..e0a53f1d5ff 100644 --- a/tests/baselines/reference/enumMemberResolution.types +++ b/tests/baselines/reference/enumMemberResolution.types @@ -3,7 +3,7 @@ enum Position2 { >Position2 : Position2 IgnoreRulesSpecific = 0 ->IgnoreRulesSpecific : Position2 +>IgnoreRulesSpecific : Position2.IgnoreRulesSpecific >0 : 0 } var x = IgnoreRulesSpecific. // error diff --git a/tests/baselines/reference/enumMergingErrors.types b/tests/baselines/reference/enumMergingErrors.types index 3603f01fb5a..34fa6fe671b 100644 --- a/tests/baselines/reference/enumMergingErrors.types +++ b/tests/baselines/reference/enumMergingErrors.types @@ -64,7 +64,7 @@ module M1 { export enum E1 { A = 0 } >E1 : E1 ->A : E1 +>A : E1.A >0 : 0 } module M1 { @@ -72,14 +72,14 @@ module M1 { export enum E1 { B } >E1 : E1 ->B : E1 +>B : E1.A } module M1 { >M1 : typeof M1 export enum E1 { C } >E1 : E1 ->C : E1 +>C : E1.A } @@ -89,14 +89,14 @@ module M2 { export enum E1 { A } >E1 : E1 ->A : E1 +>A : E1.A } module M2 { >M2 : typeof M2 export enum E1 { B = 0 } >E1 : E1 ->B : E1 +>B : E1.A >0 : 0 } module M2 { @@ -104,7 +104,7 @@ module M2 { export enum E1 { C } >E1 : E1 ->C : E1 +>C : E1.A } diff --git a/tests/baselines/reference/enumOperations.types b/tests/baselines/reference/enumOperations.types index 261b5149ebd..e4afed35b10 100644 --- a/tests/baselines/reference/enumOperations.types +++ b/tests/baselines/reference/enumOperations.types @@ -1,7 +1,7 @@ === tests/cases/compiler/enumOperations.ts === enum Enum { None = 0 } >Enum : Enum ->None : Enum +>None : Enum.None >0 : 0 var enumType: Enum = Enum.None; diff --git a/tests/baselines/reference/enumWithInfinityProperty.types b/tests/baselines/reference/enumWithInfinityProperty.types index 664aa5ea2d5..ea4dc8a1dde 100644 --- a/tests/baselines/reference/enumWithInfinityProperty.types +++ b/tests/baselines/reference/enumWithInfinityProperty.types @@ -3,7 +3,7 @@ enum A { >A : A Infinity = 1 ->Infinity : A +>Infinity : A.Infinity >1 : 1 } diff --git a/tests/baselines/reference/enumWithNaNProperty.types b/tests/baselines/reference/enumWithNaNProperty.types index 710c7554a31..5233d30473a 100644 --- a/tests/baselines/reference/enumWithNaNProperty.types +++ b/tests/baselines/reference/enumWithNaNProperty.types @@ -3,7 +3,7 @@ enum A { >A : A NaN = 1 ->NaN : A +>NaN : A.NaN >1 : 1 } diff --git a/tests/baselines/reference/enumWithNegativeInfinityProperty.types b/tests/baselines/reference/enumWithNegativeInfinityProperty.types index 951f8969769..55a3f3c5633 100644 --- a/tests/baselines/reference/enumWithNegativeInfinityProperty.types +++ b/tests/baselines/reference/enumWithNegativeInfinityProperty.types @@ -3,7 +3,7 @@ enum A { >A : A "-Infinity" = 1 ->"-Infinity" : A +>"-Infinity" : A.-Infinity >1 : 1 } diff --git a/tests/baselines/reference/enumWithQuotedElementName1.types b/tests/baselines/reference/enumWithQuotedElementName1.types index 4e3db0ca482..2452f3882d5 100644 --- a/tests/baselines/reference/enumWithQuotedElementName1.types +++ b/tests/baselines/reference/enumWithQuotedElementName1.types @@ -3,5 +3,5 @@ enum E { >E : E 'fo"o', ->'fo"o' : E +>'fo"o' : E.fo"o } diff --git a/tests/baselines/reference/enumWithQuotedElementName2.types b/tests/baselines/reference/enumWithQuotedElementName2.types index 9b07138e5ab..0c34e07188c 100644 --- a/tests/baselines/reference/enumWithQuotedElementName2.types +++ b/tests/baselines/reference/enumWithQuotedElementName2.types @@ -3,5 +3,5 @@ enum E { >E : E "fo'o", ->"fo'o" : E +>"fo'o" : E.fo'o } diff --git a/tests/baselines/reference/enumWithUnicodeEscape1.types b/tests/baselines/reference/enumWithUnicodeEscape1.types index ee9dbbf5c2a..e989936dd85 100644 --- a/tests/baselines/reference/enumWithUnicodeEscape1.types +++ b/tests/baselines/reference/enumWithUnicodeEscape1.types @@ -3,6 +3,6 @@ enum E { >E : E 'gold \u2730' ->'gold \u2730' : E +>'gold \u2730' : E.gold ✰ } diff --git a/tests/baselines/reference/enumsWithMultipleDeclarations1.types b/tests/baselines/reference/enumsWithMultipleDeclarations1.types index 1df52e22c82..552122bdc20 100644 --- a/tests/baselines/reference/enumsWithMultipleDeclarations1.types +++ b/tests/baselines/reference/enumsWithMultipleDeclarations1.types @@ -3,19 +3,19 @@ enum E { >E : E A ->A : E +>A : E.A } enum E { >E : E B ->B : E +>B : E.A } enum E { >E : E C ->C : E +>C : E.A } diff --git a/tests/baselines/reference/enumsWithMultipleDeclarations3.types b/tests/baselines/reference/enumsWithMultipleDeclarations3.types index 4f8f0ce5f58..b21e60afd24 100644 --- a/tests/baselines/reference/enumsWithMultipleDeclarations3.types +++ b/tests/baselines/reference/enumsWithMultipleDeclarations3.types @@ -6,5 +6,5 @@ enum E { >E : E A ->A : E +>A : E.A } diff --git a/tests/baselines/reference/es6modulekindWithES5Target5.types b/tests/baselines/reference/es6modulekindWithES5Target5.types index b5e69598788..74f4e8b34a6 100644 --- a/tests/baselines/reference/es6modulekindWithES5Target5.types +++ b/tests/baselines/reference/es6modulekindWithES5Target5.types @@ -3,12 +3,12 @@ export enum E1 { >E1 : E1 value1 ->value1 : E1 +>value1 : E1.value1 } export const enum E2 { >E2 : E2 value1 ->value1 : E2 +>value1 : E2.value1 } diff --git a/tests/baselines/reference/esnextmodulekindWithES5Target5.types b/tests/baselines/reference/esnextmodulekindWithES5Target5.types index c838a953ef9..bfeec26a519 100644 --- a/tests/baselines/reference/esnextmodulekindWithES5Target5.types +++ b/tests/baselines/reference/esnextmodulekindWithES5Target5.types @@ -3,12 +3,12 @@ export enum E1 { >E1 : E1 value1 ->value1 : E1 +>value1 : E1.value1 } export const enum E2 { >E2 : E2 value1 ->value1 : E2 +>value1 : E2.value1 } diff --git a/tests/baselines/reference/everyTypeAssignableToAny.types b/tests/baselines/reference/everyTypeAssignableToAny.types index c38e2bb0f61..574d77bc7e4 100644 --- a/tests/baselines/reference/everyTypeAssignableToAny.types +++ b/tests/baselines/reference/everyTypeAssignableToAny.types @@ -20,7 +20,7 @@ var ai: I; enum E { A } >E : E ->A : E +>A : E.A var ae: E; >ae : E diff --git a/tests/baselines/reference/exportCodeGen.types b/tests/baselines/reference/exportCodeGen.types index 782ac5ff499..99c912f9864 100644 --- a/tests/baselines/reference/exportCodeGen.types +++ b/tests/baselines/reference/exportCodeGen.types @@ -66,7 +66,7 @@ module E { export enum Color { Red } >Color : Color ->Red : Color +>Red : Color.Red export function fn() { } >fn : () => void @@ -94,7 +94,7 @@ module F { enum Color { Red } >Color : Color ->Red : Color +>Red : Color.Red function fn() { } >fn : () => void diff --git a/tests/baselines/reference/for-of47.types b/tests/baselines/reference/for-of47.types index 9f98a2c63b4..b235d772e84 100644 --- a/tests/baselines/reference/for-of47.types +++ b/tests/baselines/reference/for-of47.types @@ -14,7 +14,7 @@ var array = [{ x: "", y: true }] enum E { x } >E : E ->x : E +>x : E.x for ({x, y: y = E.x} of array) { >{x, y: y = E.x} : { x: string; y?: E; } diff --git a/tests/baselines/reference/for-of48.types b/tests/baselines/reference/for-of48.types index af93d4968f2..575ea99064f 100644 --- a/tests/baselines/reference/for-of48.types +++ b/tests/baselines/reference/for-of48.types @@ -14,7 +14,7 @@ var array = [{ x: "", y: true }] enum E { x } >E : E ->x : E +>x : E.x for ({x, y = E.x} of array) { >{x, y = E.x} : { x: string; y?: number; } diff --git a/tests/baselines/reference/genericCallWithGenericSignatureArguments2.types b/tests/baselines/reference/genericCallWithGenericSignatureArguments2.types index 20d58530615..64acb69d4e6 100644 --- a/tests/baselines/reference/genericCallWithGenericSignatureArguments2.types +++ b/tests/baselines/reference/genericCallWithGenericSignatureArguments2.types @@ -106,11 +106,11 @@ module onlyT { enum E { A } >E : E ->A : E +>A : E.A enum F { A } >F : F ->A : F +>A : F.A function foo3(x: T, a: (x: T) => T, b: (x: T) => T) { >foo3 : (x: T, a: (x: T) => T, b: (x: T) => T) => (x: T) => T @@ -250,11 +250,11 @@ module TU { enum E { A } >E : E ->A : E +>A : E.A enum F { A } >F : F ->A : F +>A : F.A function foo3(x: T, a: (x: T) => T, b: (x: U) => U) { >foo3 : (x: T, a: (x: T) => T, b: (x: any) => any) => (x: T) => T diff --git a/tests/baselines/reference/genericCallWithGenericSignatureArguments3.types b/tests/baselines/reference/genericCallWithGenericSignatureArguments3.types index 4379594f6eb..5bd04109723 100644 --- a/tests/baselines/reference/genericCallWithGenericSignatureArguments3.types +++ b/tests/baselines/reference/genericCallWithGenericSignatureArguments3.types @@ -93,11 +93,11 @@ var r5 = foo(new Object(), (x) => '', (x) => ''); // Object => Object enum E { A } >E : E ->A : E +>A : E.A enum F { A } >F : F ->A : F +>A : F.A var r6 = foo(E.A, (x: number) => E.A, (x: F) => F.A); // number => number >r6 : (x: number) => number diff --git a/tests/baselines/reference/inOperatorWithInvalidOperands.types b/tests/baselines/reference/inOperatorWithInvalidOperands.types index f5c8ff8fb88..d85ec6d7a3d 100644 --- a/tests/baselines/reference/inOperatorWithInvalidOperands.types +++ b/tests/baselines/reference/inOperatorWithInvalidOperands.types @@ -1,7 +1,7 @@ === tests/cases/conformance/expressions/binaryOperators/inOperator/inOperatorWithInvalidOperands.ts === enum E { a } >E : E ->a : E +>a : E.a var x: any; >x : any diff --git a/tests/baselines/reference/interfaceWithPropertyOfEveryType.types b/tests/baselines/reference/interfaceWithPropertyOfEveryType.types index 6df43d9e39a..28fddbce52a 100644 --- a/tests/baselines/reference/interfaceWithPropertyOfEveryType.types +++ b/tests/baselines/reference/interfaceWithPropertyOfEveryType.types @@ -15,7 +15,7 @@ module M { } enum E { A } >E : E ->A : E +>A : E.A interface Foo { a: number; @@ -70,7 +70,7 @@ interface Foo { var a: Foo = { >a : Foo ->{ a: 1, b: '', c: true, d: {}, e: null , f: [1], g: {}, h: (x: number) => 1, i: (x: T) => x, j: null, k: new C(), l: f1, m: M, n: {}, o: E.A} : { a: number; b: string; c: true; d: {}; e: null; f: number[]; g: {}; h: (x: number) => number; i: (x: T) => T; j: Foo; k: C; l: () => void; m: typeof M; n: {}; o: E; } +>{ a: 1, b: '', c: true, d: {}, e: null , f: [1], g: {}, h: (x: number) => 1, i: (x: T) => x, j: null, k: new C(), l: f1, m: M, n: {}, o: E.A} : { a: number; b: string; c: true; d: {}; e: null; f: number[]; g: {}; h: (x: number) => number; i: (x: T) => T; j: Foo; k: C; l: () => void; m: typeof M; n: {}; o: E.A; } a: 1, >a : number @@ -136,7 +136,7 @@ var a: Foo = { >{} : {} o: E.A ->o : E +>o : E.A >E.A : E >E : typeof E >A : E diff --git a/tests/baselines/reference/invalidBooleanAssignments.types b/tests/baselines/reference/invalidBooleanAssignments.types index 1b91002ffba..439d93e5408 100644 --- a/tests/baselines/reference/invalidBooleanAssignments.types +++ b/tests/baselines/reference/invalidBooleanAssignments.types @@ -22,7 +22,7 @@ var d: typeof undefined = x; enum E { A } >E : E ->A : E +>A : E.A var e: E = x; >e : E diff --git a/tests/baselines/reference/invalidStringAssignments.types b/tests/baselines/reference/invalidStringAssignments.types index 4f749b6528d..66510d029c9 100644 --- a/tests/baselines/reference/invalidStringAssignments.types +++ b/tests/baselines/reference/invalidStringAssignments.types @@ -71,7 +71,7 @@ i = x; enum E { A } >E : E ->A : E +>A : E.A var j: E = x; >j : E diff --git a/tests/baselines/reference/invalidUndefinedAssignments.types b/tests/baselines/reference/invalidUndefinedAssignments.types index fdb8e160be0..ab19dd824e1 100644 --- a/tests/baselines/reference/invalidUndefinedAssignments.types +++ b/tests/baselines/reference/invalidUndefinedAssignments.types @@ -5,7 +5,7 @@ var x: typeof undefined; enum E { A } >E : E ->A : E +>A : E.A E = x; >E = x : any diff --git a/tests/baselines/reference/invalidUndefinedValues.types b/tests/baselines/reference/invalidUndefinedValues.types index f93b3a4c244..3cb51ebeb29 100644 --- a/tests/baselines/reference/invalidUndefinedValues.types +++ b/tests/baselines/reference/invalidUndefinedValues.types @@ -91,7 +91,7 @@ x = f; enum E { A } >E : E ->A : E +>A : E.A x = E; >x = E : typeof E diff --git a/tests/baselines/reference/invalidVoidAssignments.types b/tests/baselines/reference/invalidVoidAssignments.types index 02c80b7f942..0711f912f3e 100644 --- a/tests/baselines/reference/invalidVoidAssignments.types +++ b/tests/baselines/reference/invalidVoidAssignments.types @@ -70,7 +70,7 @@ i = x; enum E { A } >E : E ->A : E +>A : E.A x = E; >x = E : typeof E diff --git a/tests/baselines/reference/invalidVoidValues.types b/tests/baselines/reference/invalidVoidValues.types index 9f0988cf35f..ab539e61d4f 100644 --- a/tests/baselines/reference/invalidVoidValues.types +++ b/tests/baselines/reference/invalidVoidValues.types @@ -19,7 +19,7 @@ x = true; enum E { A } >E : E ->A : E +>A : E.A x = E; >x = E : typeof E diff --git a/tests/baselines/reference/isolatedModulesAmbientConstEnum.types b/tests/baselines/reference/isolatedModulesAmbientConstEnum.types index ea849088d50..8b714d98f6e 100644 --- a/tests/baselines/reference/isolatedModulesAmbientConstEnum.types +++ b/tests/baselines/reference/isolatedModulesAmbientConstEnum.types @@ -1,7 +1,7 @@ === tests/cases/compiler/file1.ts === declare const enum E { X = 1} >E : E ->X : E +>X : E.X >1 : 1 export var y; diff --git a/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types index 1ac53071e4c..0c5f566fee9 100644 --- a/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types +++ b/tests/baselines/reference/isolatedModulesNonAmbientConstEnum.types @@ -1,7 +1,7 @@ === tests/cases/compiler/file1.ts === const enum E { X = 100 }; >E : E ->X : E +>X : E.X >100 : 100 var e = E.X; diff --git a/tests/baselines/reference/jsdocAccessEnumType.types b/tests/baselines/reference/jsdocAccessEnumType.types index a08c2b4e179..7ceabb3c7b7 100644 --- a/tests/baselines/reference/jsdocAccessEnumType.types +++ b/tests/baselines/reference/jsdocAccessEnumType.types @@ -1,7 +1,7 @@ === /a.ts === export enum E { A } >E : E ->A : E +>A : E.A === /b.js === import { E } from "./a"; diff --git a/tests/baselines/reference/logicalOrOperatorWithEveryType.types b/tests/baselines/reference/logicalOrOperatorWithEveryType.types index 354ede66365..d84dc46ef73 100644 --- a/tests/baselines/reference/logicalOrOperatorWithEveryType.types +++ b/tests/baselines/reference/logicalOrOperatorWithEveryType.types @@ -126,7 +126,7 @@ var rb5 = a5 || a2; // void || boolean is void | boolean >a2 : boolean var rb6 = a6 || a2; // enum || boolean is E | boolean ->rb6 : boolean | E +>rb6 : boolean | E.b | E.c >a6 || a2 : boolean | E.b | E.c >a6 : E >a2 : boolean @@ -246,7 +246,7 @@ var rd5 = a5 || a4; // void || string is void | string >a4 : string var rd6 = a6 || a4; // enum || string is enum | string ->rd6 : string | E +>rd6 : string | E.b | E.c >a6 || a4 : string | E.b | E.c >a6 : E >a4 : string @@ -306,7 +306,7 @@ var re5 = a5 || a5; // void || void is void >a5 : void var re6 = a6 || a5; // enum || void is enum | void ->re6 : void | E +>re6 : void | E.b | E.c >a6 || a5 : void | E.b | E.c >a6 : E >a5 : void @@ -426,7 +426,7 @@ var rh5 = a5 || a7; // void || object is void | object >a7 : { a: string; } var rh6 = a6 || a7; // enum || object is enum | object ->rh6 : E | { a: string; } +>rh6 : E.b | E.c | { a: string; } >a6 || a7 : E.b | E.c | { a: string; } >a6 : E >a7 : { a: string; } @@ -486,7 +486,7 @@ var ri5 = a5 || a8; // void || array is void | array >a8 : string[] var ri6 = a6 || a8; // enum || array is enum | array ->ri6 : E | string[] +>ri6 : E.b | E.c | string[] >a6 || a8 : E.b | E.c | string[] >a6 : E >a8 : string[] @@ -546,7 +546,7 @@ var rj5 = a5 || null; // void || null is void >null : null var rj6 = a6 || null; // enum || null is E ->rj6 : E +>rj6 : E.b | E.c >a6 || null : E.b | E.c >a6 : E >null : null @@ -606,7 +606,7 @@ var rf5 = a5 || undefined; // void || undefined is void >undefined : undefined var rf6 = a6 || undefined; // enum || undefined is E ->rf6 : E +>rf6 : E.b | E.c >a6 || undefined : E.b | E.c >a6 : E >undefined : undefined diff --git a/tests/baselines/reference/mergeWithImportedType.types b/tests/baselines/reference/mergeWithImportedType.types index ff647809287..7ba671ce468 100644 --- a/tests/baselines/reference/mergeWithImportedType.types +++ b/tests/baselines/reference/mergeWithImportedType.types @@ -1,7 +1,7 @@ === tests/cases/compiler/f1.ts === export enum E {X} >E : E ->X : E +>X : E.X === tests/cases/compiler/f2.ts === import {E} from "./f1"; diff --git a/tests/baselines/reference/mergedDeclarations2.types b/tests/baselines/reference/mergedDeclarations2.types index 15b548fa724..5d82d475d85 100644 --- a/tests/baselines/reference/mergedDeclarations2.types +++ b/tests/baselines/reference/mergedDeclarations2.types @@ -3,13 +3,13 @@ enum Foo { >Foo : Foo b ->b : Foo +>b : Foo.b } enum Foo { >Foo : Foo a = b ->a : Foo +>a : Foo.b >b : Foo } diff --git a/tests/baselines/reference/mergedEnumDeclarationCodeGen.types b/tests/baselines/reference/mergedEnumDeclarationCodeGen.types index 84e6a8237e5..1449ddcad6c 100644 --- a/tests/baselines/reference/mergedEnumDeclarationCodeGen.types +++ b/tests/baselines/reference/mergedEnumDeclarationCodeGen.types @@ -3,16 +3,16 @@ enum E { >E : E a, ->a : E +>a : E.a b = a ->b : E +>b : E.a >a : E } enum E { >E : E c = a ->c : E +>c : E.a >a : E } diff --git a/tests/baselines/reference/moduleCodeGenTest5.types b/tests/baselines/reference/moduleCodeGenTest5.types index b49c0c895d2..c0d806d9398 100644 --- a/tests/baselines/reference/moduleCodeGenTest5.types +++ b/tests/baselines/reference/moduleCodeGenTest5.types @@ -36,7 +36,7 @@ class C2{ export enum E1 {A=0} >E1 : E1 ->A : E1 +>A : E1.A >0 : 0 var u = E1.A; @@ -47,7 +47,7 @@ var u = E1.A; enum E2 {B=0} >E2 : E2 ->B : E2 +>B : E2.B >0 : 0 var v = E2.B; diff --git a/tests/baselines/reference/noImplicitAnyIndexing.types b/tests/baselines/reference/noImplicitAnyIndexing.types index 702c763c7a8..2bd27cb0c0b 100644 --- a/tests/baselines/reference/noImplicitAnyIndexing.types +++ b/tests/baselines/reference/noImplicitAnyIndexing.types @@ -3,7 +3,7 @@ enum MyEmusEnum { >MyEmusEnum : MyEmusEnum emu ->emu : MyEmusEnum +>emu : MyEmusEnum.emu } // Should be okay; should be a string. diff --git a/tests/baselines/reference/noImplicitAnyIndexingSuppressed.types b/tests/baselines/reference/noImplicitAnyIndexingSuppressed.types index fe34cdbc130..fe10152e90c 100644 --- a/tests/baselines/reference/noImplicitAnyIndexingSuppressed.types +++ b/tests/baselines/reference/noImplicitAnyIndexingSuppressed.types @@ -3,7 +3,7 @@ enum MyEmusEnum { >MyEmusEnum : MyEmusEnum emu ->emu : MyEmusEnum +>emu : MyEmusEnum.emu } // Should be okay; should be a string. diff --git a/tests/baselines/reference/nonExportedElementsOfMergedModules.types b/tests/baselines/reference/nonExportedElementsOfMergedModules.types index e0a11ecb6de..cd929474fac 100644 --- a/tests/baselines/reference/nonExportedElementsOfMergedModules.types +++ b/tests/baselines/reference/nonExportedElementsOfMergedModules.types @@ -4,7 +4,7 @@ module One { enum A { X } >A : A ->X : A +>X : A.X module B { >B : typeof B @@ -19,7 +19,7 @@ module One { enum A { Y } >A : A ->Y : A +>Y : A.Y module B { >B : typeof B diff --git a/tests/baselines/reference/nullAssignableToEveryType.types b/tests/baselines/reference/nullAssignableToEveryType.types index 1dd8cf400e7..e39c5121b2c 100644 --- a/tests/baselines/reference/nullAssignableToEveryType.types +++ b/tests/baselines/reference/nullAssignableToEveryType.types @@ -17,7 +17,7 @@ var ai: I; enum E { A } >E : E ->A : E +>A : E.A var ae: E; >ae : E diff --git a/tests/baselines/reference/nullIsSubtypeOfEverythingButUndefined.types b/tests/baselines/reference/nullIsSubtypeOfEverythingButUndefined.types index f598b4d7782..8139c9bcd76 100644 --- a/tests/baselines/reference/nullIsSubtypeOfEverythingButUndefined.types +++ b/tests/baselines/reference/nullIsSubtypeOfEverythingButUndefined.types @@ -219,7 +219,7 @@ var r12 = true ? null : c2; enum E { A } >E : E ->A : E +>A : E.A var r13 = true ? E : null; >r13 : typeof E diff --git a/tests/baselines/reference/numberAssignableToEnum.types b/tests/baselines/reference/numberAssignableToEnum.types index 44fa0ed042e..8b70b7f0e68 100644 --- a/tests/baselines/reference/numberAssignableToEnum.types +++ b/tests/baselines/reference/numberAssignableToEnum.types @@ -1,7 +1,7 @@ === tests/cases/conformance/types/typeRelationships/assignmentCompatibility/numberAssignableToEnum.ts === enum E { A } >E : E ->A : E +>A : E.A var n: number; >n : number diff --git a/tests/baselines/reference/objectTypesIdentity2.types b/tests/baselines/reference/objectTypesIdentity2.types index 3877fade0db..aa61a461507 100644 --- a/tests/baselines/reference/objectTypesIdentity2.types +++ b/tests/baselines/reference/objectTypesIdentity2.types @@ -33,7 +33,7 @@ var a: { foo: RegExp; } enum E { A } >E : E ->A : E +>A : E.A var b = { foo: E.A }; >b : { foo: E; } diff --git a/tests/baselines/reference/operatorAddNullUndefined.errors.txt b/tests/baselines/reference/operatorAddNullUndefined.errors.txt index c6a74080394..acd65de3417 100644 --- a/tests/baselines/reference/operatorAddNullUndefined.errors.txt +++ b/tests/baselines/reference/operatorAddNullUndefined.errors.txt @@ -6,10 +6,10 @@ tests/cases/compiler/operatorAddNullUndefined.ts(6,10): error TS2365: Operator ' tests/cases/compiler/operatorAddNullUndefined.ts(7,10): error TS2365: Operator '+' cannot be applied to types '1' and 'undefined'. tests/cases/compiler/operatorAddNullUndefined.ts(8,10): error TS2365: Operator '+' cannot be applied to types 'null' and '1'. tests/cases/compiler/operatorAddNullUndefined.ts(9,10): error TS2365: Operator '+' cannot be applied to types 'undefined' and '1'. -tests/cases/compiler/operatorAddNullUndefined.ts(14,11): error TS2365: Operator '+' cannot be applied to types 'null' and 'E'. -tests/cases/compiler/operatorAddNullUndefined.ts(15,11): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'E'. -tests/cases/compiler/operatorAddNullUndefined.ts(16,11): error TS2365: Operator '+' cannot be applied to types 'E' and 'null'. -tests/cases/compiler/operatorAddNullUndefined.ts(17,11): error TS2365: Operator '+' cannot be applied to types 'E' and 'undefined'. +tests/cases/compiler/operatorAddNullUndefined.ts(14,11): error TS2365: Operator '+' cannot be applied to types 'null' and 'E.x'. +tests/cases/compiler/operatorAddNullUndefined.ts(15,11): error TS2365: Operator '+' cannot be applied to types 'undefined' and 'E.x'. +tests/cases/compiler/operatorAddNullUndefined.ts(16,11): error TS2365: Operator '+' cannot be applied to types 'E.x' and 'null'. +tests/cases/compiler/operatorAddNullUndefined.ts(17,11): error TS2365: Operator '+' cannot be applied to types 'E.x' and 'undefined'. ==== tests/cases/compiler/operatorAddNullUndefined.ts (12 errors) ==== @@ -44,13 +44,13 @@ tests/cases/compiler/operatorAddNullUndefined.ts(17,11): error TS2365: Operator var x12 = undefined + "test"; var x13 = null + E.x ~~~~~~~~~~ -!!! error TS2365: Operator '+' cannot be applied to types 'null' and 'E'. +!!! error TS2365: Operator '+' cannot be applied to types 'null' and 'E.x'. var x14 = undefined + E.x ~~~~~~~~~~~~~~~ -!!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'E'. +!!! error TS2365: Operator '+' cannot be applied to types 'undefined' and 'E.x'. var x15 = E.x + null ~~~~~~~~~~ -!!! error TS2365: Operator '+' cannot be applied to types 'E' and 'null'. +!!! error TS2365: Operator '+' cannot be applied to types 'E.x' and 'null'. var x16 = E.x + undefined ~~~~~~~~~~~~~~~ -!!! error TS2365: Operator '+' cannot be applied to types 'E' and 'undefined'. \ No newline at end of file +!!! error TS2365: Operator '+' cannot be applied to types 'E.x' and 'undefined'. \ No newline at end of file diff --git a/tests/baselines/reference/operatorAddNullUndefined.types b/tests/baselines/reference/operatorAddNullUndefined.types index 63b389f70f4..c24acd2a7ec 100644 --- a/tests/baselines/reference/operatorAddNullUndefined.types +++ b/tests/baselines/reference/operatorAddNullUndefined.types @@ -1,7 +1,7 @@ === tests/cases/compiler/operatorAddNullUndefined.ts === enum E { x } >E : E ->x : E +>x : E.x var x1 = null + null; >x1 : any diff --git a/tests/baselines/reference/parseEntityNameWithReservedWord.types b/tests/baselines/reference/parseEntityNameWithReservedWord.types index 551125c55ac..e3024dae16e 100644 --- a/tests/baselines/reference/parseEntityNameWithReservedWord.types +++ b/tests/baselines/reference/parseEntityNameWithReservedWord.types @@ -1,7 +1,7 @@ === tests/cases/compiler/parseEntityNameWithReservedWord.ts === enum Bool { false } >Bool : Bool ->false : Bool +>false : Bool.false const x: Bool.false = Bool.false; >x : Bool diff --git a/tests/baselines/reference/parserComputedPropertyName16.types b/tests/baselines/reference/parserComputedPropertyName16.types index b6440d89f0f..0ccd4470d9d 100644 --- a/tests/baselines/reference/parserComputedPropertyName16.types +++ b/tests/baselines/reference/parserComputedPropertyName16.types @@ -3,7 +3,7 @@ enum E { >E : E [e] = 1 ->[e] : E +>[e] : E.__computed >e : any >1 : 1 } diff --git a/tests/baselines/reference/parserES5ComputedPropertyName6.types b/tests/baselines/reference/parserES5ComputedPropertyName6.types index cbfa5ec1f8d..61d9fa24b9a 100644 --- a/tests/baselines/reference/parserES5ComputedPropertyName6.types +++ b/tests/baselines/reference/parserES5ComputedPropertyName6.types @@ -3,7 +3,7 @@ enum E { >E : E [e] = 1 ->[e] : E +>[e] : E.__computed >e : any >1 : 1 } diff --git a/tests/baselines/reference/parserEnum5.types b/tests/baselines/reference/parserEnum5.types index 5d9e30c0932..c49a62333e0 100644 --- a/tests/baselines/reference/parserEnum5.types +++ b/tests/baselines/reference/parserEnum5.types @@ -1,7 +1,7 @@ === tests/cases/conformance/parser/ecmascript5/EnumDeclarations/parserEnum5.ts === enum E2 { a, } >E2 : E2 ->a : E2 +>a : E2.a enum E3 { a: 1, } >E3 : E3 diff --git a/tests/baselines/reference/parserEnumDeclaration3.d.types b/tests/baselines/reference/parserEnumDeclaration3.d.types index 4b741ec38ef..090556475ea 100644 --- a/tests/baselines/reference/parserEnumDeclaration3.d.types +++ b/tests/baselines/reference/parserEnumDeclaration3.d.types @@ -3,6 +3,6 @@ enum E { >E : E A = 1 ->A : E +>A : E.A >1 : 1 } diff --git a/tests/baselines/reference/parserEnumDeclaration3.types b/tests/baselines/reference/parserEnumDeclaration3.types index 027f837229f..de3e32fcbcf 100644 --- a/tests/baselines/reference/parserEnumDeclaration3.types +++ b/tests/baselines/reference/parserEnumDeclaration3.types @@ -3,6 +3,6 @@ declare enum E { >E : E A = 1 ->A : E +>A : E.A >1 : 1 } diff --git a/tests/baselines/reference/parserInterfaceKeywordInEnum.types b/tests/baselines/reference/parserInterfaceKeywordInEnum.types index aa71126883d..f648c3d2796 100644 --- a/tests/baselines/reference/parserInterfaceKeywordInEnum.types +++ b/tests/baselines/reference/parserInterfaceKeywordInEnum.types @@ -3,6 +3,6 @@ enum Bar { >Bar : Bar interface, ->interface : Bar +>interface : Bar.interface } diff --git a/tests/baselines/reference/parserInterfaceKeywordInEnum1.types b/tests/baselines/reference/parserInterfaceKeywordInEnum1.types index 57c4ef2ebec..687e01b4654 100644 --- a/tests/baselines/reference/parserInterfaceKeywordInEnum1.types +++ b/tests/baselines/reference/parserInterfaceKeywordInEnum1.types @@ -6,6 +6,6 @@ enum Bar { >Bar : Bar interface, ->interface : Bar +>interface : Bar.interface } diff --git a/tests/baselines/reference/preserveConstEnums.types b/tests/baselines/reference/preserveConstEnums.types index 9f2d30a3604..ded9ca90d74 100644 --- a/tests/baselines/reference/preserveConstEnums.types +++ b/tests/baselines/reference/preserveConstEnums.types @@ -3,8 +3,8 @@ const enum E { >E : E Value = 1, Value2 = Value ->Value : E +>Value : E.Value >1 : 1 ->Value2 : E +>Value2 : E.Value >Value : E } diff --git a/tests/baselines/reference/primtiveTypesAreIdentical.types b/tests/baselines/reference/primtiveTypesAreIdentical.types index f84a6257b8c..43b9f2e785a 100644 --- a/tests/baselines/reference/primtiveTypesAreIdentical.types +++ b/tests/baselines/reference/primtiveTypesAreIdentical.types @@ -67,7 +67,7 @@ function foo5(x: any) { } enum E { A } >E : E ->A : E +>A : E.A function foo6(x: E); >foo6 : { (x: E): any; (x: E): any; } diff --git a/tests/baselines/reference/reachabilityChecks1.types b/tests/baselines/reference/reachabilityChecks1.types index 1f74c302c64..6d054748ab9 100644 --- a/tests/baselines/reference/reachabilityChecks1.types +++ b/tests/baselines/reference/reachabilityChecks1.types @@ -61,7 +61,7 @@ module A4 { module A { const enum E { X } >E : E ->X : E +>X : E.X } } @@ -112,7 +112,7 @@ function f3() { >E : E X = 1 ->X : E +>X : E.X >1 : 1 } } @@ -131,7 +131,7 @@ function f4() { >E : E X = 1 ->X : E +>X : E.X >1 : 1 } } diff --git a/tests/baselines/reference/reachabilityChecks2.types b/tests/baselines/reference/reachabilityChecks2.types index 6268ca5012e..351f2c27adc 100644 --- a/tests/baselines/reference/reachabilityChecks2.types +++ b/tests/baselines/reference/reachabilityChecks2.types @@ -4,7 +4,7 @@ while (true) { } const enum E { X } >E : E ->X : E +>X : E.X module A4 { >A4 : typeof A4 @@ -15,7 +15,7 @@ module A4 { module A { const enum E { X } >E : E ->X : E +>X : E.X } } diff --git a/tests/baselines/reference/strictModeEnumMemberNameReserved.types b/tests/baselines/reference/strictModeEnumMemberNameReserved.types index 557dfcccc67..ed19db7b4bc 100644 --- a/tests/baselines/reference/strictModeEnumMemberNameReserved.types +++ b/tests/baselines/reference/strictModeEnumMemberNameReserved.types @@ -6,7 +6,7 @@ enum E { >E : E static ->static : E +>static : E.static } const x1: E.static = E.static; diff --git a/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.types b/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.types index d95dc856575..be2231fdfb3 100644 --- a/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.types +++ b/tests/baselines/reference/stringLiteralTypeIsSubtypeOfString.types @@ -279,7 +279,7 @@ function f13(x: any) { } enum E { A } >E : E ->A : E +>A : E.A function f14(x: 'a'); >f14 : { (x: "a"): any; (x: E): any; } diff --git a/tests/baselines/reference/subtypesOfAny.types b/tests/baselines/reference/subtypesOfAny.types index cdb9469b6a4..903997a7bbc 100644 --- a/tests/baselines/reference/subtypesOfAny.types +++ b/tests/baselines/reference/subtypesOfAny.types @@ -129,7 +129,7 @@ interface I13 { enum E { A } >E : E ->A : E +>A : E.A interface I14 { [x: string]: any; diff --git a/tests/baselines/reference/subtypesOfTypeParameter.types b/tests/baselines/reference/subtypesOfTypeParameter.types index 590f827d2b3..02d4d527786 100644 --- a/tests/baselines/reference/subtypesOfTypeParameter.types +++ b/tests/baselines/reference/subtypesOfTypeParameter.types @@ -49,7 +49,7 @@ class C2 { foo: T; } enum E { A } >E : E ->A : E +>A : E.A function f() { } >f : typeof f diff --git a/tests/baselines/reference/subtypesOfTypeParameterWithConstraints2.types b/tests/baselines/reference/subtypesOfTypeParameterWithConstraints2.types index 270840b06a9..daf700b06f2 100644 --- a/tests/baselines/reference/subtypesOfTypeParameterWithConstraints2.types +++ b/tests/baselines/reference/subtypesOfTypeParameterWithConstraints2.types @@ -142,7 +142,7 @@ class C2 { foo: T; } enum E { A } >E : E ->A : E +>A : E.A function f() { } >f : typeof f diff --git a/tests/baselines/reference/systemModuleAmbientDeclarations.types b/tests/baselines/reference/systemModuleAmbientDeclarations.types index 83a1bb857c7..9fcea7b874e 100644 --- a/tests/baselines/reference/systemModuleAmbientDeclarations.types +++ b/tests/baselines/reference/systemModuleAmbientDeclarations.types @@ -10,7 +10,7 @@ declare class C {} declare enum E {X = 1}; >E : E ->X : E +>X : E.X >1 : 1 export var promise = Promise; @@ -44,7 +44,7 @@ export declare var v: number; === tests/cases/compiler/file5.ts === export declare enum E {X = 1} >E : E ->X : E +>X : E.X >1 : 1 === tests/cases/compiler/file6.ts === diff --git a/tests/baselines/reference/systemModuleConstEnums.types b/tests/baselines/reference/systemModuleConstEnums.types index cbfb339c3e3..9c214416018 100644 --- a/tests/baselines/reference/systemModuleConstEnums.types +++ b/tests/baselines/reference/systemModuleConstEnums.types @@ -5,7 +5,7 @@ declare function use(a: any); const enum TopLevelConstEnum { X } >TopLevelConstEnum : TopLevelConstEnum ->X : TopLevelConstEnum +>X : TopLevelConstEnum.X export function foo() { >foo : () => void @@ -30,5 +30,5 @@ export function foo() { module M { export const enum NonTopLevelConstEnum { X } >NonTopLevelConstEnum : NonTopLevelConstEnum ->X : NonTopLevelConstEnum +>X : NonTopLevelConstEnum.X } diff --git a/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.types b/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.types index 55c37d31a80..8b62ffe063f 100644 --- a/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.types +++ b/tests/baselines/reference/systemModuleConstEnumsSeparateCompilation.types @@ -5,7 +5,7 @@ declare function use(a: any); const enum TopLevelConstEnum { X } >TopLevelConstEnum : TopLevelConstEnum ->X : TopLevelConstEnum +>X : TopLevelConstEnum.X export function foo() { >foo : () => void @@ -30,5 +30,5 @@ export function foo() { module M { export const enum NonTopLevelConstEnum { X } >NonTopLevelConstEnum : NonTopLevelConstEnum ->X : NonTopLevelConstEnum +>X : NonTopLevelConstEnum.X } diff --git a/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.types b/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.types index 61edb6db4b0..b96402770fd 100644 --- a/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.types +++ b/tests/baselines/reference/systemModuleNonTopLevelModuleMembers.types @@ -11,7 +11,7 @@ export function TopLevelFunction(): void {} export enum TopLevelEnum {E} >TopLevelEnum : TopLevelEnum ->E : TopLevelEnum +>E : TopLevelEnum.E export module TopLevelModule2 { >TopLevelModule2 : typeof TopLevelModule2 @@ -28,5 +28,5 @@ export module TopLevelModule2 { export enum NonTopLevelEnum {E} >NonTopLevelEnum : NonTopLevelEnum ->E : NonTopLevelEnum +>E : NonTopLevelEnum.E } diff --git a/tests/baselines/reference/tsxDefaultImports.types b/tests/baselines/reference/tsxDefaultImports.types index 08c00256e0e..a798e88fd89 100644 --- a/tests/baselines/reference/tsxDefaultImports.types +++ b/tests/baselines/reference/tsxDefaultImports.types @@ -3,7 +3,7 @@ enum SomeEnum { >SomeEnum : SomeEnum one, ->one : SomeEnum +>one : SomeEnum.one } export default class SomeClass { >SomeClass : SomeClass diff --git a/tests/baselines/reference/typeAliases.types b/tests/baselines/reference/typeAliases.types index 06dc8d4f327..8790c043adf 100644 --- a/tests/baselines/reference/typeAliases.types +++ b/tests/baselines/reference/typeAliases.types @@ -161,7 +161,7 @@ type Meters = number enum E { x = 10 } >E : E ->x : E +>x : E.x >10 : 10 declare function f15(a: string): boolean; diff --git a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.types b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.types index cb032dc0021..380e1eb686b 100644 --- a/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.types +++ b/tests/baselines/reference/typeArgumentInferenceWithObjectLiteral.types @@ -57,11 +57,11 @@ foo({ enum E1 { X } >E1 : E1 ->X : E1 +>X : E1.X enum E2 { X } >E2 : E2 ->X : E2 +>X : E2.X // Check that we infer from both a.r and b before fixing T in a.w @@ -129,10 +129,10 @@ var v2 = f1({ w: x => x, r: () => E1.X }, E1.X); >v2 : E1 >f1({ w: x => x, r: () => E1.X }, E1.X) : E1 >f1 : (a: { w: (x: T) => U; r: () => T; }, b: T) => U ->{ w: x => x, r: () => E1.X } : { w: (x: E1) => E1; r: () => E1; } ->w : (x: E1) => E1 ->x => x : (x: E1) => E1 ->x : E1 +>{ w: x => x, r: () => E1.X } : { w: (x: E1.X) => E1; r: () => E1; } +>w : (x: E1.X) => E1 +>x => x : (x: E1.X) => E1 +>x : E1.X >x : E1 >r : () => E1 >() => E1.X : () => E1 diff --git a/tests/baselines/reference/typeofANonExportedType.types b/tests/baselines/reference/typeofANonExportedType.types index 6a924e6a11d..2d4afac5e69 100644 --- a/tests/baselines/reference/typeofANonExportedType.types +++ b/tests/baselines/reference/typeofANonExportedType.types @@ -101,7 +101,7 @@ enum E { >E : E A ->A : E +>A : E.A } export var r10: typeof E; >r10 : typeof E diff --git a/tests/baselines/reference/typeofAnExportedType.types b/tests/baselines/reference/typeofAnExportedType.types index 21817a0a573..afd2b737c2f 100644 --- a/tests/baselines/reference/typeofAnExportedType.types +++ b/tests/baselines/reference/typeofAnExportedType.types @@ -101,7 +101,7 @@ export enum E { >E : E A ->A : E +>A : E.A } export var r10: typeof E; >r10 : typeof E diff --git a/tests/baselines/reference/undefinedAssignableToEveryType.types b/tests/baselines/reference/undefinedAssignableToEveryType.types index 005f2451f2a..6456ed7c859 100644 --- a/tests/baselines/reference/undefinedAssignableToEveryType.types +++ b/tests/baselines/reference/undefinedAssignableToEveryType.types @@ -17,7 +17,7 @@ var ai: I; enum E { A } >E : E ->A : E +>A : E.A var ae: E; >ae : E diff --git a/tests/baselines/reference/undefinedIsSubtypeOfEverything.types b/tests/baselines/reference/undefinedIsSubtypeOfEverything.types index 31d92c98ccf..90fd5324343 100644 --- a/tests/baselines/reference/undefinedIsSubtypeOfEverything.types +++ b/tests/baselines/reference/undefinedIsSubtypeOfEverything.types @@ -143,7 +143,7 @@ class D10 extends Base { enum E { A } >E : E ->A : E +>A : E.A class D11 extends Base { >D11 : D11 diff --git a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.types b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.types index 53414d53df2..91298487cdb 100644 --- a/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.types +++ b/tests/baselines/reference/unionSubtypeIfEveryConstituentTypeIsSubtype.types @@ -175,7 +175,7 @@ interface I13 { enum E2 { A } >E2 : E2 ->A : E2 +>A : E2.A interface I14 { [x: string]: E2; diff --git a/tests/baselines/reference/validNullAssignments.types b/tests/baselines/reference/validNullAssignments.types index 98b83a63e1b..5c27f320261 100644 --- a/tests/baselines/reference/validNullAssignments.types +++ b/tests/baselines/reference/validNullAssignments.types @@ -27,7 +27,7 @@ e = null; // ok enum E { A } >E : E ->A : E +>A : E.A E.A = null; // error >E.A = null : null diff --git a/tests/baselines/reference/validNumberAssignments.types b/tests/baselines/reference/validNumberAssignments.types index 5f6304eb1cd..fa9df93717a 100644 --- a/tests/baselines/reference/validNumberAssignments.types +++ b/tests/baselines/reference/validNumberAssignments.types @@ -17,7 +17,7 @@ var c: number = x; enum E { A }; >E : E ->A : E +>A : E.A var d: E = x; >d : E diff --git a/tests/cases/compiler/ambientConstLiterals.ts b/tests/cases/compiler/ambientConstLiterals.ts index 040b739bf93..d42b8524998 100644 --- a/tests/cases/compiler/ambientConstLiterals.ts +++ b/tests/cases/compiler/ambientConstLiterals.ts @@ -4,7 +4,7 @@ function f(x: T): T { return x; } -enum E { A, B, C } +enum E { A, B, C, "non identifier" } const c1 = "abc"; const c2 = 123; @@ -14,6 +14,7 @@ const c5 = f(123); const c6 = f(-123); const c7 = true; const c8 = E.A; +const c8b = E["non identifier"]; const c9 = { x: "abc" }; const c10 = [123]; const c11 = "abc" + "def"; diff --git a/tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts b/tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts new file mode 100644 index 00000000000..fc74d6cab4d --- /dev/null +++ b/tests/cases/compiler/declarationEmitEnumReadonlyProperty.ts @@ -0,0 +1,11 @@ +// @declaration: true +enum E { + A = 'a', + B = 'b' +} + +class C { + readonly type = E.A; +} + +let x: E.A = new C().type; \ No newline at end of file diff --git a/tests/cases/compiler/enumLiteralUnionNotWidened.ts b/tests/cases/compiler/enumLiteralUnionNotWidened.ts new file mode 100644 index 00000000000..407d29b2922 --- /dev/null +++ b/tests/cases/compiler/enumLiteralUnionNotWidened.ts @@ -0,0 +1,20 @@ +// repro from #22093 +enum A { one = "one", two = "two" }; +enum B { foo = "foo", bar = "bar" }; + +type C = A | B.foo; +type D = A | "foo"; + +class List +{ + private readonly items: T[] = []; +} + +function asList(arg: T): List { return new List(); } + +// TypeScript incorrectly infers the return type of "asList(x)" to be "List" +// The correct type is "List" +function fn1(x: C): List { return asList(x); } + +// If we use the literal "foo" instead of B.foo, the correct type is inferred +function fn2(x: D): List { return asList(x); } \ No newline at end of file From b1430e5e2c79c0a121f030dac45f006bcd9018fe Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 7 Sep 2018 12:18:03 -0700 Subject: [PATCH 064/146] Avoid adding duplicate completion from contextual keyword (#26947) --- src/services/completions.ts | 11 +++++++++-- .../server/completionEntryDetailAcrossFiles02.ts | 8 ++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index 3edc1cc4f56..16e48dc56b6 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -144,7 +144,14 @@ namespace ts.Completions { getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); } - addRange(entries, getKeywordCompletions(keywordFilters)); + if (keywordFilters !== KeywordCompletionFilters.None) { + const entryNames = arrayToSet(entries, e => e.name); + for (const keywordEntry of getKeywordCompletions(keywordFilters)) { + if (!entryNames.has(keywordEntry.name)) { + entries.push(keywordEntry); + } + } + } for (const literal of literals) { entries.push(createCompletionEntryForLiteral(literal)); @@ -180,7 +187,7 @@ namespace ts.Completions { return; } const realName = unescapeLeadingUnderscores(name); - if (addToSeen(uniqueNames, realName) && isIdentifierText(realName, target) && !isStringANonContextualKeyword(realName)) { + if (addToSeen(uniqueNames, realName) && isIdentifierText(realName, target)) { entries.push({ name: realName, kind: ScriptElementKind.warning, diff --git a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts index 2c5e53ea224..1c499efc7e2 100644 --- a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts +++ b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts @@ -14,7 +14,7 @@ //// import a = require("./a"); //// a.fo/*2*/ -goTo.marker('1'); -verify.completionEntryDetailIs("foo", "var foo: (p1: string) => void", "Modify the parameter"); -goTo.marker('2'); -verify.completionEntryDetailIs("foo", "(property) a.foo: (p1: string) => void", "Modify the parameter"); +verify.completions( + { marker: "1", includes: { name: "foo", text: "var foo: (p1: string) => void", documentation: "Modify the parameter" } }, + { marker: "2", exact: { name: "foo", text: "(property) a.foo: (p1: string) => void", documentation: "Modify the parameter" } }, +); From cbde861af6324f03a574b1bcc4f241d38fa17c77 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 7 Sep 2018 12:23:23 -0700 Subject: [PATCH 065/146] Improve use of SemanticMeaning in symbol display (#26953) --- src/services/symbolDisplay.ts | 10 +++++++--- src/services/utilities.ts | 2 +- .../fourslash/findAllRefsForDefaultExport02.ts | 5 ++--- .../findAllRefs_importType_exportEquals.ts | 2 +- .../findAllRefs_importType_meaningAtLocation.ts | 4 ++-- .../jsdocTypedefTagSemanticMeaning0.ts | 4 ++-- .../quickInfoImportedTypesWithMergedMeanings.ts | 17 +++++++++++++++-- tests/cases/fourslash/quickInfoJsdocEnum.ts | 9 ++++++--- tests/cases/fourslash/quickInfoOnThis.ts | 2 +- .../referencesForMergedDeclarations.ts | 4 ++-- .../referencesForMergedDeclarations5.ts | 4 ++-- .../referencesForMergedDeclarations7.ts | 4 ++-- .../referencesForMergedDeclarations8.ts | 2 +- 13 files changed, 44 insertions(+), 25 deletions(-) diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index d1d8709bef2..cc59aa3c0ce 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -128,14 +128,18 @@ namespace ts.SymbolDisplay { let documentation: SymbolDisplayPart[] | undefined; let tags: JSDocTagInfo[] | undefined; const symbolFlags = getCombinedLocalAndExportSymbolFlags(symbol); - let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location); + let symbolKind = semanticMeaning & SemanticMeaning.Value ? getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(typeChecker, symbol, location) : ScriptElementKind.unknown; let hasAddedSymbolInfo = false; - const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isExpression(location); + const isThisExpression = location.kind === SyntaxKind.ThisKeyword && isInExpressionContext(location); let type: Type | undefined; let printer: Printer; let documentationFromAlias: SymbolDisplayPart[] | undefined; let tagsFromAlias: JSDocTagInfo[] | undefined; + if (location.kind === SyntaxKind.ThisKeyword && !isThisExpression) { + return { displayParts: [keywordPart(SyntaxKind.ThisKeyword)], documentation: [], symbolKind: ScriptElementKind.primitiveType, tags: undefined }; + } + // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== ScriptElementKind.unknown || symbolFlags & SymbolFlags.Class || symbolFlags & SymbolFlags.Alias) { // If it is accessor they are allowed only if location is at name of the accessor @@ -285,7 +289,7 @@ namespace ts.SymbolDisplay { addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } - if (symbolFlags & SymbolFlags.TypeAlias) { + if ((symbolFlags & SymbolFlags.TypeAlias) && (semanticMeaning & SemanticMeaning.Type)) { prefixNextMeaning(); displayParts.push(keywordPart(SyntaxKind.TypeKeyword)); displayParts.push(spacePart()); diff --git a/src/services/utilities.ts b/src/services/utilities.ts index b8a235bbeb4..1c10bc983fd 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -88,7 +88,7 @@ namespace ts { if (node.kind === SyntaxKind.SourceFile) { return SemanticMeaning.Value; } - else if (node.parent.kind === SyntaxKind.ExportAssignment) { + else if (node.parent.kind === SyntaxKind.ExportAssignment || node.parent.kind === SyntaxKind.ExternalModuleReference) { return SemanticMeaning.All; } else if (isInRightSideOfInternalImportEqualsDeclaration(node)) { diff --git a/tests/cases/fourslash/findAllRefsForDefaultExport02.ts b/tests/cases/fourslash/findAllRefsForDefaultExport02.ts index 6ad8b29b5ce..c664b470938 100644 --- a/tests/cases/fourslash/findAllRefsForDefaultExport02.ts +++ b/tests/cases/fourslash/findAllRefsForDefaultExport02.ts @@ -15,9 +15,8 @@ const ranges = test.ranges(); const [r0, r1, r2, r3, r4] = ranges; const fnRanges = [r0, r1, r2, r3]; -const fn = "function DefaultExportedFunction(): () => typeof DefaultExportedFunction"; -verify.singleReferenceGroup(fn, fnRanges); +verify.singleReferenceGroup("function DefaultExportedFunction(): () => typeof DefaultExportedFunction", fnRanges); // The namespace and function do not merge, // so the namespace should be all alone. -verify.singleReferenceGroup(`namespace DefaultExportedFunction\n${fn}`, [r4]); +verify.singleReferenceGroup(`namespace DefaultExportedFunction`, [r4]); diff --git a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts index 010f7f31890..c944f2468c5 100644 --- a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts +++ b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts @@ -15,7 +15,7 @@ verify.noErrors(); const [r0, r1, r2, r3, r4] = test.ranges(); verify.referenceGroups(r0, [{ definition: "type T = number\nnamespace T", ranges: [r0, r2, r3] }]); -verify.referenceGroups(r1, [{ definition: "type T = number\nnamespace T", ranges: [r1, r2] }]); +verify.referenceGroups(r1, [{ definition: "namespace T", ranges: [r1, r2] }]); verify.referenceGroups(r2, [{ definition: "type T = number\nnamespace T", ranges: [r0, r1, r2, r3] }]); verify.referenceGroups([r3, r4], [ { definition: 'module "/a"', ranges: [r4] }, diff --git a/tests/cases/fourslash/findAllRefs_importType_meaningAtLocation.ts b/tests/cases/fourslash/findAllRefs_importType_meaningAtLocation.ts index 4bb5cb27a17..4c79999a866 100644 --- a/tests/cases/fourslash/findAllRefs_importType_meaningAtLocation.ts +++ b/tests/cases/fourslash/findAllRefs_importType_meaningAtLocation.ts @@ -9,5 +9,5 @@ ////const x: typeof import("./a").[|T|] = 0; const [r0, r1, r2, r3] = test.ranges(); -verify.singleReferenceGroup("type T = 0\nconst T: 0", [r0, r2]); -verify.singleReferenceGroup("type T = 0\nconst T: 0", [r1, r3]); +verify.singleReferenceGroup("type T = 0", [r0, r2]); +verify.singleReferenceGroup("const T: 0", [r1, r3]); diff --git a/tests/cases/fourslash/jsdocTypedefTagSemanticMeaning0.ts b/tests/cases/fourslash/jsdocTypedefTagSemanticMeaning0.ts index 3673c86b381..c45f4aadc80 100644 --- a/tests/cases/fourslash/jsdocTypedefTagSemanticMeaning0.ts +++ b/tests/cases/fourslash/jsdocTypedefTagSemanticMeaning0.ts @@ -12,5 +12,5 @@ const [t0, v0, t1, v1] = test.ranges(); -verify.singleReferenceGroup("type T = number\nconst T: 1", [t0, t1]); -verify.singleReferenceGroup("type T = number\nconst T: 1", [v0, v1]); +verify.singleReferenceGroup("type T = number", [t0, t1]); +verify.singleReferenceGroup("const T: 1", [v0, v1]); diff --git a/tests/cases/fourslash/quickInfoImportedTypesWithMergedMeanings.ts b/tests/cases/fourslash/quickInfoImportedTypesWithMergedMeanings.ts index f63b295aa4c..ee8c052e3ea 100644 --- a/tests/cases/fourslash/quickInfoImportedTypesWithMergedMeanings.ts +++ b/tests/cases/fourslash/quickInfoImportedTypesWithMergedMeanings.ts @@ -10,8 +10,9 @@ //// export { Original/*1*/ } from './quickInfoImportedTypesWithMergedMeanings'; // @Filename: importer.ts -//// import { Original as Alias } from './quickInfoImportedTypesWithMergedMeanings'; -//// Alias/*2*/; +//// import { Original as /*2*/Alias } from './quickInfoImportedTypesWithMergedMeanings'; +//// Alias/*3*/; +//// let x: Alias/*4*/ verify.quickInfoAt("1", [ "(alias) function Original(): void", @@ -26,3 +27,15 @@ verify.quickInfoAt("2", [ "(alias) namespace Alias", "import Alias", ].join("\n"), "some docs"); + +verify.quickInfoAt("3", [ + "(alias) function Alias(): void", + "(alias) namespace Alias", + "import Alias", +].join("\n"), "some docs"); + +verify.quickInfoAt("4", [ + "(alias) type Alias = () => T", + "(alias) namespace Alias", + "import Alias", +].join("\n"), "some docs"); diff --git a/tests/cases/fourslash/quickInfoJsdocEnum.ts b/tests/cases/fourslash/quickInfoJsdocEnum.ts index de67cacc7d2..9ef3b1edc78 100644 --- a/tests/cases/fourslash/quickInfoJsdocEnum.ts +++ b/tests/cases/fourslash/quickInfoJsdocEnum.ts @@ -12,12 +12,15 @@ //// A: 0, ////} //// -/////** @type {/**/E} */ -////const x = E.A; +/////** @type {/*type*/E} */ +////const x = /*value*/E.A; verify.noErrors(); -verify.quickInfoAt("", +verify.quickInfoAt("type", +`enum E`, +"Doc"); +verify.quickInfoAt("value", `enum E const E: { A: number; diff --git a/tests/cases/fourslash/quickInfoOnThis.ts b/tests/cases/fourslash/quickInfoOnThis.ts index 26fc14587ac..acbab64ae33 100644 --- a/tests/cases/fourslash/quickInfoOnThis.ts +++ b/tests/cases/fourslash/quickInfoOnThis.ts @@ -23,7 +23,7 @@ ////} verify.quickInfos({ - 0: "this: this", + 0: "this", 1: "this: void", 2: "this: this", 3: "(parameter) this: Restricted", diff --git a/tests/cases/fourslash/referencesForMergedDeclarations.ts b/tests/cases/fourslash/referencesForMergedDeclarations.ts index a6a5220497a..5346a85f24f 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations.ts @@ -15,6 +15,6 @@ ////[|Foo|].bind(this); const [type1, namespace1, value1, namespace2, type2, value2] = test.ranges(); -verify.singleReferenceGroup("interface Foo\nnamespace Foo\nfunction Foo(): void", [type1, type2]); -verify.singleReferenceGroup("namespace Foo\nfunction Foo(): void", [namespace1, namespace2]); +verify.singleReferenceGroup("interface Foo\nnamespace Foo", [type1, type2]); +verify.singleReferenceGroup("namespace Foo", [namespace1, namespace2]); verify.singleReferenceGroup("namespace Foo\nfunction Foo(): void", [value1, value2]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations5.ts b/tests/cases/fourslash/referencesForMergedDeclarations5.ts index 0116389a4de..40b43eb6819 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations5.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations5.ts @@ -8,7 +8,7 @@ const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; -verify.referenceGroups(r0, [{ definition: "interface Foo\nnamespace Foo\nfunction Foo(): void", ranges: [r0, r3] }]); -verify.referenceGroups(r1, [{ definition: "namespace Foo\nfunction Foo(): void", ranges: [r1, r3] }]); +verify.referenceGroups(r0, [{ definition: "interface Foo\nnamespace Foo", ranges: [r0, r3] }]); +verify.referenceGroups(r1, [{ definition: "namespace Foo", ranges: [r1, r3] }]); verify.referenceGroups(r2, [{ definition: "namespace Foo\nfunction Foo(): void", ranges: [r2, r3] }]); verify.referenceGroups(r3, [{ definition: "interface Foo\nnamespace Foo\nfunction Foo(): void", ranges }]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations7.ts b/tests/cases/fourslash/referencesForMergedDeclarations7.ts index 7defbecf6a1..c119992c8bc 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations7.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations7.ts @@ -12,7 +12,7 @@ const ranges = test.ranges(); const [r0, r1, r2, r3] = ranges; -verify.referenceGroups(r0, [{ definition: "interface Foo.Bar\nnamespace Foo.Bar\nfunction Foo.Bar(): void", ranges: [r0, r3] }]); -verify.referenceGroups(r1, [{ definition: "namespace Foo.Bar\nfunction Foo.Bar(): void", ranges: [r1, r3] }]); +verify.referenceGroups(r0, [{ definition: "interface Foo.Bar\nnamespace Foo.Bar", ranges: [r0, r3] }]); +verify.referenceGroups(r1, [{ definition: "namespace Foo.Bar", ranges: [r1, r3] }]); verify.referenceGroups(r2, [{ definition: "namespace Foo.Bar\nfunction Foo.Bar(): void", ranges: [r2, r3] }]); verify.referenceGroups(r3, [{ definition: "interface Foo.Bar\nnamespace Foo.Bar\nfunction Foo.Bar(): void", ranges }]); diff --git a/tests/cases/fourslash/referencesForMergedDeclarations8.ts b/tests/cases/fourslash/referencesForMergedDeclarations8.ts index 742561e21c5..4b4716c08a5 100644 --- a/tests/cases/fourslash/referencesForMergedDeclarations8.ts +++ b/tests/cases/fourslash/referencesForMergedDeclarations8.ts @@ -10,4 +10,4 @@ ////// module ////import a3 = Foo.[|Bar|].Baz; -verify.singleReferenceGroup("namespace Foo.Bar\nfunction Foo.Bar(): void"); +verify.singleReferenceGroup("namespace Foo.Bar"); From 95d57885c5efd05d3cb35fb8f7816a98bf56f1c6 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Fri, 7 Sep 2018 14:14:01 -0700 Subject: [PATCH 066/146] Ensure diagnostic reporting matches code fix ability --- .../codefixes/convertToAsyncFunction.ts | 11 +-- src/services/suggestionDiagnostics.ts | 39 +++++++++- src/services/utilities.ts | 8 ++ .../unittests/convertToAsyncFunction.ts | 76 ++++++++----------- 4 files changed, 79 insertions(+), 55 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 61e142a8a08..ba230aa95e4 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -254,6 +254,7 @@ namespace ts.codefix { } // dispatch function to recursively build the refactoring + // should be kept up to date with isFixablePromiseHandler in suggestionDiagnostics.ts function transformExpression(node: Expression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { if (!node) { return []; @@ -275,6 +276,7 @@ namespace ts.codefix { return transformPromiseCall(node, transformer, prevArgName); } + codeActionSucceeded = false; return []; } @@ -383,6 +385,7 @@ namespace ts.codefix { (createVariableDeclarationList([createVariableDeclaration(getSynthesizedDeepClone(prevArgName.identifier), /*type*/ undefined, rightHandSide)], getFlagOfIdentifier(prevArgName.identifier, transformer.constIdentifiers))))]); } + // should be kept up to date with isFixablePromiseArgument in suggestionDiagnostics.ts function getTransformationBody(func: Node, prevArgName: SynthIdentifier | undefined, argName: SynthIdentifier, parent: CallExpression, transformer: Transformer): NodeArray { const hasPrevArgName = prevArgName && prevArgName.identifier.text.length > 0; @@ -500,14 +503,6 @@ namespace ts.codefix { return innerCbBody; } - function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { - if (!isPropertyAccessExpression(node.expression)) { - return false; - } - - return node.expression.name.text === funcName; - } - function getArgName(funcNode: Node, transformer: Transformer): SynthIdentifier { const numberOfAssignmentsOriginal = 0; diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 167bcb6bbac..3df40c8d9df 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -160,7 +160,7 @@ namespace ts { } function addHandlers(returnChild: Node) { - if (isPromiseHandler(returnChild)) { + if (isFixablePromiseHandler(returnChild)) { returnStatements.push(child as ReturnStatement); } } @@ -170,8 +170,39 @@ namespace ts { return returnStatements; } - function isPromiseHandler(node: Node): boolean { - return (isCallExpression(node) && isPropertyAccessExpression(node.expression) && - (node.expression.name.text === "then" || node.expression.name.text === "catch")); + // Should be kept up to date with transformExpression in convertToAsyncFunction.ts + function isFixablePromiseHandler(node: Node): boolean { + // ensure outermost call exists and is a promise handler + if (!isPromiseHandler(node) || !node.arguments.every(isFixablePromiseArgument)) { + return false; + } + + // ensure all chained calls are valid + let currentNode = node.expression; + while (isPromiseHandler(currentNode) || isPropertyAccessExpression(currentNode)) { + if (isCallExpression(currentNode) && !currentNode.arguments.every(isFixablePromiseArgument)) { + return false; + } + currentNode = currentNode.expression; + } + return true; + } + + function isPromiseHandler(node: Node): node is CallExpression { + return isCallExpression(node) && (hasPropertyAccessExpressionWithName(node, "then") || hasPropertyAccessExpressionWithName(node, "catch")); + } + + // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts + function isFixablePromiseArgument(arg: Expression): boolean { + switch (arg.kind) { + case SyntaxKind.NullKeyword: + case SyntaxKind.Identifier: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return true; + default: + return false; + } } } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index b8a235bbeb4..19bc029e855 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -224,6 +224,14 @@ namespace ts { return undefined; } + export function hasPropertyAccessExpressionWithName(node: CallExpression, funcName: string): boolean { + if (!isPropertyAccessExpression(node.expression)) { + return false; + } + + return node.expression.name.text === funcName; + } + export function isJumpStatementTarget(node: Node): node is Identifier & { parent: BreakOrContinueStatement } { return node.kind === SyntaxKind.Identifier && isBreakOrContinueStatement(node.parent) && node.parent.label === node; } diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 9fac9e59e92..9f675f1c89a 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1,10 +1,4 @@ namespace ts { - const enum TestExpectation { - Normal, - NoDiagnostic, - NoAction - } - const libFile: TestFSWithWatch.File = { path: "/a/lib/lib.d.ts", content: `/// @@ -261,14 +255,14 @@ interface String { charAt: any; } interface Array {}` }; - function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectedResult: TestExpectation = TestExpectation.Normal) { + function testConvertToAsyncFunction(caption: string, text: string, baselineFolder: string, includeLib?: boolean, expectFailure = false) { const t = extractTest(text); const selectionRange = t.ranges.get("selection")!; if (!selectionRange) { throw new Error(`Test ${caption} does not specify selection range`); } - const extensions = expectedResult === TestExpectation.Normal ? [Extension.Ts, Extension.Js] : [Extension.Ts]; + const extensions = expectFailure ? [Extension.Ts] : [Extension.Ts, Extension.Js]; extensions.forEach(extension => it(`${caption} [${extension}]`, () => runBaseline(extension))); @@ -304,21 +298,21 @@ interface Array {}` const diagnostics = languageService.getSuggestionDiagnostics(f.path); const diagnostic = find(diagnostics, diagnostic => diagnostic.messageText === Diagnostics.This_may_be_converted_to_an_async_function.message && diagnostic.start === context.span.start && diagnostic.length === context.span.length); - if (expectedResult === TestExpectation.NoDiagnostic) { + if (expectFailure) { assert.isUndefined(diagnostic); - return; } - - assert.exists(diagnostic); + else { + assert.exists(diagnostic); + } const actions = codefix.getFixes(context); const action = find(actions, action => action.description === Diagnostics.Convert_to_async_function.message); - if (expectedResult === TestExpectation.NoAction) { - assert.isUndefined(action); + if (expectFailure) { + assert.isNotTrue(action && action.changes.length > 0); return; } - assert.exists(action); + assert.isTrue(action && action.changes.length > 0); const data: string[] = []; data.push(`// ==ORIGINAL==`); @@ -481,7 +475,7 @@ function [#|f|]() { } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NoSuggestion", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestion", ` function [#|f|]():Promise { return fetch('https://typescriptlang.org'); } @@ -495,7 +489,7 @@ function [#|f|]():Promise{ } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NoSuggestionNoPromise", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NoSuggestionNoPromise", ` function [#|f|]():void{ } ` @@ -548,21 +542,21 @@ function [#|f|]():Promise { } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally1", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally1", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).catch(rej => console.log("error", rej)).finally(console.log("finally!")); } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally2", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally2", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").then(res => console.log(res)).finally(console.log("finally!")); } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Finally3", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Finally3", ` function [#|finallyTest|](): Promise { return fetch("https://typescriptlang.org").finally(console.log("finally!")); } @@ -590,14 +584,14 @@ function [#|innerPromise|](): Promise { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn01", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn01", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org").then(resp => console.log(resp)); return blob; } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn02", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn02", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); blob.then(resp => console.log(resp)); @@ -605,7 +599,7 @@ function [#|f|]() { } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn03", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn03", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org") let blob2 = blob.then(resp => console.log(resp)); @@ -618,7 +612,7 @@ function err (rej) { } ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn04", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn04", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)), blob2 = fetch("https://microsoft.com").then(res => res.ok).catch(err); return blob; @@ -629,7 +623,7 @@ function err (rej) { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn05", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn05", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org").then(res => console.log(res)); blob.then(x => x); @@ -638,7 +632,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn06", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn06", ` function [#|f|]() { var blob = fetch("https://typescriptlang.org"); return blob; @@ -646,7 +640,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn07", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn07", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); let blob2 = fetch("https://microsoft.com"); @@ -657,7 +651,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn08", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn08", ` function [#|f|]() { let blob = fetch("https://typescriptlang.org"); if (!blob.ok){ @@ -669,7 +663,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn09", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn09", ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -683,7 +677,7 @@ function [#|f|]() { ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn10", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn10", ` function [#|f|]() { let blob3; let blob = fetch("https://typescriptlang.org"); @@ -697,7 +691,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_VarReturn11", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_VarReturn11", ` function [#|f|]() { let blob; return blob; @@ -707,7 +701,7 @@ function [#|f|]() { - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_Param1", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_Param1", ` function [#|f|]() { return my_print(fetch("https://typescriptlang.org").then(res => console.log(res))); } @@ -764,7 +758,7 @@ function [#|f|](): Promise { ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_SeperateLines", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_SeperateLines", ` function [#|f|](): Promise { var blob = fetch("https://typescriptlang.org") blob.then(resp => { @@ -1027,7 +1021,7 @@ function [#|f|]() { } `); -_testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_CatchFollowedByCall", ` +_testConvertToAsyncFunctionFailed("convertToAsyncFunction_CatchFollowedByCall", ` function [#|f|](){ return fetch("https://typescriptlang.org").then(res).catch(rej).toString(); } @@ -1091,7 +1085,7 @@ function [#|f|]() { ` ); - _testConvertToAsyncFunctionNoDiagnostic("convertToAsyncFunction_NestedFunctionWrongLocation", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_NestedFunctionWrongLocation", ` function [#|f|]() { function fn2(){ function fn3(){ @@ -1140,13 +1134,13 @@ const [#|foo|] = function () { } `); - _testConvertToAsyncFunctionNoAction("convertToAsyncFunction_thenArgumentNotFunction", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunction", ` function [#|f|]() { return Promise.resolve().then(f ? (x => x) : (y => y)); } `); -_testConvertToAsyncFunctionNoAction("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` + _testConvertToAsyncFunctionFailed("convertToAsyncFunction_thenArgumentNotFunctionNotLastInChain", ` function [#|f|]() { return Promise.resolve().then(f ? (x => x) : (y => y)).then(q => q); } @@ -1159,11 +1153,7 @@ function [#|f|]() { testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true); } - function _testConvertToAsyncFunctionNoDiagnostic(caption: string, text: string) { - testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, TestExpectation.NoDiagnostic); - } - - function _testConvertToAsyncFunctionNoAction(caption: string, text: string) { - testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, TestExpectation.NoAction); + function _testConvertToAsyncFunctionFailed(caption: string, text: string) { + testConvertToAsyncFunction(caption, text, "convertToAsyncFunction", /*includeLib*/ true, /*expectFailure*/ true); } } \ No newline at end of file From 16477b65067d7e4b3d71eeb1300ae03d7723fe2d Mon Sep 17 00:00:00 2001 From: christian Date: Sat, 8 Sep 2018 00:06:07 -0400 Subject: [PATCH 067/146] Take into account undefined nodeValue when recording diagnostic --- src/compiler/commandLineParser.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index ecc69fccf86..edee847019a 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1847,8 +1847,12 @@ namespace ts { const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; if (filesSpecs.length === 0 && hasZeroOrNoReferences) { if (sourceFile) { + const fileName = configFileName || "tsconfig.json"; + const diagnosticMessage = Diagnostics.The_files_list_in_config_file_0_is_empty; const nodeValue = firstDefined(getTsConfigPropArray(sourceFile, "files"), property => property.initializer); - const error = createDiagnosticForNodeInSourceFile(sourceFile, nodeValue!, Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"); + const error = nodeValue + ? createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName) + : createCompilerDiagnostic(diagnosticMessage, fileName); errors.push(error); } else { From 745f5be2cbf0bda18310ad14ad68974b42d9b9e4 Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Sat, 8 Sep 2018 13:12:09 -0700 Subject: [PATCH 068/146] Invert gutter instead of setting colors Fixes #26850 --- src/compiler/program.ts | 2 +- .../deeplyNestedAssignabilityIssue.errors.txt | 16 +++--- ...uplicateIdentifierRelatedSpans1.errors.txt | 56 +++++++++---------- ...uplicateIdentifierRelatedSpans2.errors.txt | 16 +++--- ...uplicateIdentifierRelatedSpans3.errors.txt | 48 ++++++++-------- ...uplicateIdentifierRelatedSpans4.errors.txt | 16 +++--- ...uplicateIdentifierRelatedSpans5.errors.txt | 48 ++++++++-------- ...uplicateIdentifierRelatedSpans6.errors.txt | 48 ++++++++-------- ...uplicateIdentifierRelatedSpans7.errors.txt | 16 +++--- ...opPrettyErrorRelatedInformation.errors.txt | 8 +-- ...LineContextDiagnosticWithPretty.errors.txt | 12 ++-- .../prettyContextNotDebugAssertion.errors.txt | 4 +- .../reference/typedefCrossModule5.errors.txt | 32 +++++------ 13 files changed, 161 insertions(+), 161 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c97f1a61d27..c24f570819e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -250,7 +250,7 @@ namespace ts { Blue = "\u001b[94m", Cyan = "\u001b[96m" } - const gutterStyleSequence = "\u001b[30;47m"; + const gutterStyleSequence = "\u001b[7m"; const gutterSeparator = " "; const resetEscapeSequence = "\u001b[0m"; const ellipsis = "..."; diff --git a/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt b/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt index cf243a1e5bd..772d1e4f5a3 100644 --- a/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt +++ b/tests/baselines/reference/deeplyNestedAssignabilityIssue.errors.txt @@ -1,22 +1,22 @@ tests/cases/compiler/deeplyNestedAssignabilityIssue.ts:22:17 - error TS2322: Type '{}' is not assignable to type 'A'. Property 'a' is missing in type '{}'. -22 thing: {} -   ~~~~~ +22 thing: {} +   ~~~~~ tests/cases/compiler/deeplyNestedAssignabilityIssue.ts:9:17 - 9 thing: A; -    ~~~~~ + 9 thing: A; +    ~~~~~ The expected type comes from property 'thing' which is declared here on type '{ thing: A; }' tests/cases/compiler/deeplyNestedAssignabilityIssue.ts:25:17 - error TS2322: Type '{}' is not assignable to type 'A'. Property 'a' is missing in type '{}'. -25 another: {} -   ~~~~~~~ +25 another: {} +   ~~~~~~~ tests/cases/compiler/deeplyNestedAssignabilityIssue.ts:12:17 - 12 another: A; -    ~~~~~~~ + 12 another: A; +    ~~~~~~~ The expected type comes from property 'another' which is declared here on type '{ another: A; }' diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt index 62b4774f4f7..9a963614b61 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans1.errors.txt @@ -1,64 +1,64 @@ tests/cases/compiler/file1.ts:1:7 - error TS2300: Duplicate identifier 'Foo'. -1 class Foo { } -   ~~~ +1 class Foo { } +   ~~~ tests/cases/compiler/file2.ts:1:6 - 1 type Foo = number; -    ~~~ + 1 type Foo = number; +    ~~~ 'Foo' was also declared here. tests/cases/compiler/file3.ts:1:6 - 1 type Foo = 54; -    ~~~ + 1 type Foo = 54; +    ~~~ and here. tests/cases/compiler/file1.ts:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 const Bar = 3; -   ~~~ +2 const Bar = 3; +   ~~~ tests/cases/compiler/file2.ts:2:7 - 2 class Bar {} -    ~~~ + 2 class Bar {} +    ~~~ 'Bar' was also declared here. tests/cases/compiler/file3.ts:2:5 - 2 let Bar = 42 -    ~~~ + 2 let Bar = 42 +    ~~~ and here. tests/cases/compiler/file2.ts:1:6 - error TS2300: Duplicate identifier 'Foo'. -1 type Foo = number; -   ~~~ +1 type Foo = number; +   ~~~ tests/cases/compiler/file1.ts:1:7 - 1 class Foo { } -    ~~~ + 1 class Foo { } +    ~~~ 'Foo' was also declared here. tests/cases/compiler/file2.ts:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 class Bar {} -   ~~~ +2 class Bar {} +   ~~~ tests/cases/compiler/file1.ts:2:7 - 2 const Bar = 3; -    ~~~ + 2 const Bar = 3; +    ~~~ 'Bar' was also declared here. tests/cases/compiler/file3.ts:1:6 - error TS2300: Duplicate identifier 'Foo'. -1 type Foo = 54; -   ~~~ +1 type Foo = 54; +   ~~~ tests/cases/compiler/file1.ts:1:7 - 1 class Foo { } -    ~~~ + 1 class Foo { } +    ~~~ 'Foo' was also declared here. tests/cases/compiler/file3.ts:2:5 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 let Bar = 42 -   ~~~ +2 let Bar = 42 +   ~~~ tests/cases/compiler/file1.ts:2:7 - 2 const Bar = 3; -    ~~~ + 2 const Bar = 3; +    ~~~ 'Bar' was also declared here. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt index 2925b636d2d..c6d6291e66a 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans2.errors.txt @@ -1,20 +1,20 @@ tests/cases/compiler/file1.ts:1:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: A, B, C, D, E, F, G, H, I -1 class A { } -  ~~~~~ +1 class A { } +  ~~~~~ tests/cases/compiler/file2.ts:1:1 - 1 class A { } -   ~~~~~ + 1 class A { } +   ~~~~~ Conflicts are in this file. tests/cases/compiler/file2.ts:1:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: A, B, C, D, E, F, G, H, I -1 class A { } -  ~~~~~ +1 class A { } +  ~~~~~ tests/cases/compiler/file1.ts:1:1 - 1 class A { } -   ~~~~~ + 1 class A { } +   ~~~~~ Conflicts are in this file. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt index a97ce217928..2fb1879933c 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans3.errors.txt @@ -1,56 +1,56 @@ tests/cases/compiler/file1.ts:2:5 - error TS2300: Duplicate identifier 'duplicate1'. -2 duplicate1: () => string; -   ~~~~~~~~~~ +2 duplicate1: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:2:5 - 2 duplicate1(): number; -    ~~~~~~~~~~ + 2 duplicate1(): number; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file1.ts:3:5 - error TS2300: Duplicate identifier 'duplicate2'. -3 duplicate2: () => string; -   ~~~~~~~~~~ +3 duplicate2: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:3:5 - 3 duplicate2(): number; -    ~~~~~~~~~~ + 3 duplicate2(): number; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file1.ts:4:5 - error TS2300: Duplicate identifier 'duplicate3'. -4 duplicate3: () => string; -   ~~~~~~~~~~ +4 duplicate3: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:4:5 - 4 duplicate3(): number; -    ~~~~~~~~~~ + 4 duplicate3(): number; +    ~~~~~~~~~~ 'duplicate3' was also declared here. tests/cases/compiler/file2.ts:2:5 - error TS2300: Duplicate identifier 'duplicate1'. -2 duplicate1(): number; -   ~~~~~~~~~~ +2 duplicate1(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:2:5 - 2 duplicate1: () => string; -    ~~~~~~~~~~ + 2 duplicate1: () => string; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file2.ts:3:5 - error TS2300: Duplicate identifier 'duplicate2'. -3 duplicate2(): number; -   ~~~~~~~~~~ +3 duplicate2(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:3:5 - 3 duplicate2: () => string; -    ~~~~~~~~~~ + 3 duplicate2: () => string; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file2.ts:4:5 - error TS2300: Duplicate identifier 'duplicate3'. -4 duplicate3(): number; -   ~~~~~~~~~~ +4 duplicate3(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:4:5 - 4 duplicate3: () => string; -    ~~~~~~~~~~ + 4 duplicate3: () => string; +    ~~~~~~~~~~ 'duplicate3' was also declared here. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt index da50e3ad4a3..9512e55733e 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans4.errors.txt @@ -1,20 +1,20 @@ tests/cases/compiler/file1.ts:1:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: duplicate1, duplicate2, duplicate3, duplicate4, duplicate5, duplicate6, duplicate7, duplicate8 -1 interface TopLevel { -  ~~~~~~~~~ +1 interface TopLevel { +  ~~~~~~~~~ tests/cases/compiler/file2.ts:1:1 - 1 interface TopLevel { -   ~~~~~~~~~ + 1 interface TopLevel { +   ~~~~~~~~~ Conflicts are in this file. tests/cases/compiler/file2.ts:1:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: duplicate1, duplicate2, duplicate3, duplicate4, duplicate5, duplicate6, duplicate7, duplicate8 -1 interface TopLevel { -  ~~~~~~~~~ +1 interface TopLevel { +  ~~~~~~~~~ tests/cases/compiler/file1.ts:1:1 - 1 interface TopLevel { -   ~~~~~~~~~ + 1 interface TopLevel { +   ~~~~~~~~~ Conflicts are in this file. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt index 2cbd4fa9629..497a0642296 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans5.errors.txt @@ -1,56 +1,56 @@ tests/cases/compiler/file1.ts:3:9 - error TS2300: Duplicate identifier 'duplicate1'. -3 duplicate1: () => string; -   ~~~~~~~~~~ +3 duplicate1: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:4:9 - 4 duplicate1(): number; -    ~~~~~~~~~~ + 4 duplicate1(): number; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file1.ts:4:9 - error TS2300: Duplicate identifier 'duplicate2'. -4 duplicate2: () => string; -   ~~~~~~~~~~ +4 duplicate2: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:5:9 - 5 duplicate2(): number; -    ~~~~~~~~~~ + 5 duplicate2(): number; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file1.ts:5:9 - error TS2300: Duplicate identifier 'duplicate3'. -5 duplicate3: () => string; -   ~~~~~~~~~~ +5 duplicate3: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:6:9 - 6 duplicate3(): number; -    ~~~~~~~~~~ + 6 duplicate3(): number; +    ~~~~~~~~~~ 'duplicate3' was also declared here. tests/cases/compiler/file2.ts:4:9 - error TS2300: Duplicate identifier 'duplicate1'. -4 duplicate1(): number; -   ~~~~~~~~~~ +4 duplicate1(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:3:9 - 3 duplicate1: () => string; -    ~~~~~~~~~~ + 3 duplicate1: () => string; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file2.ts:5:9 - error TS2300: Duplicate identifier 'duplicate2'. -5 duplicate2(): number; -   ~~~~~~~~~~ +5 duplicate2(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:4:9 - 4 duplicate2: () => string; -    ~~~~~~~~~~ + 4 duplicate2: () => string; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file2.ts:6:9 - error TS2300: Duplicate identifier 'duplicate3'. -6 duplicate3(): number; -   ~~~~~~~~~~ +6 duplicate3(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:5:9 - 5 duplicate3: () => string; -    ~~~~~~~~~~ + 5 duplicate3: () => string; +    ~~~~~~~~~~ 'duplicate3' was also declared here. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt index afe6ebe9f42..db980204718 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans6.errors.txt @@ -1,56 +1,56 @@ tests/cases/compiler/file1.ts:3:9 - error TS2300: Duplicate identifier 'duplicate1'. -3 duplicate1: () => string; -   ~~~~~~~~~~ +3 duplicate1: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:5:9 - 5 duplicate1(): number; -    ~~~~~~~~~~ + 5 duplicate1(): number; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file1.ts:4:9 - error TS2300: Duplicate identifier 'duplicate2'. -4 duplicate2: () => string; -   ~~~~~~~~~~ +4 duplicate2: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:6:9 - 6 duplicate2(): number; -    ~~~~~~~~~~ + 6 duplicate2(): number; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file1.ts:5:9 - error TS2300: Duplicate identifier 'duplicate3'. -5 duplicate3: () => string; -   ~~~~~~~~~~ +5 duplicate3: () => string; +   ~~~~~~~~~~ tests/cases/compiler/file2.ts:7:9 - 7 duplicate3(): number; -    ~~~~~~~~~~ + 7 duplicate3(): number; +    ~~~~~~~~~~ 'duplicate3' was also declared here. tests/cases/compiler/file2.ts:5:9 - error TS2300: Duplicate identifier 'duplicate1'. -5 duplicate1(): number; -   ~~~~~~~~~~ +5 duplicate1(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:3:9 - 3 duplicate1: () => string; -    ~~~~~~~~~~ + 3 duplicate1: () => string; +    ~~~~~~~~~~ 'duplicate1' was also declared here. tests/cases/compiler/file2.ts:6:9 - error TS2300: Duplicate identifier 'duplicate2'. -6 duplicate2(): number; -   ~~~~~~~~~~ +6 duplicate2(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:4:9 - 4 duplicate2: () => string; -    ~~~~~~~~~~ + 4 duplicate2: () => string; +    ~~~~~~~~~~ 'duplicate2' was also declared here. tests/cases/compiler/file2.ts:7:9 - error TS2300: Duplicate identifier 'duplicate3'. -7 duplicate3(): number; -   ~~~~~~~~~~ +7 duplicate3(): number; +   ~~~~~~~~~~ tests/cases/compiler/file1.ts:5:9 - 5 duplicate3: () => string; -    ~~~~~~~~~~ + 5 duplicate3: () => string; +    ~~~~~~~~~~ 'duplicate3' was also declared here. diff --git a/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt b/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt index 76bb3d9c750..7b568736ff3 100644 --- a/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt +++ b/tests/baselines/reference/duplicateIdentifierRelatedSpans7.errors.txt @@ -1,20 +1,20 @@ tests/cases/compiler/file1.ts:1:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: duplicate1, duplicate2, duplicate3, duplicate4, duplicate5, duplicate6, duplicate7, duplicate8, duplicate9 -1 declare module "someMod" { -  ~~~~~~~ +1 declare module "someMod" { +  ~~~~~~~ tests/cases/compiler/file2.ts:3:1 - 3 declare module "someMod" { -   ~~~~~~~ + 3 declare module "someMod" { +   ~~~~~~~ Conflicts are in this file. tests/cases/compiler/file2.ts:3:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: duplicate1, duplicate2, duplicate3, duplicate4, duplicate5, duplicate6, duplicate7, duplicate8, duplicate9 -3 declare module "someMod" { -  ~~~~~~~ +3 declare module "someMod" { +  ~~~~~~~ tests/cases/compiler/file1.ts:1:1 - 1 declare module "someMod" { -   ~~~~~~~ + 1 declare module "someMod" { +   ~~~~~~~ Conflicts are in this file. diff --git a/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt b/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt index 1d1c983162f..14c054c466c 100644 --- a/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt +++ b/tests/baselines/reference/esModuleInteropPrettyErrorRelatedInformation.errors.txt @@ -1,12 +1,12 @@ tests/cases/compiler/index.ts:3:8 - error TS2345: Argument of type '{ default: () => void; }' is not assignable to parameter of type '() => void'. Type '{ default: () => void; }' provides no match for the signature '(): void'. -3 invoke(foo); -   ~~~ +3 invoke(foo); +   ~~~ tests/cases/compiler/index.ts:1:1 - 1 import * as foo from "./foo"; -   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + 1 import * as foo from "./foo"; +   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead. diff --git a/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt b/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt index c6b8095d15b..525f30415d1 100644 --- a/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt +++ b/tests/baselines/reference/multiLineContextDiagnosticWithPretty.errors.txt @@ -1,12 +1,12 @@ tests/cases/compiler/multiLineContextDiagnosticWithPretty.ts:2:5 - error TS2322: Type '{ a: { b: string; }; }' is not assignable to type '{ c: string; }'. Object literal may only specify known properties, and 'a' does not exist in type '{ c: string; }'. -2 a: { -   ~~~~ -3 b: '', -  ~~~~~~~~~~~~~~ -4 } -  ~~~~~ +2 a: { +   ~~~~ +3 b: '', +  ~~~~~~~~~~~~~~ +4 } +  ~~~~~ ==== tests/cases/compiler/multiLineContextDiagnosticWithPretty.ts (1 errors) ==== diff --git a/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt b/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt index 57b4f5d62f7..d983f0d973e 100644 --- a/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt +++ b/tests/baselines/reference/prettyContextNotDebugAssertion.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/index.ts:2:1 - error TS1005: '}' expected. -2 -   +2 +   ==== tests/cases/compiler/index.ts (1 errors) ==== diff --git a/tests/baselines/reference/typedefCrossModule5.errors.txt b/tests/baselines/reference/typedefCrossModule5.errors.txt index b75652a31d5..2784f0e1896 100644 --- a/tests/baselines/reference/typedefCrossModule5.errors.txt +++ b/tests/baselines/reference/typedefCrossModule5.errors.txt @@ -1,38 +1,38 @@ tests/cases/conformance/jsdoc/mod1.js:1:23 - error TS2300: Duplicate identifier 'Foo'. -1 /** @typedef {number} Foo */ -   ~~~ +1 /** @typedef {number} Foo */ +   ~~~ tests/cases/conformance/jsdoc/mod2.js:1:7 - 1 class Foo { } // should error -    ~~~ + 1 class Foo { } // should error +    ~~~ 'Foo' was also declared here. tests/cases/conformance/jsdoc/mod1.js:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 class Bar {} -   ~~~ +2 class Bar {} +   ~~~ tests/cases/conformance/jsdoc/mod2.js:2:7 - 2 const Bar = 3; -    ~~~ + 2 const Bar = 3; +    ~~~ 'Bar' was also declared here. tests/cases/conformance/jsdoc/mod2.js:1:7 - error TS2300: Duplicate identifier 'Foo'. -1 class Foo { } // should error -   ~~~ +1 class Foo { } // should error +   ~~~ tests/cases/conformance/jsdoc/mod1.js:1:23 - 1 /** @typedef {number} Foo */ -    ~~~ + 1 /** @typedef {number} Foo */ +    ~~~ 'Foo' was also declared here. tests/cases/conformance/jsdoc/mod2.js:2:7 - error TS2451: Cannot redeclare block-scoped variable 'Bar'. -2 const Bar = 3; -   ~~~ +2 const Bar = 3; +   ~~~ tests/cases/conformance/jsdoc/mod1.js:2:7 - 2 class Bar {} -    ~~~ + 2 class Bar {} +    ~~~ 'Bar' was also declared here. From 95ba73e16b5b417a7a9c5d664b4c092677231937 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Mon, 10 Sep 2018 10:37:44 -0700 Subject: [PATCH 069/146] Don't offer module completions in non-module JS files --- src/services/completions.ts | 4 +-- .../fourslash/completionsImport_importType.ts | 13 +++++--- ...oImportCompletionsInOtherJavaScriptFile.ts | 31 +++++++++++++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts diff --git a/src/services/completions.ts b/src/services/completions.ts index 16e48dc56b6..61e424c43ec 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1268,10 +1268,10 @@ namespace ts.Completions { if (sourceFile.externalModuleIndicator) return true; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (programContainsEs6Modules(program)) return true; // For JS, stay on the safe side. if (isUncheckedFile) return false; + // If some file is using ES6 modules, assume that it's OK to add more. + if (programContainsEs6Modules(program)) return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. return compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); } diff --git a/tests/cases/fourslash/completionsImport_importType.ts b/tests/cases/fourslash/completionsImport_importType.ts index b1b69a9a8d0..3c371980b90 100644 --- a/tests/cases/fourslash/completionsImport_importType.ts +++ b/tests/cases/fourslash/completionsImport_importType.ts @@ -3,13 +3,14 @@ // @allowJs: true // @Filename: /a.js -////export const x = 0; -////export class C {} -/////** @typedef {number} T */ +//// export const x = 0; +//// export class C {} +//// /** @typedef {number} T */ // @Filename: /b.js -/////** @type {/*0*/} */ -/////** @type {/*1*/} */ +//// export const m = 0; +//// /** @type {/*0*/} */ +//// /** @type {/*1*/} */ verify.completions({ marker: ["0", "1"], @@ -43,6 +44,7 @@ verify.applyCodeActionFromCompletion("0", { newFileContent: `import { C } from "./a"; +export const m = 0; /** @type {} */ /** @type {} */`, }); @@ -55,6 +57,7 @@ verify.applyCodeActionFromCompletion("1", { newFileContent: `import { C } from "./a"; +export const m = 0; /** @type {} */ /** @type {import("./a").} */`, }); diff --git a/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts new file mode 100644 index 00000000000..3493c4c2cff --- /dev/null +++ b/tests/cases/fourslash/noImportCompletionsInOtherJavaScriptFile.ts @@ -0,0 +1,31 @@ +/// + +// @allowJs: true +// @module: esnext + +// @Filename: /node_modules/foo/index.d.ts +//// export const fail: number; + +// @Filename: /a.js +//// export const x = 0; +//// export class C {} +//// + +// @Filename: /b.js +//// /**/ + +goTo.file("/b.js"); +goTo.marker(); +verify.not.completionListContains("fail", undefined, undefined, undefined, undefined, undefined, { includeCompletionsForModuleExports: true }); +edit.insert("export const k = 10;\r\nf"); +verify.completionListContains( + { name: "fail", source: "/node_modules/foo/index" }, + "const fail: number", + "", + "const", + undefined, + true, + { + includeCompletionsForModuleExports: true, + sourceDisplay: "./node_modules/foo/index" + }); From 24a5bdd1b165f0cc5211cd786d1782eadf6117d2 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 10 Sep 2018 11:25:03 -0700 Subject: [PATCH 070/146] Add 'fileToRename' property to RenameInfo (#24702) * Add 'fileToRename' property to RenameInfo * Update tests * Support directory rename --- src/harness/client.ts | 1 + src/harness/fourslash.ts | 21 +++++++++------- src/server/protocol.ts | 6 +++++ src/server/session.ts | 2 +- src/services/rename.ts | 24 +++++++++++++++++-- src/services/types.ts | 5 ++++ .../reference/api/tsserverlibrary.d.ts | 10 ++++++++ tests/baselines/reference/api/typescript.d.ts | 5 ++++ .../findAllRefs_importType_exportEquals.ts | 2 +- tests/cases/fourslash/fourslash.ts | 4 ++-- tests/cases/fourslash/renameImport.ts | 14 +++++++++-- 11 files changed, 77 insertions(+), 17 deletions(-) diff --git a/src/harness/client.ts b/src/harness/client.ts index ebe97aea070..d873cd9b4fe 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -397,6 +397,7 @@ namespace ts.server { return this.lastRenameEntry = { canRename: body.info.canRename, + fileToRename: body.info.fileToRename, displayName: body.info.displayName, fullDisplayName: body.info.fullDisplayName, kind: body.info.kind, diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 214e1f295ab..1abb7d4c1cc 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -420,12 +420,12 @@ namespace FourSlash { } } - public goToEachRange(action: () => void) { + public goToEachRange(action: (range: Range) => void) { const ranges = this.getRanges(); assert(ranges.length); for (const range of ranges) { this.selectRange(range); - action(); + action(range); } } @@ -1525,7 +1525,7 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { + public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined): void { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { this.raiseError("Rename did not succeed"); @@ -1535,12 +1535,15 @@ Actual: ${stringify(fullActual)}`); this.validate("fullDisplayName", fullDisplayName, renameInfo.fullDisplayName); this.validate("kind", kind, renameInfo.kind); this.validate("kindModifiers", kindModifiers, renameInfo.kindModifiers); + this.validate("fileToRename", fileToRename, renameInfo.fileToRename); - if (this.getRanges().length !== 1) { - this.raiseError("Expected a single range to be selected in the test file."); + if (!expectedRange) { + if (this.getRanges().length !== 1) { + this.raiseError("Expected a single range to be selected in the test file."); + } + expectedRange = this.getRanges()[0]; } - const expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.pos || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.pos + "," + expectedRange.end + "). Got [" + @@ -3977,7 +3980,7 @@ namespace FourSlashInterface { this.state.goToRangeStart(range); } - public eachRange(action: () => void) { + public eachRange(action: (range: FourSlash.Range) => void) { this.state.goToEachRange(action); } @@ -4456,8 +4459,8 @@ namespace FourSlashInterface { this.state.verifySemanticClassifications(classifications); } - public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers); + public renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, expectedRange?: FourSlash.Range) { + this.state.verifyRenameInfoSucceeded(displayName, fullDisplayName, kind, kindModifiers, fileToRename, expectedRange); } public renameInfoFailed(message?: string) { diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 5c6d9bed337..2804b27deaf 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -1093,6 +1093,12 @@ namespace ts.server.protocol { */ canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; + /** * Error message if item can not be renamed. */ diff --git a/src/server/session.ts b/src/server/session.ts index 5d364abc757..e6c4c33a53d 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1096,7 +1096,7 @@ namespace ts.server { return projectInfo; } - private getRenameInfo(args: protocol.FileLocationRequestArgs) { + private getRenameInfo(args: protocol.FileLocationRequestArgs): RenameInfo { const { file, project } = this.getFileAndProject(args); const position = this.getPositionInFile(args, file); return project.getLanguageService().getRenameInfo(file, position); diff --git a/src/services/rename.ts b/src/services/rename.ts index 43f76ff4428..649ed33786f 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -25,8 +25,9 @@ namespace ts.Rename { return undefined; } - // Can't rename a module name. - if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) return undefined; + if (isStringLiteralLike(node) && tryGetImportFromModuleSpecifier(node)) { + return getRenameInfoForModule(node, sourceFile, symbol); + } const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node); const specifierName = (isImportOrExportSpecifierName(node) || isStringOrNumericLiteralLike(node) && node.parent.kind === SyntaxKind.ComputedPropertyName) @@ -37,9 +38,28 @@ namespace ts.Rename { return getRenameInfoSuccess(displayName, fullDisplayName, kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } + function getRenameInfoForModule(node: StringLiteralLike, sourceFile: SourceFile, moduleSymbol: Symbol): RenameInfo | undefined { + const moduleSourceFile = find(moduleSymbol.declarations, isSourceFile); + if (!moduleSourceFile) return undefined; + const withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : tryRemoveSuffix(removeFileExtension(moduleSourceFile.fileName), "/index"); + const name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; + const kind = withoutIndex === undefined ? ScriptElementKind.moduleElement : ScriptElementKind.directory; + return { + canRename: true, + fileToRename: name, + kind, + displayName: name, + localizedErrorMessage: undefined, + fullDisplayName: name, + kindModifiers: ScriptElementKindModifier.none, + triggerSpan: createTriggerSpanForNode(node, sourceFile), + }; + } + function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { return { canRename: true, + fileToRename: undefined, kind, displayName, localizedErrorMessage: undefined, diff --git a/src/services/types.ts b/src/services/types.ts index 9bf0edf3150..08a09d7f912 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -784,6 +784,11 @@ namespace ts { export interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 2fa23f14a7b..672b93e55da 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -5101,6 +5101,11 @@ declare namespace ts { } interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; @@ -6422,6 +6427,11 @@ declare namespace ts.server.protocol { * True if item can be renamed. */ canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; /** * Error message if item can not be renamed. */ diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 8290cb96236..5d093382f54 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -5101,6 +5101,11 @@ declare namespace ts { } interface RenameInfo { canRename: boolean; + /** + * File or directory to rename. + * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. + */ + fileToRename?: string; localizedErrorMessage?: string; displayName: string; fullDisplayName: string; diff --git a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts index c944f2468c5..04b3c212dfc 100644 --- a/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts +++ b/tests/cases/fourslash/findAllRefs_importType_exportEquals.ts @@ -27,5 +27,5 @@ verify.renameLocations(r1, [r1, r2]); verify.renameLocations(r2, [r0, r1, r2]); for (const range of [r3, r4]) { goTo.rangeStart(range); - verify.renameInfoFailed(); + verify.renameInfoSucceeded(/*displayName*/ "/a.ts", /*fullDisplayName*/ "/a.ts", /*kind*/ "module", /*kindModifiers*/ "", /*fileToRename*/ "/a.ts", range); } diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 2d73be1a917..2fb29e245da 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -129,7 +129,7 @@ declare namespace FourSlashInterface { eachMarker(markers: ReadonlyArray, action: (marker: Marker, index: number) => void): void; eachMarker(action: (marker: Marker, index: number) => void): void; rangeStart(range: Range): void; - eachRange(action: () => void): void; + eachRange(action: (range: Range) => void): void; bof(): void; eof(): void; implementation(): void; @@ -315,7 +315,7 @@ declare namespace FourSlashInterface { text: string; textSpan?: TextSpan; }[]): void; - renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string): void; + renameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string, fileToRename?: string, range?: Range): void; renameInfoFailed(message?: string): void; renameLocations(startRanges: ArrayOrSingle, options: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges: Range[] }): void; diff --git a/tests/cases/fourslash/renameImport.ts b/tests/cases/fourslash/renameImport.ts index 84d3ca3d335..f3221f3584e 100644 --- a/tests/cases/fourslash/renameImport.ts +++ b/tests/cases/fourslash/renameImport.ts @@ -5,12 +5,22 @@ // @Filename: /a.ts ////export const x = 0; +// @Filename: /dir/index.ts +////export const x = 0; + // @Filename: /b.ts ////import * as a from "[|./a|]"; -////import a2 = require("[|./a"|]); +////import a2 = require("[|./a|]"); +////import * as dir from "[|{| "target": "dir" |}./dir|]"; +////import * as dir2 from "[|{| "target": "dir/index" |}./dir/index|]"; // @Filename: /c.js ////const a = require("[|./a|]"); verify.noErrors(); -goTo.eachRange(() => { verify.renameInfoFailed(); }); +goTo.eachRange(range => { + const target = range.marker && range.marker.data && range.marker.data.target; + const name = target === "dir" ? "/dir" : target === "dir/index" ? "/dir/index.ts" : "/a.ts"; + const kind = target === "dir" ? "directory" : "module"; + verify.renameInfoSucceeded(/*displayName*/ name, /*fullDisplayName*/ name, /*kind*/ kind, /*kindModifiers*/ "", /*fileToRename*/ name, range); +}); From 59060a1b9064c5ece4e2219ac6404ac45f5c1316 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 6 Sep 2018 16:03:34 -0700 Subject: [PATCH 071/146] Remove unnecessary projectReferences from ExpandResult and referenceSpecs from ConfigFileSpecs --- src/compiler/commandLineParser.ts | 16 ++++------------ src/compiler/types.ts | 2 -- .../baselines/reference/api/tsserverlibrary.d.ts | 1 - tests/baselines/reference/api/typescript.d.ts | 1 - 4 files changed, 4 insertions(+), 16 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index e4c4edcb4db..e7269acfa5b 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1825,7 +1825,8 @@ namespace ts { const options = extend(existingOptions, parsedConfig.options || {}); options.configFilePath = configFileName && normalizeSlashes(configFileName); setConfigFileInOptions(options, sourceFile); - const { fileNames, wildcardDirectories, spec, projectReferences } = getFileNames(); + let projectReferences: ProjectReference[] | undefined; + const { fileNames, wildcardDirectories, spec } = getFileNames(); return { options, fileNames, @@ -1891,13 +1892,12 @@ namespace ts { if (hasProperty(raw, "references") && !isNullOrUndefined(raw.references)) { if (isArray(raw.references)) { - const references: ProjectReference[] = []; for (const ref of raw.references) { if (typeof ref.path !== "string") { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string"); } else { - references.push({ + (projectReferences || (projectReferences = [])).push({ path: getNormalizedAbsolutePath(ref.path, basePath), originalPath: ref.path, prepend: ref.prepend, @@ -1905,7 +1905,6 @@ namespace ts { }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -2398,7 +2397,7 @@ namespace ts { // new entries in these paths. const wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames); - const spec: ConfigFileSpecs = { filesSpecs, referencesSpecs: undefined, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; + const spec: ConfigFileSpecs = { filesSpecs, includeSpecs, excludeSpecs, validatedIncludeSpecs, validatedExcludeSpecs, wildcardDirectories }; return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions); } @@ -2469,16 +2468,9 @@ namespace ts { const literalFiles = arrayFrom(literalFileMap.values()); const wildcardFiles = arrayFrom(wildcardFileMap.values()); - const projectReferences = spec.referencesSpecs && spec.referencesSpecs.map((r): ProjectReference => { - return { - ...r, - path: getNormalizedAbsolutePath(r.path, basePath) - }; - }); return { fileNames: literalFiles.concat(wildcardFiles), - projectReferences, wildcardDirectories, spec }; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 279fef73d5e..27622b9ec4f 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4516,7 +4516,6 @@ namespace ts { /* @internal */ export interface ConfigFileSpecs { filesSpecs: ReadonlyArray | undefined; - referencesSpecs: ReadonlyArray | undefined; /** * Present to report errors (user specified specs), validatedIncludeSpecs are used for file name matching */ @@ -4532,7 +4531,6 @@ namespace ts { export interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; /* @internal */ spec: ConfigFileSpecs; } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 672b93e55da..a2fbf9ac944 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2584,7 +2584,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 5d093382f54..6ab352033f3 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2584,7 +2584,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { From 50bcfb63280155dfd5f9ca51e366b7edf7c6b9ff Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 7 Sep 2018 12:59:38 -0700 Subject: [PATCH 072/146] Try the ParsedCommandLine from cache instead of re-reading contents of tsconfig file --- src/compiler/tsbuild.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 4ddda98a41f..b5a95039a02 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -356,10 +356,19 @@ namespace ts { } function createConfigFileCache(host: CompilerHost) { - const cache = createFileMap(); + const cache = createFileMap(); const configParseHost = parseConfigHostFromCompilerHost(host); + function isParsedCommandLine(value: ParsedCommandLine | "error"): value is ParsedCommandLine { + return !(value as "error").length; + } + function parseConfigFile(configFilePath: ResolvedConfigFileName) { + const value = cache.getValueOrUndefined(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + const sourceFile = host.getSourceFile(configFilePath, ScriptTarget.JSON) as JsonSourceFile; if (sourceFile === undefined) { return undefined; From 521edc1c80cc2d1bcca4024e20625b69f7fb15d2 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 7 Sep 2018 13:36:45 -0700 Subject: [PATCH 073/146] Refactoring to handle case sensitivity of the host when caching --- src/compiler/tsbuild.ts | 126 +++++++++++++++++++--------------------- 1 file changed, 60 insertions(+), 66 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index b5a95039a02..e72e9d1903e 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -34,8 +34,8 @@ namespace ts { /** * Map from config file name to up-to-date status */ - projectStatus: FileMap; - diagnostics?: FileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time + projectStatus: ConfigFileMap; + diagnostics?: ConfigFileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time invalidateProject(project: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined): void; getNextInvalidatedProject(): ResolvedConfigFileName | undefined; @@ -189,62 +189,56 @@ namespace ts { } } - interface FileMap { - setValue(fileName: string, value: T): void; - getValue(fileName: string): T | never; - getValueOrUndefined(fileName: string): T | undefined; - hasKey(fileName: string): boolean; - removeKey(fileName: string): void; - getKeys(): string[]; + interface FileMap { + setValue(fileName: U, value: T): void; + getValue(fileName: U): T | undefined; + hasKey(fileName: U): boolean; + removeKey(fileName: U): void; + forEach(action: (value: T, key: V) => void): void; getSize(): number; } + type ResolvedConfigFilePath = ResolvedConfigFileName & Path; + type ConfigFileMap = FileMap; + type ToResolvedConfigFilePath = (fileName: ResolvedConfigFileName) => ResolvedConfigFilePath; + type ToPath = (fileName: string) => Path; + /** * A FileMap maintains a normalized-key to value relationship */ - function createFileMap(): FileMap { + function createFileMap(toPath: ToResolvedConfigFilePath): ConfigFileMap; + function createFileMap(toPath: ToPath): FileMap; + function createFileMap(toPath: (fileName: U) => V): FileMap { // tslint:disable-next-line:no-null-keyword const lookup = createMap(); return { setValue, getValue, - getValueOrUndefined, removeKey, - getKeys, + forEach, hasKey, getSize }; - function getKeys(): string[] { - return Object.keys(lookup); + function forEach(action: (value: T, key: V) => void) { + lookup.forEach(action); } - function hasKey(fileName: string) { - return lookup.has(normalizePath(fileName)); + function hasKey(fileName: U) { + return lookup.has(toPath(fileName)); } - function removeKey(fileName: string) { - lookup.delete(normalizePath(fileName)); + function removeKey(fileName: U) { + lookup.delete(toPath(fileName)); } - function setValue(fileName: string, value: T) { - lookup.set(normalizePath(fileName), value); + function setValue(fileName: U, value: T) { + lookup.set(toPath(fileName), value); } - function getValue(fileName: string): T | never { - const f = normalizePath(fileName); - if (lookup.has(f)) { - return lookup.get(f)!; - } - else { - throw new Error(`No value corresponding to ${fileName} exists in this map`); - } - } - - function getValueOrUndefined(fileName: string): T | undefined { - const f = normalizePath(fileName); - return lookup.get(f); + function getValue(fileName: U): T | undefined { + return lookup.get(toPath(fileName)); } function getSize() { @@ -252,10 +246,9 @@ namespace ts { } } - function createDependencyMapper() { - const childToParents = createFileMap(); - const parentToChildren = createFileMap(); - const allKeys = createFileMap(); + function createDependencyMapper(toPath: ToResolvedConfigFilePath) { + const childToParents = createFileMap(toPath); + const parentToChildren = createFileMap(toPath); function addReference(childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName): void { addEntry(childToParents, childConfigFileName, parentConfigFileName); @@ -263,36 +256,29 @@ namespace ts { } function getReferencesTo(parentConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return parentToChildren.getValueOrUndefined(parentConfigFileName) || []; + return parentToChildren.getValue(parentConfigFileName) || []; } function getReferencesOf(childConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return childToParents.getValueOrUndefined(childConfigFileName) || []; - } - - function getKeys(): ReadonlyArray { - return allKeys.getKeys() as ResolvedConfigFileName[]; + return childToParents.getValue(childConfigFileName) || []; } function addEntry(mapToAddTo: typeof childToParents | typeof parentToChildren, key: ResolvedConfigFileName, element: ResolvedConfigFileName) { key = normalizePath(key) as ResolvedConfigFileName; element = normalizePath(element) as ResolvedConfigFileName; - let arr = mapToAddTo.getValueOrUndefined(key); + let arr = mapToAddTo.getValue(key); if (arr === undefined) { mapToAddTo.setValue(key, arr = []); } if (arr.indexOf(element) < 0) { arr.push(element); } - allKeys.setValue(key, true); - allKeys.setValue(element, true); } return { addReference, getReferencesTo, getReferencesOf, - getKeys }; } @@ -355,8 +341,8 @@ namespace ts { return opts.rootDir || getDirectoryPath(configFileName); } - function createConfigFileCache(host: CompilerHost) { - const cache = createFileMap(); + function createConfigFileCache(host: CompilerHost, toPath: ToResolvedConfigFilePath) { + const cache = createFileMap(toPath); const configParseHost = parseConfigHostFromCompilerHost(host); function isParsedCommandLine(value: ParsedCommandLine | "error"): value is ParsedCommandLine { @@ -364,7 +350,7 @@ namespace ts { } function parseConfigFile(configFilePath: ResolvedConfigFileName) { - const value = cache.getValueOrUndefined(configFilePath); + const value = cache.getValue(configFilePath); if (value) { return isParsedCommandLine(value) ? value : undefined; } @@ -398,18 +384,18 @@ namespace ts { return fileExtensionIs(fileName, Extension.Dts); } - export function createBuildContext(options: BuildOptions): BuildContext { + export function createBuildContext(options: BuildOptions, toPath: ToResolvedConfigFilePath): BuildContext { const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; let nextIndex = 0; - const projectPendingBuild = createFileMap(); + const projectPendingBuild = createFileMap(toPath); const missingRoots = createMap(); - const diagnostics = options.watch ? createFileMap() : undefined; + const diagnostics = options.watch ? createFileMap(toPath) : undefined; return { options, - projectStatus: createFileMap(), + projectStatus: createFileMap(toPath), diagnostics, - unchangedOutputs: createFileMap(), + unchangedOutputs: createFileMap(toPath as ToPath), invalidateProject, getNextInvalidatedProject, hasPendingInvalidatedProjects, @@ -513,8 +499,10 @@ namespace ts { */ export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions) { const hostWithWatch = host as SolutionBuilderWithWatchHost; - const configFileCache = createConfigFileCache(host); - let context = createBuildContext(defaultOptions); + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const configFileCache = createConfigFileCache(host, toPath); + let context = createBuildContext(defaultOptions, toPath); let timerToBuildInvalidatedProject: any; let reportFileChangeDetected = false; @@ -535,6 +523,12 @@ namespace ts { startWatching }; + function toPath(fileName: ResolvedConfigFileName): ResolvedConfigFilePath; + function toPath(fileName: string): Path; + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function reportStatus(message: DiagnosticMessage, ...args: string[]) { host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } @@ -600,7 +594,7 @@ namespace ts { } function resetBuildContext(opts = defaultOptions) { - context = createBuildContext(opts); + context = createBuildContext(opts, toPath); } function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus { @@ -623,13 +617,13 @@ namespace ts { return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - const prior = context.projectStatus.getValueOrUndefined(project.options.configFilePath!); + const prior = context.projectStatus.getValue(project.options.configFilePath as ResolvedConfigFilePath); if (prior !== undefined) { return prior; } const actual = getUpToDateStatusWorker(project); - context.projectStatus.setValue(project.options.configFilePath!, actual); + context.projectStatus.setValue(project.options.configFilePath as ResolvedConfigFilePath, actual); return actual; } @@ -700,7 +694,7 @@ namespace ts { // had its file touched but not had its contents changed - this allows us // to skip a downstream typecheck if (isDeclarationFile(output)) { - const unchangedTime = context.unchangedOutputs.getValueOrUndefined(output); + const unchangedTime = context.unchangedOutputs.getValue(output); if (unchangedTime !== undefined) { newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } @@ -845,9 +839,9 @@ namespace ts { function reportErrorSummary() { if (context.options.watch) { - let errorCount = 0; - context.diagnostics!.getKeys().forEach(resolved => errorCount += context.diagnostics!.getValue(resolved)); - reportWatchStatus(errorCount === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, errorCount); + let totalErrors = 0; + context.diagnostics!.forEach(singleProjectErrors => totalErrors += singleProjectErrors); + reportWatchStatus(totalErrors === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors); } } @@ -881,7 +875,7 @@ namespace ts { const permanentMarks: { [path: string]: true } = {}; const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; - const graph = createDependencyMapper(); + const graph = createDependencyMapper(toPath); let hadError = false; @@ -1061,7 +1055,7 @@ namespace ts { host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath!, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); + context.projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { From 82041eb300260d06da720a47d6f660ae2ace1db2 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 7 Sep 2018 15:22:10 -0700 Subject: [PATCH 074/146] Add partial reload support also watch wild cards correctly. Partially fixes #26524 --- src/compiler/tsbuild.ts | 250 +++++++++++-------- src/testRunner/unittests/tsbuildWatchMode.ts | 8 +- 2 files changed, 158 insertions(+), 100 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index e72e9d1903e..55af0080983 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -37,8 +37,8 @@ namespace ts { projectStatus: ConfigFileMap; diagnostics?: ConfigFileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time - invalidateProject(project: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined): void; - getNextInvalidatedProject(): ResolvedConfigFileName | undefined; + invalidateProject(project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel | undefined, dependencyGraph: DependencyGraph | undefined): void; + getNextInvalidatedProject(): { project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel } | undefined; hasPendingInvalidatedProjects(): boolean; missingRoots: Map; } @@ -341,40 +341,6 @@ namespace ts { return opts.rootDir || getDirectoryPath(configFileName); } - function createConfigFileCache(host: CompilerHost, toPath: ToResolvedConfigFilePath) { - const cache = createFileMap(toPath); - const configParseHost = parseConfigHostFromCompilerHost(host); - - function isParsedCommandLine(value: ParsedCommandLine | "error"): value is ParsedCommandLine { - return !(value as "error").length; - } - - function parseConfigFile(configFilePath: ResolvedConfigFileName) { - const value = cache.getValue(configFilePath); - if (value) { - return isParsedCommandLine(value) ? value : undefined; - } - - const sourceFile = host.getSourceFile(configFilePath, ScriptTarget.JSON) as JsonSourceFile; - if (sourceFile === undefined) { - return undefined; - } - - const parsed = parseJsonSourceFileConfigFileContent(sourceFile, configParseHost, getDirectoryPath(configFilePath)); - parsed.options.configFilePath = configFilePath; - cache.setValue(configFilePath, parsed); - return parsed; - } - - function removeKey(configFilePath: ResolvedConfigFileName) { - cache.removeKey(configFilePath); - } - - return { - parseConfigFile, - removeKey - }; - } function newer(date1: Date, date2: Date): Date { return date2 > date1 ? date2 : date1; @@ -387,7 +353,7 @@ namespace ts { export function createBuildContext(options: BuildOptions, toPath: ToResolvedConfigFilePath): BuildContext { const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; let nextIndex = 0; - const projectPendingBuild = createFileMap(toPath); + const projectPendingBuild = createFileMap(toPath); const missingRoots = createMap(); const diagnostics = options.watch ? createFileMap(toPath) : undefined; @@ -402,31 +368,39 @@ namespace ts { missingRoots }; - function invalidateProject(proj: ResolvedConfigFileName, dependencyGraph: DependencyGraph | undefined) { - if (!projectPendingBuild.hasKey(proj)) { - addProjToQueue(proj); - if (dependencyGraph) { - queueBuildForDownstreamReferences(proj, dependencyGraph); - } + function invalidateProject(proj: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel | undefined, dependencyGraph: DependencyGraph | undefined) { + if (addProjToQueue(proj, reloadLevel) && dependencyGraph) { + queueBuildForDownstreamReferences(proj, dependencyGraph); } } - function addProjToQueue(proj: ResolvedConfigFileName) { - Debug.assert(!projectPendingBuild.hasKey(proj)); - projectPendingBuild.setValue(proj, true); - invalidatedProjectQueue.push(proj); + /** + * return true if new addition + */ + function addProjToQueue(proj: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + const value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + return true; + } + + if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + } } function getNextInvalidatedProject() { if (nextIndex < invalidatedProjectQueue.length) { - const proj = invalidatedProjectQueue[nextIndex]; + const project = invalidatedProjectQueue[nextIndex]; nextIndex++; - projectPendingBuild.removeKey(proj); + const reloadLevel = projectPendingBuild.getValue(project)!; + projectPendingBuild.removeKey(project); if (!projectPendingBuild.getSize()) { invalidatedProjectQueue.length = 0; nextIndex = 0; } - return proj; + return { project, reloadLevel }; } } @@ -439,8 +413,7 @@ namespace ts { const deps = dependencyGraph.dependencyMap.getReferencesTo(root); for (const ref of deps) { // Can skip circular references - if (!projectPendingBuild.hasKey(ref)) { - addProjToQueue(ref); + if (addProjToQueue(ref)) { queueBuildForDownstreamReferences(ref, dependencyGraph); } } @@ -501,12 +474,15 @@ namespace ts { const hostWithWatch = host as SolutionBuilderWithWatchHost; const currentDirectory = host.getCurrentDirectory(); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - const configFileCache = createConfigFileCache(host, toPath); + const parseConfigFileHost = parseConfigHostFromCompilerHost(host); + type ConfigFileCacheEntry = ParsedCommandLine | Diagnostic; + const configFileCache = createFileMap(toPath); let context = createBuildContext(defaultOptions, toPath); let timerToBuildInvalidatedProject: any; let reportFileChangeDetected = false; - const existingWatchersForWildcards = createMap(); + const existingWatchersForWildcards = createFileMap>(toPath); + return { buildAllProjects, getUpToDateStatus, @@ -529,6 +505,24 @@ namespace ts { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } + function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine { + return !!(entry as ParsedCommandLine).options; + } + + function parseConfigFile(configFilePath: ResolvedConfigFileName): ParsedCommandLine | undefined { + const value = configFileCache.getValue(configFilePath); + if (value) { + return isParsedCommandLine(value) ? value : undefined; + } + + let diagnostic: Diagnostic | undefined; + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = d => diagnostic = d; + const parsed = getParsedCommandLineOfConfigFile(configFilePath, {}, parseConfigFileHost); + parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; + configFileCache.setValue(configFilePath, parsed || diagnostic!); + return parsed; + } + function reportStatus(message: DiagnosticMessage, ...args: string[]) { host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } @@ -559,19 +553,36 @@ namespace ts { } for (const resolved of graph.buildQueue) { - const cfg = configFileCache.parseConfigFile(resolved); + const cfg = parseConfigFile(resolved); if (cfg) { // Watch this file hostWithWatch.watchFile(resolved, () => { configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved); + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); }); // Update watchers for wildcard directories if (cfg.configFileSpecs) { - updateWatchingWildcardDirectories(existingWatchersForWildcards, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => { - return hostWithWatch.watchDirectory(dir, () => { - invalidateProjectAndScheduleBuilds(resolved); + const existingWatches = existingWatchersForWildcards.getValue(resolved); + let newWatches: Map | undefined; + if (!existingWatches) { + newWatches = createMap(); + existingWatchersForWildcards.setValue(resolved, newWatches); + } + updateWatchingWildcardDirectories(existingWatches || newWatches!, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => { + return hostWithWatch.watchDirectory(dir, fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, cfg.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + + if (isOutputFile(fileOrDirectory, cfg)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial); }, !!(flags & WatchDirectoryFlags.Recursive)); }); } @@ -579,7 +590,7 @@ namespace ts { // Watch input files for (const input of cfg.fileNames) { hostWithWatch.watchFile(input, () => { - invalidateProjectAndScheduleBuilds(resolved); + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None); }); } } @@ -587,9 +598,41 @@ namespace ts { } - function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName) { + function isOutputFile(fileName: string, configFile: ParsedCommandLine) { + if (configFile.options.noEmit) return false; + + // ts or tsx files are not output + if (!fileExtensionIs(fileName, Extension.Dts) && + (fileExtensionIs(fileName, Extension.Ts) || fileExtensionIs(fileName, Extension.Tsx))) { + return false; + } + + // If options have --outFile or --out, check if its that + const out = configFile.options.outFile || configFile.options.out; + if (out && (isSameFile(fileName, out) || isSameFile(fileName, removeFileExtension(out) + Extension.Dts))) { + return true; + } + + // If declarationDir is specified, return if its a file in that directory + if (configFile.options.declarationDir && containsPath(configFile.options.declarationDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + // If --outDir, check if file is in that directory + if (configFile.options.outDir && containsPath(configFile.options.outDir, fileName, currentDirectory, !host.useCaseSensitiveFileNames())) { + return true; + } + + return !forEach(configFile.fileNames, inputFile => isSameFile(fileName, inputFile)); + } + + function isSameFile(file1: string, file2: string) { + return comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === Comparison.EqualTo; + } + + function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { reportFileChangeDetected = true; - invalidateProject(resolved); + invalidateProject(resolved, reloadLevel); scheduleBuildInvalidatedProject(); } @@ -598,7 +641,7 @@ namespace ts { } function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus { - return getUpToDateStatus(configFileCache.parseConfigFile(configFileName)); + return getUpToDateStatus(parseConfigFile(configFileName)); } function getBuildGraph(configFileNames: ReadonlyArray) { @@ -712,7 +755,7 @@ namespace ts { for (const ref of project.projectReferences) { usesPrepend = usesPrepend || !!(ref.prepend); const resolvedRef = resolveProjectReferencePath(host, ref); - const refStatus = getUpToDateStatus(configFileCache.parseConfigFile(resolvedRef)); + const refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); // An upstream project is blocked if (refStatus.type === UpToDateStatusType.Unbuildable) { @@ -789,7 +832,7 @@ namespace ts { }; } - function invalidateProject(configFileName: string) { + function invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel) { const resolved = resolveProjectName(configFileName); if (resolved === undefined) { // If this was a rootName, we need to track it as missing. @@ -800,13 +843,12 @@ namespace ts { return; } - configFileCache.removeKey(resolved); context.projectStatus.removeKey(resolved); if (context.options.watch) { context.diagnostics!.removeKey(resolved); } - context.invalidateProject(resolved, getGlobalDependencyGraph()); + context.invalidateProject(resolved, reloadLevel, getGlobalDependencyGraph()); } function scheduleBuildInvalidatedProject() { @@ -826,14 +868,16 @@ namespace ts { reportWatchStatus(Diagnostics.File_change_detected_Starting_incremental_compilation); } const buildProject = context.getNextInvalidatedProject(); - buildSomeProjects(p => p === buildProject); - if (context.hasPendingInvalidatedProjects()) { - if (!timerToBuildInvalidatedProject) { - scheduleBuildInvalidatedProject(); + if (buildProject) { + buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); + if (context.hasPendingInvalidatedProjects()) { + if (!timerToBuildInvalidatedProject) { + scheduleBuildInvalidatedProject(); + } + } + else { + reportErrorSummary(); } - } - else { - reportErrorSummary(); } } @@ -845,29 +889,37 @@ namespace ts { } } - function buildSomeProjects(predicate: (projName: ResolvedConfigFileName) => boolean) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return; + function buildSingleInvalidatedProject(project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { + // TODO:: handle this in better way later - const graph = createDependencyGraph(resolvedNames)!; - for (const next of graph.buildQueue) { - if (!predicate(next)) continue; + const resolved = resolveProjectName(project); + if (!resolved) return; // ?? + const proj = parseConfigFile(resolved); + if (!proj) return; // ? + // TODO:: If full reload , update watch for wild cards + // TODO:: If full or partial reload, update watch for input files - const resolved = resolveProjectName(next); - if (!resolved) continue; // ?? - const proj = configFileCache.parseConfigFile(resolved); - if (!proj) continue; // ? - - const status = getUpToDateStatus(proj); - verboseReportProjectStatus(next, status); - - if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); - continue; + if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { + // Update file names + const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(project), proj.options, parseConfigFileHost); + if (result.fileNames.length !== 0) { + filterMutate(proj.errors, error => !isErrorNoInputFiles(error)); } - - buildSingleProject(next); + else if (!proj.configFileSpecs!.filesSpecs && !some(proj.errors, isErrorNoInputFiles)) { + proj.errors.push(getErrorForNoInputFiles(proj.configFileSpecs!, resolved)); + } + proj.fileNames = result.fileNames; } + + const status = getUpToDateStatus(proj); + verboseReportProjectStatus(project, status); + + if (status.type === UpToDateStatusType.UpstreamBlocked) { + if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + return; + } + + buildSingleProject(project); } function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined { @@ -907,7 +959,7 @@ namespace ts { temporaryMarks[projPath] = true; circularityReportStack.push(projPath); - const parsed = configFileCache.parseConfigFile(projPath); + const parsed = parseConfigFile(projPath); if (parsed === undefined) { hadError = true; return; @@ -941,10 +993,11 @@ namespace ts { let resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; - const configFile = configFileCache.parseConfigFile(proj); + const configFile = parseConfigFile(proj); if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; + host.reportDiagnostic(configFileCache.getValue(proj) as Diagnostic); storeErrorSummary(proj, 1); context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; @@ -959,7 +1012,8 @@ namespace ts { projectReferences: configFile.projectReferences, host, rootNames: configFile.fileNames, - options: configFile.options + options: configFile.options, + configFileParsingDiagnostics: configFile.errors }; const program = createProgram(programOptions); @@ -1068,7 +1122,7 @@ namespace ts { const filesToDelete: string[] = []; for (const proj of graph.buildQueue) { - const parsed = configFileCache.parseConfigFile(proj); + const parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here continue; @@ -1155,7 +1209,7 @@ namespace ts { let anyFailed = false; for (const next of queue) { - const proj = configFileCache.parseConfigFile(next); + const proj = parseConfigFile(next); if (proj === undefined) { anyFailed = true; break; diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index daa1276e023..c9c57379ec2 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -26,8 +26,12 @@ namespace ts.tscWatch { type SubProjectFiles = [ReadonlyFile, ReadonlyFile] | [ReadonlyFile, ReadonlyFile, ReadonlyFile, ReadonlyFile]; const root = Harness.IO.getWorkspaceRoot(); + function projectPath(subProject: SubProject) { + return `${projectsLocation}/${project}/${subProject}`; + } + function projectFilePath(subProject: SubProject, baseFileName: string) { - return `${projectsLocation}/${project}/${subProject}/${baseFileName.toLowerCase()}`; + return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`; } function projectFile(subProject: SubProject, baseFileName: string): File { @@ -92,7 +96,7 @@ namespace ts.tscWatch { createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); checkWatchedFiles(host, testProjectExpectedWatchedFiles); checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, emptyArray, /*recursive*/ true); // TODO: #26524 + checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); checkOutputErrorsInitial(host, emptyArray); const outputFileStamps = getOutputFileStamps(host); for (const stamp of outputFileStamps) { From 78c800350426a542335ccd46791311e0d1fd90a7 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Mon, 10 Sep 2018 13:22:30 -0700 Subject: [PATCH 075/146] Update user baselines (#27000) --- tests/baselines/reference/user/acorn.log | 141 ++++++------ .../user/chrome-devtools-frontend.log | 214 ++++++++---------- tests/baselines/reference/user/debug.log | 16 +- tests/baselines/reference/user/npm.log | 9 +- tests/baselines/reference/user/puppeteer.log | 3 +- tests/baselines/reference/user/uglify-js.log | 4 + 6 files changed, 182 insertions(+), 205 deletions(-) diff --git a/tests/baselines/reference/user/acorn.log b/tests/baselines/reference/user/acorn.log index 7780ccb6e48..75c36a98697 100644 --- a/tests/baselines/reference/user/acorn.log +++ b/tests/baselines/reference/user/acorn.log @@ -15,43 +15,43 @@ node_modules/acorn/dist/acorn.es.js(545,15): error TS2339: Property 'parseTopLev node_modules/acorn/dist/acorn.es.js(558,14): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.es.js(718,25): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.es.js(738,25): error TS2531: Object is possibly 'null'. -node_modules/acorn/dist/acorn.es.js(2751,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2751,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2751,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.es.js(2962,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2963,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2966,18): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2967,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2968,16): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2970,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2974,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2974,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2975,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2979,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2980,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2985,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2986,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2995,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2996,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2998,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(2999,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3003,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3004,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3006,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3007,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3012,22): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3013,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2752,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2752,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2752,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.es.js(2963,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2964,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2967,18): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2968,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2969,16): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2971,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2975,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2975,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2976,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2980,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2981,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2986,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2987,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2996,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2997,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(2999,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3000,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3004,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3005,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3007,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3008,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3013,22): error TS2339: Property 'context' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.es.js(3014,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3016,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3018,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3023,12): error TS2339: Property 'options' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3024,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3024,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3015,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3017,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3019,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3024,12): error TS2339: Property 'options' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.es.js(3025,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3025,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(3028,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.es.js(5290,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. -node_modules/acorn/dist/acorn.es.js(5291,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.es.js(3025,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3026,14): error TS2339: Property 'value' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3026,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(3029,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.es.js(5291,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.es.js(5292,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. node_modules/acorn/dist/acorn.js(3,9): error TS2304: Cannot find name 'define'. node_modules/acorn/dist/acorn.js(3,34): error TS2304: Cannot find name 'define'. node_modules/acorn/dist/acorn.js(3,47): error TS2304: Cannot find name 'define'. @@ -64,43 +64,44 @@ node_modules/acorn/dist/acorn.js(551,15): error TS2339: Property 'parseTopLevel' node_modules/acorn/dist/acorn.js(564,14): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.js(724,25): error TS2531: Object is possibly 'null'. node_modules/acorn/dist/acorn.js(744,25): error TS2531: Object is possibly 'null'. -node_modules/acorn/dist/acorn.js(2757,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2757,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2757,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. -node_modules/acorn/dist/acorn.js(2968,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2969,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2972,18): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2973,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2974,16): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2976,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2980,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2980,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2981,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2985,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2986,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2991,8): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(2992,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3001,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3002,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3004,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3005,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3009,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3010,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3012,12): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3013,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3018,22): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3019,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2758,7): error TS2339: Property 'pos' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2758,22): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2758,37): error TS2339: Property 'raisedAt' does not exist on type 'SyntaxError'. +node_modules/acorn/dist/acorn.js(2969,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2970,10): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2973,18): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2974,38): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2975,16): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2977,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2981,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2981,26): error TS2339: Property 'braceIsBlock' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2982,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2986,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2987,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2992,8): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(2993,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3002,73): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3003,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3005,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3006,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3010,12): error TS2339: Property 'curContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3011,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3013,12): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3014,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3019,22): error TS2339: Property 'context' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.js(3020,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3022,14): error TS2339: Property 'context' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3024,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3029,12): error TS2339: Property 'options' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3030,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3030,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3021,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3023,14): error TS2339: Property 'context' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3025,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3030,12): error TS2339: Property 'options' does not exist on type 'TokenType'. node_modules/acorn/dist/acorn.js(3031,14): error TS2339: Property 'value' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3031,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(3034,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. -node_modules/acorn/dist/acorn.js(5296,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. -node_modules/acorn/dist/acorn.js(5297,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.js(3031,38): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3032,14): error TS2339: Property 'value' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3032,40): error TS2339: Property 'inGeneratorContext' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(3035,8): error TS2339: Property 'exprAllowed' does not exist on type 'TokenType'. +node_modules/acorn/dist/acorn.js(5297,5): error TS2339: Property 'nextToken' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn.js(5298,12): error TS2339: Property 'parseExpression' does not exist on type 'Parser'. +node_modules/acorn/dist/acorn_loose.es.js(1,56): error TS2440: Import declaration conflicts with local declaration of 'defaultOptions'. node_modules/acorn/dist/acorn_loose.es.js(73,9): error TS2339: Property 'name' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,9): error TS2339: Property 'value' does not exist on type 'Node'. node_modules/acorn/dist/acorn_loose.es.js(79,23): error TS2339: Property 'raw' does not exist on type 'Node'. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 6085bb91b9e..e58d2188be4 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -46,6 +46,7 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(1088,15): error TS235 node_modules/chrome-devtools-frontend/front_end/Tests.js(107,5): error TS2322: Type 'Timer' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/Tests.js(208,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(221,7): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(378,17): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(397,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(416,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(440,5): error TS2554: Expected 4 arguments, but got 3. @@ -55,6 +56,7 @@ node_modules/chrome-devtools-frontend/front_end/Tests.js(590,27): error TS2554: node_modules/chrome-devtools-frontend/front_end/Tests.js(687,7): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(711,7): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(735,5): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(814,38): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(816,7): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/Tests.js(847,9): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/Tests.js(848,9): error TS2554: Expected 2 arguments, but got 1. @@ -86,10 +88,14 @@ node_modules/chrome-devtools-frontend/front_end/Tests.js(977,11): error TS2554: node_modules/chrome-devtools-frontend/front_end/Tests.js(978,11): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(986,5): error TS2554: Expected 3 arguments, but got 2. node_modules/chrome-devtools-frontend/front_end/Tests.js(988,5): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1033,32): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1040,30): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1084,27): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1139,33): error TS2339: Property 'ConsoleView' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1142,31): error TS2339: Property 'ConsoleView' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1186,5): error TS2554: Expected 4 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/Tests.js(1199,9): error TS2554: Expected 4 arguments, but got 3. +node_modules/chrome-devtools-frontend/front_end/Tests.js(1199,35): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1229,10): error TS2339: Property 'uiTests' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Tests.js(1229,41): error TS2339: Property 'domAutomationController' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(9,11): error TS2554: Expected 2 arguments, but got 1. @@ -109,10 +115,8 @@ node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(182,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(209,39): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAAttributesView.js(213,36): error TS2339: Property '_isEditingName' does not exist on type 'ARIAAttributePrompt'. -node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAConfig.js(5,28): error TS2339: Property '_config' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(56,35): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(57,32): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. -node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(57,102): error TS2339: Property '_config' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/ARIAMetadata.js(58,37): error TS2339: Property '_instance' does not exist on type 'typeof ARIAMetadata'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(10,11): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(14,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. @@ -431,10 +435,27 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(380,11) node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(387,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(394,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationUI.js(402,11): error TS2339: Property 'AnimationUI' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(53,47): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(102,25): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(130,39): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/AppcacheTestRunner.js(131,36): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(11,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(13,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(19,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(21,37): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(32,5): error TS2304: Cannot find name 'promise'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(40,11): error TS2304: Cannot find name 'promise'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(61,13): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(68,37): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(70,13): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(135,10): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(12,40): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(47,42): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/IndexedDBTestRunner.js(140,24): error TS2554: Expected 1 arguments, but got 2. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourceTreeTestRunner.js(69,18): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourcesTestRunner.js(76,15): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ResourcesTestRunner.js(77,33): error TS2339: Property 'resources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/ServiceWorkersTestRunner.js(44,26): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(16,50): error TS2345: Argument of type '(msg: string) => void' is not assignable to parameter of type '(arg0: string) => undefined'. Type 'void' is not assignable to type 'undefined'. node_modules/chrome-devtools-frontend/front_end/audits2/Audits2Panel.js(16,76): error TS2555: Expected at least 2 arguments, but got 1. @@ -843,6 +864,16 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24079,1): error TS2323: Cannot redeclare exported variable 'Buf16'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(24080,1): error TS2323: Cannot redeclare exported variable 'Buf32'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(26059,1): error TS2323: Cannot redeclare exported variable 'deflate'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27915,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27918,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27921,30): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27928,27): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27929,20): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(27956,16): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28222,51): error TS2300: Duplicate identifier '_read'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(28457,20): error TS2339: Property 'emit' does not exist on type 'Readable'. @@ -3223,7 +3254,7 @@ node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(47,37): e node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(50,20): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(75,11): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(111,22): error TS2554: Expected 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(133,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(133,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(139,22): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(155,26): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/changes/ChangesView.js(156,25): error TS2339: Property 'pushAll' does not exist on type 'any[]'. @@ -3600,14 +3631,6 @@ node_modules/chrome-devtools-frontend/front_end/common/Color.js(149,13): error T node_modules/chrome-devtools-frontend/front_end/common/Color.js(182,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(217,15): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(235,58): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(320,58): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(321,49): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(323,48): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(324,30): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(369,82): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(371,82): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(375,61): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(376,43): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(563,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(566,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(573,23): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. @@ -3623,8 +3646,6 @@ node_modules/chrome-devtools-frontend/front_end/common/Color.js(650,25): error T node_modules/chrome-devtools-frontend/front_end/common/Color.js(661,5): error TS2322: Type '{ r: number; g: number; b: number; }' is not assignable to type '{ r: number; g: number; b: number; a: number; }'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(661,5): error TS2322: Type '{ r: number; g: number; b: number; }' is not assignable to type '{ r: number; g: number; b: number; a: number; }'. Property 'a' is missing in type '{ r: number; g: number; b: number; }'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(718,24): error TS2339: Property '_tmpHSLA' does not exist on type '(hsva: number[], out_rgba: number[]) => void'. -node_modules/chrome-devtools-frontend/front_end/common/Color.js(721,37): error TS2339: Property '_blendedFg' does not exist on type '(fgRGBA: number[], bgRGBA: number[]) => number'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(934,23): error TS2339: Property 'hashCode' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/Color.js(935,45): error TS2345: Argument of type 'number | { min: number; max: number; }' is not assignable to parameter of type 'number | { min: number; max: number; count: number; }'. Type '{ min: number; max: number; }' is not assignable to type 'number | { min: number; max: number; count: number; }'. @@ -3772,7 +3793,6 @@ node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(390,12): node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(392,12): error TS2339: Property 'href' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(418,10): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(432,31): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(440,43): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(443,16): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(445,16): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/components/Linkifier.js(481,27): error TS2694: Namespace 'Components' has no exported member '_LinkInfo'. @@ -4165,7 +4185,6 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(14 node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1430,15): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1431,15): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1433,33): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1435,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1435,76): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1437,55): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(1453,26): error TS2339: Property 'ConsoleViewMessage' does not exist on type '{ new (): Console; prototype: Console; }'. @@ -4391,7 +4410,6 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(19, node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(21,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(29,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(112,11): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(201,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(206,18): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(208,18): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageListView.js(210,18): error TS2555: Expected at least 2 arguments, but got 1. @@ -4422,13 +4440,7 @@ node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(210,23 node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(214,21): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(230,25): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(250,31): error TS2694: Namespace 'Coverage' has no exported member 'RangeUseCount'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(251,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(267,37): error TS2339: Property 'peekLast' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(288,26): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(301,25): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(340,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(371,24): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. -node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(398,25): error TS2694: Namespace 'Coverage' has no exported member 'CoverageType'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(405,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(427,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. node_modules/chrome-devtools-frontend/front_end/coverage/CoverageModel.js(428,31): error TS2694: Namespace 'Coverage' has no exported member 'CoverageSegment'. @@ -4459,6 +4471,9 @@ node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTes node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(28,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(52,31): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/coverage_test_runner/CoverageTestRunner.js(87,31): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(12,35): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(49,15): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/cpu_profiler_test_runner/ProfilerTestRunner.js(54,33): error TS2339: Property 'js_profiler' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(32,41): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(41,18): error TS2339: Property 'tabIndex' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(49,40): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -4935,9 +4950,8 @@ node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1290,2 node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1292,31): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1293,28): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. node_modules/chrome-devtools-frontend/front_end/devtools_compatibility.js(1302,19): error TS2339: Property '__originalDOMTokenListToggle' does not exist on type 'DOMTokenList'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(22,21): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(43,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(91,33): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(22,26): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/diff/Diff.js(43,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,116): error TS2322: Type 'string[]' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. Property 'chars1' is missing in type 'string[]'. node_modules/chrome-devtools-frontend/front_end/diff/diff_match_patch.js(6,240): error TS2322: Type '0' is not assignable to type '{ chars1: string; chars2: string; lineArray: string[]; }'. @@ -5351,7 +5365,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(855,24): error TS2339: Property 'keyCode' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(855,79): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(856,15): error TS2339: Property 'consume' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(868,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(878,19): error TS2339: Property 'runPendingUpdates' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(972,37): error TS2339: Property 'selectNodeAfterEdit' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1106,27): error TS2339: Property '_decoratorExtensions' does not exist on type 'TreeOutline'. @@ -5388,7 +5401,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1528,37): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1533,40): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1537,18): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(1577,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElementHighlighter.js(24,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(34,32): error TS2417: Class static side 'typeof ElementsTreeOutline' incorrectly extends base class static side 'typeof TreeOutline'. Types of property 'Events' are incompatible. @@ -5404,7 +5416,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(173,11): error TS2339: Property 'handled' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(197,11): error TS2339: Property 'handled' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(254,11): error TS2339: Property 'handled' does not exist on type 'Event'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(270,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(271,26): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(495,29): error TS2339: Property 'totalOffsetLeft' does not exist on type 'HTMLElement'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(515,19): error TS2694: Namespace 'UI' has no exported member 'PopoverRequest'. @@ -5420,7 +5431,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(755,33): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(758,36): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(813,22): error TS2339: Property 'index' does not exist on type 'DOMNode'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(847,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2322: Type 'Node & ParentNode' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2322: Type 'Node & ParentNode' is not assignable to type 'Element'. Property 'assignedSlot' is missing in type 'Node & ParentNode'. @@ -5756,7 +5766,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(29 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3021,19): error TS2339: Property 'key' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3049,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3120,39): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3244,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3265,15): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3272,15): error TS2339: Property 'createTextChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3282,41): error TS2555: Expected at least 2 arguments, but got 1. @@ -5767,13 +5776,26 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(33 Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. Property 'item' is missing in type 'ToolbarButton'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/EditDOMTestRunner.js(15,5): error TS2304: Cannot find name 'eventSender'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/EditDOMTestRunner.js(19,37): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(112,55): error TS2339: Property 'eventListener' does not exist on type 'TreeElement'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(128,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(132,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(191,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(316,20): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(322,13): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(326,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(372,22): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(384,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(429,28): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(490,15): error TS2339: Property 'runtime' does not exist on type 'Window'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(549,33): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(735,11): error TS2540: Cannot assign to 'name' because it is a constant or a read-only property. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1024,26): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1048,13): error TS2339: Property 'elements' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1052,13): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/ElementsTestRunner.js(1080,35): error TS2339: Property 'AnimationTimeline' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js(99,35): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/elements_test_runner/StylesUpdateLinksTestRunner.js(119,31): error TS2339: Property 'elements' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(56,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(92,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/emulation/AdvancedApp.js(105,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -6125,7 +6147,6 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(789,2 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionAPI.js(790,12): error TS2339: Property 'webInspector' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(232,23): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(240,18): error TS2339: Property 'style' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(246,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionPanel.js(279,40): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionRegistryStub.js(30,13): error TS2339: Property 'InspectorExtensionRegistry' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(129,5): error TS2555: Expected at least 2 arguments, but got 1. @@ -6137,11 +6158,9 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(24 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(290,77): error TS2345: Argument of type 'ToolbarButton' is not assignable to parameter of type '{ item(): any & any; } & { item(): any & any; }'. Type 'ToolbarButton' is not assignable to type '{ item(): any & any; }'. Property 'item' is missing in type 'ToolbarButton'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(416,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(463,53): error TS2345: Argument of type '{ url: string; type: string; }' is not assignable to parameter of type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property 'contentURL' is missing in type '{ url: string; type: string; }'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(471,22): error TS2339: Property 'valuesArray' does not exist on type 'Map; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }>'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(502,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(542,14): error TS2339: Property '_extensionOrigin' does not exist on type 'MessagePort'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(567,30): error TS2339: Property 'KeyboardEvent' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(599,76): error TS2345: Argument of type 'symbol' is not assignable to parameter of type 'string'. @@ -6476,6 +6495,13 @@ node_modules/chrome-devtools-frontend/front_end/formatter_worker.js(5,11): error node_modules/chrome-devtools-frontend/front_end/formatter_worker.js(6,8): error TS2339: Property 'importScripts' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(26,11): error TS2403: Subsequent variable declarations must have the same type. Variable 'page' must be of type 'any', but here has type 'HARPage'. node_modules/chrome-devtools-frontend/front_end/har_importer/HARImporter.js(46,5): error TS2322: Type 'Date' is not assignable to type 'number'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(320,70): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(321,35): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(366,55): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(590,24): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(624,20): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(653,15): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(658,33): error TS2339: Property 'heap_profiler' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(678,36): error TS2339: Property 'instance' does not exist on type 'typeof SamplingHeapProfileType'. node_modules/chrome-devtools-frontend/front_end/heap_profiler_test_runner/HeapProfilerTestRunner.js(682,36): error TS2339: Property 'instance' does not exist on type 'typeof SamplingHeapProfileType'. node_modules/chrome-devtools-frontend/front_end/heap_snapshot_worker/HeapSnapshot.js(37,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -6735,8 +6761,6 @@ node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(356,20): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(361,30): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowEditor.js(367,20): error TS2339: Property 'value' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowModel.js(46,38): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/CSSShadowModel.js(63,41): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(16,35): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(17,32): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(21,83): error TS2339: Property '_constructor' does not exist on type 'typeof ColorSwatch'. @@ -6755,7 +6779,6 @@ node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(210 node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(227,39): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(228,36): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(232,91): error TS2339: Property '_constructor' does not exist on type 'typeof CSSShadowSwatch'. -node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(248,39): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(290,10): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/inline_editor/ColorSwatch.js(291,33): error TS2339: Property 'createChild' does not exist on type 'CSSShadowSwatch'. node_modules/chrome-devtools-frontend/front_end/inline_editor/SwatchPopoverHelper.js(13,37): error TS2345: Argument of type 'symbol' is not assignable to parameter of type 'boolean'. @@ -6980,6 +7003,7 @@ node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(150,22): e node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(160,58): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(169,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/layers/LayersPanel.js(187,22): error TS2694: Namespace 'Common' has no exported member 'Event'. +node_modules/chrome-devtools-frontend/front_end/layers_test_runner/LayersTestRunner.js(55,22): error TS2339: Property 'layers' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/layers_test_runner/LayersTestRunner.js(130,3): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/main/ExecutionContextSelector.js(63,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/main/ExecutionContextSelector.js(83,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -7099,7 +7123,6 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottl node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(37,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(38,31): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/NetworkThrottlingSelector.js(43,62): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(11,34): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(16,59): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(18,36): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(20,36): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. @@ -7117,13 +7140,11 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingMana node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(141,81): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(147,42): error TS2694: Namespace 'MobileThrottling' has no exported member 'MobileThrottlingConditionsGroup'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(148,35): error TS2694: Namespace 'MobileThrottling' has no exported member 'ConditionsList'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(178,32): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(188,20): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(218,82): error TS2339: Property 'selectedIndex' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(224,32): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingManager.js(266,15): error TS2339: Property 'singleton' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(16,35): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(17,43): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(20,18): error TS2300: Duplicate identifier 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(22,30): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(25,16): error TS2555: Expected at least 2 arguments, but got 1. @@ -7146,7 +7167,6 @@ node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPres node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(77,38): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(82,38): error TS2694: Namespace 'MobileThrottling' has no exported member 'Conditions'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(87,39): error TS2694: Namespace 'SDK.NetworkManager' has no exported member 'Conditions'. -node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingPresets.js(94,37): error TS2694: Namespace 'MobileThrottling' has no exported member 'CPUThrottlingRates'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(14,25): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(14,68): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/mobile_throttling/ThrottlingSettingsTab.js(17,9): error TS2555: Expected at least 2 arguments, but got 1. @@ -7735,6 +7755,9 @@ node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriori node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(56,29): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(57,66): error TS2339: Property '_symbolicToNumericPriorityMap' does not exist on type '() => Map'. node_modules/chrome-devtools-frontend/front_end/network_priorities/NetworkPriorities.js(68,48): error TS2339: Property '_symbolicToNumericPriorityMap' does not exist on type '() => Map'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(20,34): error TS2339: Property 'network' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(49,13): error TS2339: Property 'network' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(53,20): error TS2339: Property 'network' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,8): error TS2304: Cannot find name 'i'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,15): error TS2304: Cannot find name 'i'. node_modules/chrome-devtools-frontend/front_end/network_test_runner/NetworkTestRunner.js(69,36): error TS2304: Cannot find name 'i'. @@ -8096,12 +8119,23 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js( node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js(495,14): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineOverviewPane.js(508,61): error TS2339: Property 'boxInWindow' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(74,36): error TS2554: Expected 0 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(81,20): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(91,33): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(98,5): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(108,20): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(120,43): error TS2554: Expected 0 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(130,13): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(131,97): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(135,35): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(139,27): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(147,15): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(159,9): error TS2554: Expected 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(189,60): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(220,44): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(254,19): error TS2554: Expected 2 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(321,53): error TS2345: Argument of type 'number' is not assignable to parameter of type 'V'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(347,30): error TS2339: Property 'timeline' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/performance_test_runner/TimelineTestRunner.js(355,13): error TS2339: Property 'timeline' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(67,40): error TS2339: Property 'valuesArray' does not exist on type 'Set'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(155,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/persistence/Automapping.js(315,20): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -8951,7 +8985,6 @@ node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(310 node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(312,16): error TS2339: Property 'sendRequestTime' does not exist on type '(arg0: any) => any'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(422,49): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(422,67): error TS2339: Property 'context' does not exist on type 'Console'. -node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(634,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(716,49): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/protocol/InspectorBackend.js(716,67): error TS2339: Property 'context' does not exist on type 'Console'. node_modules/chrome-devtools-frontend/front_end/quick_open/CommandMenu.js(75,10): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -9556,7 +9589,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(18,24): error node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(39,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(168,56): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(170,17): error TS2339: Property 'runtime' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/sdk/CSSProperty.js(259,32): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(9,24): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(33,32): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. node_modules/chrome-devtools-frontend/front_end/sdk/CSSRule.js(33,98): error TS2694: Namespace 'Protocol' has no exported member 'CSS'. @@ -9634,14 +9666,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(136,53): error T node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(137,28): error TS2339: Property 'documentElement' does not exist on type 'DOMDocument'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(138,53): error TS2339: Property 'body' does not exist on type 'DOMDocument'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(139,28): error TS2339: Property 'body' does not exist on type 'DOMDocument'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(369,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(396,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(419,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(433,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(447,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(454,35): error TS2694: Namespace 'SDK.DOMNode' has no exported member 'Attribute'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(507,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(519,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(554,31): error TS2339: Property 'index' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(555,16): error TS2339: Property 'index' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(590,25): error TS2694: Namespace 'Protocol' has no exported member 'Page'. @@ -9650,9 +9675,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(659,32): error T node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(672,32): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(687,32): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(743,24): error TS2339: Property 'remove' does not exist on type 'any[]'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(751,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(751,50): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(768,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(852,31): error TS2339: Property 'baseURL' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(853,65): error TS2339: Property 'baseURL' does not exist on type 'DOMNode'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(860,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -9671,8 +9694,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1096,16): error node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1165,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1176,34): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1188,46): error TS2339: Property 'valuesArray' does not exist on type 'Set'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1203,34): error TS2694: Namespace 'Protocol' has no exported member 'Error'. -node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1208,26): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1214,16): error TS2345: Argument of type 'T' is not assignable to parameter of type 'T'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1220,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/sdk/DOMModel.js(1235,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. @@ -9741,11 +9762,8 @@ node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(355,24): er node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(356,24): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(389,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(419,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(421,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(429,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(431,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(431,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(432,24): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(433,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(434,32): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/DebuggerModel.js(435,24): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -10259,9 +10277,7 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(489,36): err node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(492,18): error TS2339: Property 'CompileScriptResult' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(503,18): error TS2339: Property 'EvaluationOptions' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(507,36): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(508,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(511,18): error TS2339: Property 'EvaluationResult' does not exist on type 'typeof RuntimeModel'. -node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(515,25): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(518,18): error TS2339: Property 'QueryObjectResult' does not exist on type 'typeof RuntimeModel'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(523,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/RuntimeModel.js(526,30): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -10300,11 +10316,11 @@ node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(159,5): error TS23 node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(159,5): error TS2322: Type 'StaticContentProvider' is not assignable to type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Property '_contentURL' does not exist on type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(174,43): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. -node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,33): error TS2694: Namespace 'Protocol' has no exported member 'Error'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,50): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,95): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,127): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(190,158): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. +node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(198,16): error TS2345: Argument of type '"Script failed to parse"' is not assignable to parameter of type 'symbol'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(203,54): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(247,31): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/sdk/Script.js(251,54): error TS2339: Property 'debuggerAgent' does not exist on type 'Target'. @@ -10764,8 +10780,8 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/ResourceSourceFrame node_modules/chrome-devtools-frontend/front_end/source_frame/ResourceSourceFrame.js(69,5): error TS2554: Expected 3 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(15,22): error TS2339: Property 'installGutter' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(89,28): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(110,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(177,20): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(110,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(177,25): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(202,16): error TS2403: Subsequent variable declarations must have the same type. Variable 'lineNumber' must be of type 'any', but here has type 'number'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(206,41): error TS2339: Property 'diff' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourceCodeDiff.js(275,22): error TS2339: Property 'setGutterDecoration' does not exist on type 'CodeMirrorTextEditor'. @@ -10796,9 +10812,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(39,23): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(45,12): error TS2339: Property '_isHandlingMouseDownEvent' does not exist on type 'SourcesTextEditor'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(54,20): error TS2694: Namespace 'UI' has no exported member 'AutocompleteConfig'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(55,65): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(73,53): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(80,53): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(90,14): error TS2403: Subsequent variable declarations must have the same type. Variable 'i' must be of type 'number', but here has type 'string'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(93,29): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(134,12): error TS2339: Property '_tokenHighlighter' does not exist on type 'CodeMirrorTextEditor'. @@ -10823,13 +10836,11 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(284,25): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(285,25): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(295,38): error TS2339: Property 'lineInfo' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(359,40): error TS2339: Property 'Indent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(360,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(361,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(363,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(364,25): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(373,23): error TS2339: Property 'setOption' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(392,72): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(393,27): error TS2339: Property 'replaceRange' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(409,25): error TS2339: Property 'operation' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(411,35): error TS2339: Property 'getCursor' does not exist on type 'CodeMirror'. @@ -10844,10 +10855,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(614,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(622,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(631,14): error TS2339: Property 'operation' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(639,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(670,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(714,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(729,40): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(764,24): error TS2339: Property 'removeLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(769,24): error TS2339: Property 'addLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(780,51): error TS2339: Property 'markText' does not exist on type 'CodeMirror'. @@ -10857,9 +10864,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(803,39): error TS2339: Property 'getSelections' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(809,26): error TS2339: Property 'addLineClass' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(821,33): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(822,63): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(823,72): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(824,59): error TS2339: Property 'isWord' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(829,24): error TS2339: Property 'removeOverlay' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(839,9): error TS2367: This condition will always return 'false' since the types 'void' and 'number' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(854,9): error TS1345: An expression of type 'void' cannot be tested for truthiness @@ -10868,11 +10872,9 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.j node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,9): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,33): error TS1345: An expression of type 'void' cannot be tested for truthiness -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(873,70): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(874,14): error TS2367: This condition will always return 'false' since the types 'void' and 'number' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,12): error TS1345: An expression of type 'void' cannot be tested for truthiness node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,12): error TS1345: An expression of type 'void' cannot be tested for truthiness -node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,46): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(878,71): error TS2367: This condition will always return 'true' since the types 'void' and 'string' have no overlap. node_modules/chrome-devtools-frontend/front_end/source_frame/SourcesTextEditor.js(887,22): error TS2339: Property 'addOverlay' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(39,35): error TS2555: Expected at least 2 arguments, but got 1. @@ -10916,7 +10918,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/AdvancedSearchView.js(31 node_modules/chrome-devtools-frontend/front_end/sources/AdvancedSearchView.js(397,46): error TS2339: Property 'window' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(84,13): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(102,19): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. -node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(150,41): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(197,26): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(197,34): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(212,26): error TS2339: Property 'title' does not exist on type 'Element'. @@ -10928,7 +10929,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(266,25): er node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(288,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(292,25): error TS2339: Property 'setBezierText' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(315,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(327,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/CSSPlugin.js(333,40): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(33,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/CallStackSidebarPane.js(39,57): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -11427,14 +11427,10 @@ node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(550 node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(552,39): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(603,22): error TS2339: Property '_messageBucket' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(604,35): error TS2339: Property 'createChild' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(624,42): error TS2339: Property 'lineIndent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(638,38): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(652,23): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(722,23): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(728,21): error TS2339: Property 'toggleLineClass' does not exist on type 'CodeMirrorTextEditor'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(733,32): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(744,41): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. -node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(745,38): error TS2339: Property '_messageLevelPriority' does not exist on type 'typeof Message'. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(755,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(761,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/sources/UISourceCodeFrame.js(767,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -11527,6 +11523,14 @@ node_modules/chrome-devtools-frontend/front_end/sources_test_runner/BreakpointMa Property '_settings' is missing in type '{ get: () => any; set: (breakpoints: any) => void; }'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/BreakpointManagerTestRunner.js(333,12): error TS2339: Property 'setBreakpointCallback' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(125,28): error TS2339: Property 'sprintf' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(170,17): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(171,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(212,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(218,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(224,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(230,15): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(396,25): error TS2339: Property 'sources' does not exist on type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(426,25): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(483,26): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(515,23): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/DebuggerTestRunner.js(644,15): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -11539,6 +11543,7 @@ node_modules/chrome-devtools-frontend/front_end/sources_test_runner/EditorTestRu node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(91,3): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(94,23): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(95,19): error TS2304: Cannot find name 'editor'. +node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(97,34): error TS2339: Property 'sources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(114,23): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SearchTestRunner.js(115,19): error TS2304: Cannot find name 'editor'. node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SourcesTestRunner.js(26,29): error TS2339: Property 'map' does not exist on type 'NodeListOf'. @@ -11725,19 +11730,7 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(270,27): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(356,16): error TS2339: Property 'addKeyMap' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(395,29): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(425,31): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(425,81): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(426,31): error TS2339: Property 'isUpperCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(426,82): error TS2339: Property 'isLowerCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(438,31): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(438,81): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(439,31): error TS2339: Property 'isUpperCase' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(439,82): error TS2339: Property 'isLowerCase' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(449,60): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(461,61): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(466,29): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(467,63): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(476,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(557,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(565,9): error TS2339: Property 'consume' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(570,18): error TS2694: Namespace 'UI' has no exported member 'AutocompleteConfig'. @@ -11761,13 +11754,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1261,5): error TS2322: Type 'CodeMirrorPositionHandle' is not assignable to type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1261,5): error TS2322: Type 'CodeMirrorPositionHandle' is not assignable to type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. Property '_codeMirror' does not exist on type '{ resolve(): { lineNumber: number; columnNumber: number; }; equal(positionHandle: any): boolean; }'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1280,21): error TS2339: Property 'autocomplete' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1283,21): error TS2339: Property 'undoLastSelection' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1286,21): error TS2339: Property 'selectNextOccurrence' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1289,21): error TS2339: Property 'moveCamelLeft' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1290,21): error TS2339: Property 'selectCamelLeft' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1293,21): error TS2339: Property 'moveCamelRight' does not exist on type 'typeof commands'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1294,21): error TS2339: Property 'selectCamelRight' does not exist on type 'typeof commands'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1301,31): error TS2339: Property 'listSelections' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1305,38): error TS2339: Property 'findMatchingBracket' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1313,14): error TS2339: Property 'setSelections' does not exist on type 'CodeMirror'. @@ -11784,8 +11770,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1392,35): error TS2339: Property 'getLineHandle' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1401,58): error TS2339: Property 'getLineNumber' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1451,22): error TS2339: Property 'execCommand' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1494,96): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1497,90): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1539,44): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1543,22): error TS2339: Property 'eachLine' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/CodeMirrorTextEditor.js(1543,69): error TS2339: Property 'lineCount' does not exist on type 'CodeMirror'. @@ -11823,8 +11807,6 @@ node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocomple node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(55,24): error TS2339: Property 'off' does not exist on type 'CodeMirror'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(62,26): error TS2694: Namespace 'CodeMirror' has no exported member 'BeforeChangeObject'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(67,48): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. -node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(74,25): error TS2339: Property 'textToWords' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(91,25): error TS2339: Property 'textToWords' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(113,40): error TS2694: Namespace 'UI.SuggestBox' has no exported member 'Suggestions'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(135,34): error TS2694: Namespace 'CodeMirror' has no exported member 'ChangeObject'. node_modules/chrome-devtools-frontend/front_end/text_editor/TextEditorAutocompleteController.js(151,47): error TS2339: Property 'getLine' does not exist on type 'CodeMirror'. @@ -11853,28 +11835,10 @@ node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(122,16): erro node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(122,16): error TS2339: Property 'Position' does not exist on type 'typeof Text'. node_modules/chrome-devtools-frontend/front_end/text_utils/Text.js(160,42): error TS2339: Property 'lowerBound' does not exist on type 'number[]'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextRange.js(84,31): error TS2339: Property 'computeLineEndings' does not exist on type 'string'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(35,3): error TS2322: Type '{ isStopChar: (char: string) => boolean; isWordChar: (char: string) => boolean; isSpaceChar: (char: string) => boolean; isWord: (word: string) => boolean; isOpeningBraceChar: (char: string) => boolean; ... 6 more ...; splitStringByRegexes(text: string, regexes: RegExp[]): { ...; }[]; }' is not assignable to type 'typeof TextUtils'. - Object literal may only specify known properties, and 'isStopChar' does not exist in type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(45,33): error TS2339: Property 'isStopChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(45,74): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(53,32): error TS2339: Property '_SpaceCharRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(62,32): error TS2339: Property 'isWordChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(89,32): error TS2339: Property 'isOpeningBraceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(89,80): error TS2339: Property 'isClosingBraceChar' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(118,61): error TS2339: Property 'isSpaceChar' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(201,38): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(202,39): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(210,46): error TS2694: Namespace 'TextUtils.FilterParser' has no exported member 'ParsedFilter'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(213,43): error TS2339: Property 'splitStringByRegexes' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(214,27): error TS2339: Property '_keyValueFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(214,69): error TS2339: Property '_regexFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(215,27): error TS2339: Property '_textFilterRegex' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(243,24): error TS2339: Property 'ParsedFilter' does not exist on type 'typeof FilterParser'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(245,21): error TS2339: Property '_keyValueFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(246,21): error TS2339: Property '_regexFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(247,21): error TS2339: Property '_textFilterRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(248,21): error TS2339: Property '_SpaceCharRegex' does not exist on type 'typeof TextUtils'. -node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(253,21): error TS2339: Property 'Indent' does not exist on type 'typeof TextUtils'. node_modules/chrome-devtools-frontend/front_end/text_utils/TextUtils.js(340,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(59,42): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/CountersGraph.js(75,9): error TS2555: Expected at least 2 arguments, but got 1. @@ -13778,15 +13742,15 @@ node_modules/chrome-devtools-frontend/front_end/workspace/Workspace.js(243,25): Type 'ProjectStore' is not comparable to type '{ workspace(): Workspace; id(): string; type(): string; isServiceProject(): boolean; displayName(): string; requestMetadata(uiSourceCode: UISourceCode): Promise; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }'. Property 'isServiceProject' is missing in type 'ProjectStore'. node_modules/chrome-devtools-frontend/front_end/workspace/Workspace.js(432,27): error TS2339: Property 'valuesArray' does not exist on type 'Map; ... 17 more ...; uiSourceCodes(): UISourceCode[]; }>'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(30,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(30,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(38,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(47,31): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(72,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(80,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(88,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(96,22): error TS2694: Namespace 'Common' has no exported member 'Event'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(236,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. -node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(260,30): error TS2694: Namespace 'Diff' has no exported member 'Diff'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(236,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. +node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(260,35): error TS2694: Namespace 'Diff.Diff' has no exported member 'DiffArray'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(301,36): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(302,33): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. node_modules/chrome-devtools-frontend/front_end/workspace_diff/WorkspaceDiff.js(303,38): error TS2339: Property '_instance' does not exist on type 'typeof WorkspaceDiff'. diff --git a/tests/baselines/reference/user/debug.log b/tests/baselines/reference/user/debug.log index f15ca0b273b..62f54f6f17a 100644 --- a/tests/baselines/reference/user/debug.log +++ b/tests/baselines/reference/user/debug.log @@ -12,18 +12,18 @@ node_modules/debug/src/debug.js(25,1): error TS2323: Cannot redeclare exported v node_modules/debug/src/debug.js(26,1): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/debug/src/debug.js(46,13): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. node_modules/debug/src/debug.js(47,57): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/debug/src/debug.js(51,18): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(51,50): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. +node_modules/debug/src/debug.js(51,18): error TS2339: Property 'colors' does not exist on type 'typeof createDebug'. +node_modules/debug/src/debug.js(51,50): error TS2339: Property 'colors' does not exist on type 'typeof createDebug'. node_modules/debug/src/debug.js(75,10): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. node_modules/debug/src/debug.js(76,10): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. node_modules/debug/src/debug.js(77,10): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(112,13): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. Did you mean 'formatters'? +node_modules/debug/src/debug.js(112,13): error TS2551: Property 'formatArgs' does not exist on type 'typeof createDebug'. Did you mean 'formatters'? node_modules/debug/src/debug.js(114,23): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(114,38): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(120,29): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(125,37): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(126,13): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. -node_modules/debug/src/debug.js(153,11): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: typeof createDebug; names: any[]; skips: any[]; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; instances: any[]; formatters: {}; }'. +node_modules/debug/src/debug.js(114,38): error TS2339: Property 'log' does not exist on type 'typeof createDebug'. +node_modules/debug/src/debug.js(120,29): error TS2339: Property 'useColors' does not exist on type 'typeof createDebug'. +node_modules/debug/src/debug.js(125,37): error TS2339: Property 'init' does not exist on type 'typeof createDebug'. +node_modules/debug/src/debug.js(126,13): error TS2339: Property 'init' does not exist on type 'typeof createDebug'. +node_modules/debug/src/debug.js(153,11): error TS2339: Property 'save' does not exist on type 'typeof createDebug'. node_modules/debug/src/debug.js(155,3): error TS2323: Cannot redeclare exported variable 'names'. node_modules/debug/src/debug.js(156,3): error TS2323: Cannot redeclare exported variable 'skips'. node_modules/debug/src/debug.js(217,12): error TS2304: Cannot find name 'Mixed'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index f2db4a09546..920fae18b06 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -1013,6 +1013,7 @@ node_modules/npm/test/network/registry.js(5,20): error TS2307: Cannot find modul node_modules/npm/test/network/registry.js(29,47): error TS2339: Property '_extend' does not exist on type 'typeof import("util")'. node_modules/npm/test/tap/00-check-mock-dep.js(12,20): error TS2732: Cannot find module 'npm-registry-mock/package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension node_modules/npm/test/tap/00-check-mock-dep.js(13,19): error TS2732: Cannot find module '../../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension +node_modules/npm/test/tap/00-config-setup.js(23,39): error TS2339: Property 'HOME' does not exist on type 'typeof env'. node_modules/npm/test/tap/00-verify-bundle-deps.js(1,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/00-verify-bundle-deps.js(3,24): error TS2732: Cannot find module '../../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension node_modules/npm/test/tap/00-verify-ls-ok.js(2,20): error TS2307: Cannot find module 'tap'. @@ -1222,13 +1223,19 @@ node_modules/npm/test/tap/gist-shortcut.js(7,29): error TS2307: Cannot find modu node_modules/npm/test/tap/gist-shortcut.js(9,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/git-dependency-install-link.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/git-dependency-install-link.js(9,18): error TS2307: Cannot find module 'npm-registry-mock'. +node_modules/npm/test/tap/git-dependency-install-link.js(66,11): error TS2339: Property 'chdir' does not exist on type 'typeof process'. +node_modules/npm/test/tap/git-dependency-install-link.js(84,11): error TS2339: Property 'chdir' does not exist on type 'typeof process'. +node_modules/npm/test/tap/git-dependency-install-link.js(110,11): error TS2339: Property 'kill' does not exist on type 'typeof process'. node_modules/npm/test/tap/git-dependency-install-link.js(125,7): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. +node_modules/npm/test/tap/git-dependency-install-link.js(175,11): error TS2339: Property 'chdir' does not exist on type 'typeof process'. node_modules/npm/test/tap/git-npmignore.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/git-npmignore.js(12,21): error TS2307: Cannot find module 'tacks'. node_modules/npm/test/tap/git-prepare.js(8,22): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/git-prepare.js(9,20): error TS2307: Cannot find module 'npm-registry-mock'. node_modules/npm/test/tap/git-prepare.js(19,21): error TS2307: Cannot find module 'tacks'. +node_modules/npm/test/tap/git-prepare.js(123,11): error TS2339: Property 'kill' does not exist on type 'typeof process'. node_modules/npm/test/tap/git-prepare.js(131,7): error TS2339: Property 'load' does not exist on type 'typeof EventEmitter'. +node_modules/npm/test/tap/git-prepare.js(179,11): error TS2339: Property 'chdir' does not exist on type 'typeof process'. node_modules/npm/test/tap/github-shortcut-package.js(7,29): error TS2307: Cannot find module 'require-inject'. node_modules/npm/test/tap/github-shortcut-package.js(9,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/github-shortcut.js(10,31): error TS2307: Cannot find module 'require-inject'. @@ -1280,6 +1287,7 @@ node_modules/npm/test/tap/install-duplicate-deps-warning.js(8,20): error TS2307: node_modules/npm/test/tap/install-from-local.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/install-into-likenamed-folder.js(6,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/install-link-scripts.js(7,20): error TS2307: Cannot find module 'tap'. +node_modules/npm/test/tap/install-link-scripts.js(130,11): error TS2339: Property 'chdir' does not exist on type 'typeof process'. node_modules/npm/test/tap/install-local-dep-cycle.js(6,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/install-man.js(7,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/install-noargs-dev.js(5,18): error TS2307: Cannot find module 'npm-registry-mock'. @@ -1492,7 +1500,6 @@ node_modules/npm/test/tap/process-logger.js(9,37): error TS2345: Argument of typ node_modules/npm/test/tap/process-logger.js(10,37): error TS2345: Argument of type '"log"' is not assignable to parameter of type 'Signals'. node_modules/npm/test/tap/progress-config.js(3,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/progress-config.js(12,29): error TS2307: Cannot find module 'require-inject'. -node_modules/npm/test/tap/progress-config.js(18,9): error TS2339: Property 'stderr' does not exist on type 'typeof process'. node_modules/npm/test/tap/prune-dev-dep-cycle.js(4,20): error TS2307: Cannot find module 'tap'. node_modules/npm/test/tap/prune-dev-dep-cycle.js(5,21): error TS2307: Cannot find module 'tacks'. node_modules/npm/test/tap/prune-dev-dep-with-bins.js(4,20): error TS2307: Cannot find module 'tap'. diff --git a/tests/baselines/reference/user/puppeteer.log b/tests/baselines/reference/user/puppeteer.log index 086229172aa..5e11f2261fc 100644 --- a/tests/baselines/reference/user/puppeteer.log +++ b/tests/baselines/reference/user/puppeteer.log @@ -27,6 +27,8 @@ lib/FrameManager.js(127,15): error TS2503: Cannot find namespace 'Protocol'. lib/FrameManager.js(685,57): error TS2345: Argument of type 'string | number | Function' is not assignable to parameter of type 'number'. Type 'string' is not assignable to type 'number'. lib/FrameManager.js(773,15): error TS2503: Cannot find namespace 'Protocol'. +lib/Launcher.js(160,105): error TS2733: Index '3' is out-of-bounds in tuple of length 3. +lib/Launcher.js(160,169): error TS2733: Index '4' is out-of-bounds in tuple of length 3. lib/NetworkManager.js(129,15): error TS2503: Cannot find namespace 'Protocol'. lib/NetworkManager.js(174,15): error TS2503: Cannot find namespace 'Protocol'. lib/NetworkManager.js(207,15): error TS2503: Cannot find namespace 'Protocol'. @@ -52,7 +54,6 @@ lib/Page.js(935,3): error TS2322: Type '{ width: number; height: number; }' is n lib/Page.js(936,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. lib/Page.js(937,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. lib/Page.js(938,3): error TS2322: Type '{ width: number; height: number; }' is not assignable to type 'string'. -lib/externs.d.ts(2,30): error TS2497: Module '"/puppeteer/puppeteer/lib/Browser"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(3,29): error TS2497: Module '"/puppeteer/puppeteer/lib/Target"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(5,32): error TS2497: Module '"/puppeteer/puppeteer/lib/TaskQueue"' resolves to a non-module entity and cannot be imported using this construct. lib/externs.d.ts(9,37): error TS2497: Module '"/puppeteer/puppeteer/lib/ElementHandle"' resolves to a non-module entity and cannot be imported using this construct. diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 2ba94206d96..b34f83e350a 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -4,6 +4,10 @@ node_modules/uglify-js/lib/ast.js(207,23): error TS2554: Expected 0 arguments, b node_modules/uglify-js/lib/ast.js(328,33): error TS2339: Property 'transform' does not exist on type 'string'. node_modules/uglify-js/lib/ast.js(869,5): error TS2322: Type '{ _visit: (node: any, descend: any) => any; parent: (n: any) => any; push: typeof push; pop: typeof pop; self: () => any; find_parent: (type: any) => any; has_directive: (type: any) => any; loopcontrol_target: (node: any) => any; in_boolean_context: () => boolean | undefined; }' is not assignable to type 'TreeWalker'. Object literal may only specify known properties, but '_visit' does not exist in type 'TreeWalker'. Did you mean to write 'visit'? +node_modules/uglify-js/lib/ast.js(870,14): error TS2339: Property 'push' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(877,14): error TS2339: Property 'pop' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(932,25): error TS2339: Property 'self' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(933,37): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. node_modules/uglify-js/lib/compress.js(167,27): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(500,26): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(817,18): error TS2554: Expected 0 arguments, but got 1. From 228858f36c04bdfaab4303a4a826791a6e2b7cae Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 10 Sep 2018 15:46:33 -0700 Subject: [PATCH 076/146] Inline builder context instead of it being outside for easier access and resetting --- src/compiler/tsbuild.ts | 271 +++++++++++++++++++--------------------- 1 file changed, 127 insertions(+), 144 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 55af0080983..fd0f7350abe 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -11,38 +11,6 @@ namespace ts { message(diag: DiagnosticMessage, ...args: string[]): void; } - /** - * A BuildContext tracks what's going on during the course of a build. - * - * Callers may invoke any number of build requests within the same context; - * until the context is reset, each project will only be built at most once. - * - * Example: In a standard setup where project B depends on project A, and both are out of date, - * a failed build of A will result in A remaining out of date. When we try to build - * B, we should immediately bail instead of recomputing A's up-to-date status again. - * - * This also matters for performing fast (i.e. fake) downstream builds of projects - * when their upstream .d.ts files haven't changed content (but have newer timestamps) - */ - export interface BuildContext { - options: BuildOptions; - /** - * Map from output file name to its pre-build timestamp - */ - unchangedOutputs: FileMap; - - /** - * Map from config file name to up-to-date status - */ - projectStatus: ConfigFileMap; - diagnostics?: ConfigFileMap; // TODO(shkamat): this should be really be diagnostics but thats for later time - - invalidateProject(project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel | undefined, dependencyGraph: DependencyGraph | undefined): void; - getNextInvalidatedProject(): { project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel } | undefined; - hasPendingInvalidatedProjects(): boolean; - missingRoots: Map; - } - type Mapper = ReturnType; interface DependencyGraph { buildQueue: ResolvedConfigFileName[]; @@ -196,6 +164,7 @@ namespace ts { removeKey(fileName: U): void; forEach(action: (value: T, key: V) => void): void; getSize(): number; + clear(): void; } type ResolvedConfigFilePath = ResolvedConfigFileName & Path; @@ -218,7 +187,8 @@ namespace ts { removeKey, forEach, hasKey, - getSize + getSize, + clear }; function forEach(action: (value: T, key: V) => void) { @@ -244,6 +214,10 @@ namespace ts { function getSize() { return lookup.size; } + + function clear() { + lookup.clear(); + } } function createDependencyMapper(toPath: ToResolvedConfigFilePath) { @@ -341,7 +315,6 @@ namespace ts { return opts.rootDir || getDirectoryPath(configFileName); } - function newer(date1: Date, date2: Date): Date { return date2 > date1 ? date2 : date1; } @@ -350,76 +323,6 @@ namespace ts { return fileExtensionIs(fileName, Extension.Dts); } - export function createBuildContext(options: BuildOptions, toPath: ToResolvedConfigFilePath): BuildContext { - const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; - let nextIndex = 0; - const projectPendingBuild = createFileMap(toPath); - const missingRoots = createMap(); - const diagnostics = options.watch ? createFileMap(toPath) : undefined; - - return { - options, - projectStatus: createFileMap(toPath), - diagnostics, - unchangedOutputs: createFileMap(toPath as ToPath), - invalidateProject, - getNextInvalidatedProject, - hasPendingInvalidatedProjects, - missingRoots - }; - - function invalidateProject(proj: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel | undefined, dependencyGraph: DependencyGraph | undefined) { - if (addProjToQueue(proj, reloadLevel) && dependencyGraph) { - queueBuildForDownstreamReferences(proj, dependencyGraph); - } - } - - /** - * return true if new addition - */ - function addProjToQueue(proj: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { - const value = projectPendingBuild.getValue(proj); - if (value === undefined) { - projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); - invalidatedProjectQueue.push(proj); - return true; - } - - if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { - projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); - } - } - - function getNextInvalidatedProject() { - if (nextIndex < invalidatedProjectQueue.length) { - const project = invalidatedProjectQueue[nextIndex]; - nextIndex++; - const reloadLevel = projectPendingBuild.getValue(project)!; - projectPendingBuild.removeKey(project); - if (!projectPendingBuild.getSize()) { - invalidatedProjectQueue.length = 0; - nextIndex = 0; - } - return { project, reloadLevel }; - } - } - - function hasPendingInvalidatedProjects() { - return !!projectPendingBuild.getSize(); - } - - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root: ResolvedConfigFileName, dependencyGraph: DependencyGraph) { - const deps = dependencyGraph.dependencyMap.getReferencesTo(root); - for (const ref of deps) { - // Can skip circular references - if (addProjToQueue(ref)) { - queueBuildForDownstreamReferences(ref, dependencyGraph); - } - } - } - } - export interface SolutionBuilderHost extends CompilerHost { getModifiedTime(fileName: string): Date | undefined; setModifiedTime(fileName: string, date: Date): void; @@ -475,12 +378,27 @@ namespace ts { const currentDirectory = host.getCurrentDirectory(); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); const parseConfigFileHost = parseConfigHostFromCompilerHost(host); + + // State of the solution + let options = defaultOptions; type ConfigFileCacheEntry = ParsedCommandLine | Diagnostic; const configFileCache = createFileMap(toPath); - let context = createBuildContext(defaultOptions, toPath); + /** Map from output file name to its pre-build timestamp */ + const unchangedOutputs = createFileMap(toPath as ToPath); + /** Map from config file name to up-to-date status */ + const projectStatus = createFileMap(toPath); + const missingRoots = createMap(); + + // Watch state + // TODO(shkamat): this should be really be diagnostics but thats for later time + const diagnostics = createFileMap(toPath); + const projectPendingBuild = createFileMap(toPath); + const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; + let nextProjectToBuild = 0; let timerToBuildInvalidatedProject: any; let reportFileChangeDetected = false; + // Watches for the solution const existingWatchersForWildcards = createFileMap>(toPath); return { @@ -505,6 +423,25 @@ namespace ts { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } + function resetBuildContext(opts = defaultOptions) { + options = opts; + configFileCache.clear(); + unchangedOutputs.clear(); + projectStatus.clear(); + missingRoots.clear(); + + diagnostics.clear(); + projectPendingBuild.clear(); + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + if (timerToBuildInvalidatedProject) { + clearTimeout(timerToBuildInvalidatedProject); + timerToBuildInvalidatedProject = undefined; + } + reportFileChangeDetected = false; + existingWatchersForWildcards.forEach(wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf)); + } + function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine { return !!(entry as ParsedCommandLine).options; } @@ -528,20 +465,20 @@ namespace ts { } function storeErrors(proj: ResolvedConfigFileName, diagnostics: ReadonlyArray) { - if (context.options.watch) { + if (options.watch) { storeErrorSummary(proj, diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); } } function storeErrorSummary(proj: ResolvedConfigFileName, errorCount: number) { - if (context.options.watch) { - context.diagnostics!.setValue(proj, errorCount); + if (options.watch) { + diagnostics.setValue(proj, errorCount); } } function reportWatchStatus(message: DiagnosticMessage, ...args: (string | number | undefined)[]) { if (hostWithWatch.onWatchStatusChange) { - hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: context.options.preserveWatchOutput }); + hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: options.preserveWatchOutput }); } } @@ -636,10 +573,6 @@ namespace ts { scheduleBuildInvalidatedProject(); } - function resetBuildContext(opts = defaultOptions) { - context = createBuildContext(opts, toPath); - } - function getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus { return getUpToDateStatus(parseConfigFile(configFileName)); } @@ -660,13 +593,13 @@ namespace ts { return { type: UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" }; } - const prior = context.projectStatus.getValue(project.options.configFilePath as ResolvedConfigFilePath); + const prior = projectStatus.getValue(project.options.configFilePath as ResolvedConfigFilePath); if (prior !== undefined) { return prior; } const actual = getUpToDateStatusWorker(project); - context.projectStatus.setValue(project.options.configFilePath as ResolvedConfigFilePath, actual); + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFilePath, actual); return actual; } @@ -737,7 +670,7 @@ namespace ts { // had its file touched but not had its contents changed - this allows us // to skip a downstream typecheck if (isDeclarationFile(output)) { - const unchangedTime = context.unchangedOutputs.getValue(output); + const unchangedTime = unchangedOutputs.getValue(output); if (unchangedTime !== undefined) { newestDeclarationFileContentChangedTime = newer(unchangedTime, newestDeclarationFileContentChangedTime); } @@ -843,12 +776,62 @@ namespace ts { return; } - context.projectStatus.removeKey(resolved); - if (context.options.watch) { - context.diagnostics!.removeKey(resolved); + projectStatus.removeKey(resolved); + if (options.watch) { + diagnostics.removeKey(resolved); } - context.invalidateProject(resolved, reloadLevel, getGlobalDependencyGraph()); + if (addProjToQueue(resolved, reloadLevel)) { + const dependencyGraph = getGlobalDependencyGraph(); + if (dependencyGraph) { + queueBuildForDownstreamReferences(resolved, dependencyGraph); + } + } + } + + /** + * return true if new addition + */ + function addProjToQueue(proj: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + const value = projectPendingBuild.getValue(proj); + if (value === undefined) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + invalidatedProjectQueue.push(proj); + return true; + } + + if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { + projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); + } + } + + function getNextInvalidatedProject() { + if (nextProjectToBuild < invalidatedProjectQueue.length) { + const project = invalidatedProjectQueue[nextProjectToBuild]; + nextProjectToBuild++; + const reloadLevel = projectPendingBuild.getValue(project)!; + projectPendingBuild.removeKey(project); + if (!projectPendingBuild.getSize()) { + invalidatedProjectQueue.length = 0; + nextProjectToBuild = 0; + } + return { project, reloadLevel }; + } + } + + function hasPendingInvalidatedProjects() { + return !!projectPendingBuild.getSize(); + } + + // Mark all downstream projects of this one needing to be built "later" + function queueBuildForDownstreamReferences(root: ResolvedConfigFileName, dependencyGraph: DependencyGraph) { + const deps = dependencyGraph.dependencyMap.getReferencesTo(root); + for (const ref of deps) { + // Can skip circular references + if (addProjToQueue(ref)) { + queueBuildForDownstreamReferences(ref, dependencyGraph); + } + } } function scheduleBuildInvalidatedProject() { @@ -867,10 +850,10 @@ namespace ts { reportFileChangeDetected = false; reportWatchStatus(Diagnostics.File_change_detected_Starting_incremental_compilation); } - const buildProject = context.getNextInvalidatedProject(); + const buildProject = getNextInvalidatedProject(); if (buildProject) { buildSingleInvalidatedProject(buildProject.project, buildProject.reloadLevel); - if (context.hasPendingInvalidatedProjects()) { + if (hasPendingInvalidatedProjects()) { if (!timerToBuildInvalidatedProject) { scheduleBuildInvalidatedProject(); } @@ -882,9 +865,9 @@ namespace ts { } function reportErrorSummary() { - if (context.options.watch) { + if (options.watch) { let totalErrors = 0; - context.diagnostics!.forEach(singleProjectErrors => totalErrors += singleProjectErrors); + diagnostics.forEach(singleProjectErrors => totalErrors += singleProjectErrors); reportWatchStatus(totalErrors === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors); } } @@ -915,7 +898,7 @@ namespace ts { verboseReportProjectStatus(project, status); if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } @@ -983,12 +966,12 @@ namespace ts { } function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags { - if (context.options.dry) { + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj); return BuildResultFlags.Success; } - if (context.options.verbose) reportStatus(Diagnostics.Building_project_0, proj); + if (options.verbose) reportStatus(Diagnostics.Building_project_0, proj); let resultFlags = BuildResultFlags.None; resultFlags |= BuildResultFlags.DeclarationOutputUnchanged; @@ -999,7 +982,7 @@ namespace ts { resultFlags |= BuildResultFlags.ConfigFileErrors; host.reportDiagnostic(configFileCache.getValue(proj) as Diagnostic); storeErrorSummary(proj, 1); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } @@ -1028,7 +1011,7 @@ namespace ts { host.reportDiagnostic(diag); } storeErrors(proj, syntaxDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); return resultFlags; } @@ -1041,7 +1024,7 @@ namespace ts { host.reportDiagnostic(diag); } storeErrors(proj, declDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); return resultFlags; } } @@ -1054,7 +1037,7 @@ namespace ts { host.reportDiagnostic(diag); } storeErrors(proj, semanticDiagnostics); - context.projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); return resultFlags; } @@ -1077,7 +1060,7 @@ namespace ts { host.writeFile(fileName, content, writeBom, onError, emptyArray); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - context.unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(fileName, priorChangeTime); } }); @@ -1085,16 +1068,16 @@ namespace ts { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + projectStatus.setValue(proj, status); return resultFlags; } function updateOutputTimestamps(proj: ParsedCommandLine) { - if (context.options.dry) { + if (options.dry) { return reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath!); } - if (context.options.verbose) { + if (options.verbose) { reportStatus(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!); } @@ -1109,7 +1092,7 @@ namespace ts { host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); + projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { @@ -1158,7 +1141,7 @@ namespace ts { return ExitStatus.DiagnosticsPresent_OutputsSkipped; } - if (context.options.dry) { + if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r\n * ${f}`).join("")); return ExitStatus.Success; } @@ -1197,7 +1180,7 @@ namespace ts { } function buildAllProjects(): ExitStatus { - if (context.options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } + if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } const graph = getGlobalDependencyGraph(); if (graph === undefined) { reportErrorSummary(); @@ -1218,7 +1201,7 @@ namespace ts { verboseReportProjectStatus(next, status); const projName = proj.options.configFilePath!; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDate && !options.force) { // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1227,14 +1210,14 @@ namespace ts { continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - if (context.options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); + if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } @@ -1254,13 +1237,13 @@ namespace ts { * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph: DependencyGraph) { - if (!context.options.verbose) return; + if (!options.verbose) return; const names: string[] = []; for (const name of graph.buildQueue) { names.push(name); } - if (context.options.verbose) reportStatus(Diagnostics.Projects_in_this_build_Colon_0, names.map(s => "\r\n * " + relName(s)).join("")); + if (options.verbose) reportStatus(Diagnostics.Projects_in_this_build_Colon_0, names.map(s => "\r\n * " + relName(s)).join("")); } function relName(path: string): string { @@ -1271,7 +1254,7 @@ namespace ts { * Report the up-to-date status of a project if we're in verbose mode */ function verboseReportProjectStatus(configFileName: string, status: UpToDateStatus) { - if (!context.options.verbose) return; + if (!options.verbose) return; return formatUpToDateStatus(configFileName, status, relName, reportStatus); } } From e9c6d967f6a608eb1641e091203346ac46b49ed6 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 10 Sep 2018 16:40:33 -0700 Subject: [PATCH 077/146] Add related span pointing at missing arguments (#27013) --- src/compiler/checker.ts | 23 ++++++++++++++--- src/compiler/diagnosticMessages.json | 8 ++++++ ...yErrorRelatedSpanBindingPattern.errors.txt | 19 ++++++++++++++ .../arityErrorRelatedSpanBindingPattern.js | 19 ++++++++++++++ ...rityErrorRelatedSpanBindingPattern.symbols | 19 ++++++++++++++ .../arityErrorRelatedSpanBindingPattern.types | 25 +++++++++++++++++++ .../baselines/reference/baseCheck.errors.txt | 1 + ...dSameNameFunctionDeclarationES5.errors.txt | 3 ++- ...dSameNameFunctionDeclarationES6.errors.txt | 3 ++- ...ameFunctionDeclarationStrictES5.errors.txt | 4 ++- ...ameFunctionDeclarationStrictES6.errors.txt | 4 ++- .../reference/callWithSpread2.errors.txt | 2 ++ ...assCanExtendConstructorFunction.errors.txt | 1 + ...ssWithBaseClassButNoConstructor.errors.txt | 4 +++ .../classWithConstructors.errors.txt | 6 +++++ .../reference/cloduleTest2.errors.txt | 6 ++++- .../reference/constructorFunctions.errors.txt | 1 + ...ClassWithoutExplicitConstructor.errors.txt | 2 ++ ...lassWithoutExplicitConstructor2.errors.txt | 2 ++ ...lassWithoutExplicitConstructor3.errors.txt | 4 +++ ...llingBaseImplWithOptionalParams.errors.txt | 3 ++- ...rdReferenceForwadingConstructor.errors.txt | 1 + .../reference/functionCall11.errors.txt | 1 + .../reference/functionCall12.errors.txt | 1 + .../reference/functionCall13.errors.txt | 1 + .../reference/functionCall16.errors.txt | 1 + .../reference/functionCall17.errors.txt | 1 + .../reference/functionCall18.errors.txt | 1 + .../reference/functionCall6.errors.txt | 1 + .../reference/functionCall7.errors.txt | 1 + .../reference/functionOverloads29.errors.txt | 1 + .../reference/functionOverloads34.errors.txt | 1 + .../reference/functionOverloads37.errors.txt | 1 + .../functionParameterArityMismatch.errors.txt | 1 + ...unctionsWithOptionalParameters2.errors.txt | 1 + .../reference/genericRestArity.errors.txt | 1 + .../genericRestParameters1.errors.txt | 1 + .../genericRestParameters3.errors.txt | 1 + .../reference/iteratorSpreadInCall.errors.txt | 3 ++- .../iteratorSpreadInCall10.errors.txt | 3 ++- .../iteratorSpreadInCall2.errors.txt | 3 ++- .../iteratorSpreadInCall4.errors.txt | 3 ++- ...leFunctionParametersAsOptional2.errors.txt | 3 +++ .../jsdocTypeTagRequiredParameters.errors.txt | 3 +++ ...ortWithExportPropertyAssignment.errors.txt | 1 + .../optionalParamArgsTest.errors.txt | 8 ++++++ .../baselines/reference/overload1.errors.txt | 1 + ...loadsAndTypeArgumentArityErrors.errors.txt | 1 + .../requiredInitializedParameter1.errors.txt | 2 ++ .../restParamsWithNonRestParams.errors.txt | 1 + ...eStringsWithOverloadResolution3.errors.txt | 1 + ...ingsWithOverloadResolution3_ES6.errors.txt | 1 + .../thisTypeInFunctionsNegative.errors.txt | 5 ++++ ...eAssertionToGenericFunctionType.errors.txt | 3 ++- .../typesWithPublicConstructor.errors.txt | 1 + .../unionTypeCallSignatures.errors.txt | 11 ++++++++ .../unionTypeCallSignatures4.errors.txt | 1 + .../unionTypeConstructSignatures.errors.txt | 12 ++++++++- .../arityErrorRelatedSpanBindingPattern.ts | 7 ++++++ 59 files changed, 235 insertions(+), 15 deletions(-) create mode 100644 tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt create mode 100644 tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js create mode 100644 tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols create mode 100644 tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types create mode 100644 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ae0124616a4..90762a54f97 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19208,12 +19208,16 @@ namespace ts { let aboveArgCount = Number.POSITIVE_INFINITY; let argCount = args.length; + let closestSignature: Signature | undefined; for (const sig of signatures) { const minCount = getMinArgumentCount(sig); const maxCount = getParameterCount(sig); if (minCount < argCount && minCount > belowArgCount) belowArgCount = minCount; if (argCount < maxCount && maxCount < aboveArgCount) aboveArgCount = maxCount; - min = Math.min(min, minCount); + if (minCount < min) { + min = minCount; + closestSignature = sig; + } max = Math.max(max, maxCount); } @@ -19226,16 +19230,29 @@ namespace ts { argCount--; } + let related: DiagnosticWithLocation | undefined; + if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { + const paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; + if (paramDecl) { + related = createDiagnosticForNode( + paramDecl, + isBindingPattern(paramDecl.name) ? Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : Diagnostics.An_argument_for_0_was_not_provided, + !paramDecl.name ? argCount : !isBindingPattern(paramDecl.name) ? idText(getFirstIdentifier(paramDecl.name)) : undefined + ); + } + } if (hasRestParameter || hasSpreadArgument) { const error = hasRestParameter && hasSpreadArgument ? Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more : hasRestParameter ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : Diagnostics.Expected_0_arguments_but_got_1_or_more; - return createDiagnosticForNode(node, error, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, error, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } if (min < argCount && argCount < max) { return createDiagnosticForNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount); } - return createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + const diagnostic = createDiagnosticForNode(node, Diagnostics.Expected_0_arguments_but_got_1, paramRange, argCount); + return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node: Node, signatures: ReadonlyArray, typeArguments: NodeArray) { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4384167a4e0..7a57b89d320 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3708,6 +3708,14 @@ "category": "Message", "code": 6209 }, + "An argument for '{0}' was not provided.": { + "category": "Message", + "code": 6210 + }, + "An argument matching this binding pattern was not provided.": { + "category": "Message", + "code": 6211 + }, "Projects to reference": { "category": "Message", diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt new file mode 100644 index 00000000000..788ff30c58f --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.errors.txt @@ -0,0 +1,19 @@ +tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts(5,1): error TS2554: Expected 3 arguments, but got 2. +tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts(7,1): error TS2554: Expected 3 arguments, but got 2. + + +==== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts (2 errors) ==== + function foo(a, b, {c}): void {} + + function bar(a, b, [c]): void {} + + foo("", 0); + ~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:1:20: An argument matching this binding pattern was not provided. + + bar("", 0); + ~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6211 tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts:3:20: An argument matching this binding pattern was not provided. + \ No newline at end of file diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js new file mode 100644 index 00000000000..66f9316457d --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.js @@ -0,0 +1,19 @@ +//// [arityErrorRelatedSpanBindingPattern.ts] +function foo(a, b, {c}): void {} + +function bar(a, b, [c]): void {} + +foo("", 0); + +bar("", 0); + + +//// [arityErrorRelatedSpanBindingPattern.js] +function foo(a, b, _a) { + var c = _a.c; +} +function bar(a, b, _a) { + var c = _a[0]; +} +foo("", 0); +bar("", 0); diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols new file mode 100644 index 00000000000..f58194abaac --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts === +function foo(a, b, {c}): void {} +>foo : Symbol(foo, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 0)) +>a : Symbol(a, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 13)) +>b : Symbol(b, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 15)) +>c : Symbol(c, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 20)) + +function bar(a, b, [c]): void {} +>bar : Symbol(bar, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 32)) +>a : Symbol(a, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 13)) +>b : Symbol(b, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 15)) +>c : Symbol(c, Decl(arityErrorRelatedSpanBindingPattern.ts, 2, 20)) + +foo("", 0); +>foo : Symbol(foo, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 0)) + +bar("", 0); +>bar : Symbol(bar, Decl(arityErrorRelatedSpanBindingPattern.ts, 0, 32)) + diff --git a/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types new file mode 100644 index 00000000000..954cb537665 --- /dev/null +++ b/tests/baselines/reference/arityErrorRelatedSpanBindingPattern.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts === +function foo(a, b, {c}): void {} +>foo : (a: any, b: any, { c }: { c: any; }) => void +>a : any +>b : any +>c : any + +function bar(a, b, [c]): void {} +>bar : (a: any, b: any, [c]: [any]) => void +>a : any +>b : any +>c : any + +foo("", 0); +>foo("", 0) : void +>foo : (a: any, b: any, { c }: { c: any; }) => void +>"" : "" +>0 : 0 + +bar("", 0); +>bar("", 0) : void +>bar : (a: any, b: any, [c]: [any]) => void +>"" : "" +>0 : 0 + diff --git a/tests/baselines/reference/baseCheck.errors.txt b/tests/baselines/reference/baseCheck.errors.txt index ca99ca426fc..67358a10338 100644 --- a/tests/baselines/reference/baseCheck.errors.txt +++ b/tests/baselines/reference/baseCheck.errors.txt @@ -32,6 +32,7 @@ tests/cases/compiler/baseCheck.ts(26,9): error TS2304: Cannot find name 'x'. class D extends C { constructor(public z: number) { super(this.z) } } // too few params ~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/compiler/baseCheck.ts:1:34: An argument for 'y' was not provided. ~~~~ !!! error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. class E extends C { constructor(public z: number) { super(0, this.z) } } diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt index 77dc618f912..c9f636a7914 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES5.errors.txt @@ -34,4 +34,5 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationES5.ts:1:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt index c9a8c67296a..755bf4e9750 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationES6.errors.txt @@ -34,4 +34,5 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts(16,1): error T foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationES6.ts:1:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt index fb53f7a8f96..e8c41aea290 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES5.errors.txt @@ -31,8 +31,10 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts(17,1): e foo(); // not ok - needs number ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts:2:14: An argument for 'a' was not provided. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES5.ts:2:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt index ae2bdcf587f..fe208689c00 100644 --- a/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt +++ b/tests/baselines/reference/blockScopedSameNameFunctionDeclarationStrictES6.errors.txt @@ -25,8 +25,10 @@ tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts(17,1): e foo(); // not ok ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts:2:14: An argument for 'a' was not provided. } foo(10); foo(); // not ok - needs number ~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/blockScopedSameNameFunctionDeclarationStrictES6.ts:2:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/callWithSpread2.errors.txt b/tests/baselines/reference/callWithSpread2.errors.txt index 4333571ebf8..127bf936920 100644 --- a/tests/baselines/reference/callWithSpread2.errors.txt +++ b/tests/baselines/reference/callWithSpread2.errors.txt @@ -68,9 +68,11 @@ tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts(34,8): erro prefix(...ns) // required parameters are required ~~~~~~~~~~~~~ !!! error TS2556: Expected 1-3 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts:3:25: An argument for 's' was not provided. prefix(...mixed) ~~~~~~~~~~~~~~~~ !!! error TS2556: Expected 1-3 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithSpread2.ts:3:25: An argument for 's' was not provided. prefix(...tuple) ~~~~~~~~ !!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt b/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt index 8624160bccc..b3e2f836283 100644 --- a/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt +++ b/tests/baselines/reference/classCanExtendConstructorFunction.errors.txt @@ -42,6 +42,7 @@ tests/cases/conformance/salsa/second.ts(17,15): error TS2345: Argument of type ' super(); // error: not enough arguments ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/salsa/first.js:5:16: An argument for 'numberOxen' was not provided. this.foonly = 12 } /** diff --git a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt index da4c3a16f8b..c2ca458b7e6 100644 --- a/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt +++ b/tests/baselines/reference/classWithBaseClassButNoConstructor.errors.txt @@ -17,6 +17,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var c = new C(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts:2:17: An argument for 'x' was not provided. var c2 = new C(1); // ok class Base2 { @@ -31,6 +32,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var d = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts:14:17: An argument for 'x' was not provided. var d2 = new D(1); // ok // specialized base class @@ -42,6 +44,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var d3 = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts:14:17: An argument for 'x' was not provided. var d4 = new D(1); // ok class D3 extends Base2 { @@ -52,4 +55,5 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseCl var d5 = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithBaseClassButNoConstructor.ts:14:17: An argument for 'x' was not provided. var d6 = new D(1); // ok \ No newline at end of file diff --git a/tests/baselines/reference/classWithConstructors.errors.txt b/tests/baselines/reference/classWithConstructors.errors.txt index 870d8ef13da..0e03869e2b8 100644 --- a/tests/baselines/reference/classWithConstructors.errors.txt +++ b/tests/baselines/reference/classWithConstructors.errors.txt @@ -15,6 +15,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:3:21: An argument for 'x' was not provided. var c2 = new C(''); // ok class C2 { @@ -26,6 +27,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:10:21: An argument for 'x' was not provided. var c4 = new C2(''); // ok var c5 = new C2(1); // ok @@ -34,6 +36,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:10:21: An argument for 'x' was not provided. var d2 = new D(1); // ok var d3 = new D(''); // ok } @@ -46,6 +49,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c = new C(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:28:21: An argument for 'x' was not provided. var c2 = new C(''); // ok class C2 { @@ -57,6 +61,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var c3 = new C2(); // error ~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:35:21: An argument for 'x' was not provided. var c4 = new C2(''); // ok var c5 = new C2(1, 2); // ok @@ -65,6 +70,7 @@ tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstr var d = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/members/constructorFunctionTypes/classWithConstructors.ts:35:21: An argument for 'x' was not provided. var d2 = new D(1); // ok var d3 = new D(''); // ok } \ No newline at end of file diff --git a/tests/baselines/reference/cloduleTest2.errors.txt b/tests/baselines/reference/cloduleTest2.errors.txt index ec780ba72a2..9cc6053c1c7 100644 --- a/tests/baselines/reference/cloduleTest2.errors.txt +++ b/tests/baselines/reference/cloduleTest2.errors.txt @@ -15,6 +15,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2554: Expected 1 arguments, var r = new m3d(); // error ~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/cloduleTest2.ts:3:37: An argument for 'foo' was not provided. } module T2 { @@ -23,6 +24,7 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2554: Expected 1 arguments, var r = new m3d(); // error ~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/cloduleTest2.ts:8:37: An argument for 'foo' was not provided. } module T3 { @@ -56,8 +58,10 @@ tests/cases/compiler/cloduleTest2.ts(36,10): error TS2554: Expected 1 arguments, var r = new m3d(); // error ~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/cloduleTest2.ts:32:33: An argument for 'foo' was not provided. declare class m4d extends m3d { } var r2 = new m4d(); // error ~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/cloduleTest2.ts:32:33: An argument for 'foo' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/constructorFunctions.errors.txt b/tests/baselines/reference/constructorFunctions.errors.txt index 5ba869f25bf..1464b1a874c 100644 --- a/tests/baselines/reference/constructorFunctions.errors.txt +++ b/tests/baselines/reference/constructorFunctions.errors.txt @@ -65,4 +65,5 @@ tests/cases/conformance/salsa/index.js(55,13): error TS2554: Expected 1 argument var c7_v1 = new C7(); ~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/salsa/index.js:53:13: An argument for 'num' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt index b8fa513e289..86e444a4687 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor.errors.txt @@ -16,6 +16,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts:3:17: An argument for 'x' was not provided. var r2 = new Derived(1); class Base2 { @@ -31,4 +32,5 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor.ts:16:17: An argument for 'x' was not provided. var d2 = new D(new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt index 0bf92d51f93..cdb9ae53950 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor2.errors.txt @@ -18,6 +18,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ !!! error TS2554: Expected 1-3 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts:3:17: An argument for 'x' was not provided. var r2 = new Derived(1); var r3 = new Derived(1, 2); var r4 = new Derived(1, 2, 3); @@ -37,6 +38,7 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D(); // error ~~~~~~~ !!! error TS2554: Expected 1-3 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor2.ts:20:17: An argument for 'x' was not provided. var d2 = new D(new Date()); // ok var d3 = new D(new Date(), new Date()); var d4 = new D(new Date(), new Date(), new Date()); \ No newline at end of file diff --git a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt index 79b8cd23606..aa4cd142257 100644 --- a/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt +++ b/tests/baselines/reference/derivedClassWithoutExplicitConstructor3.errors.txt @@ -28,9 +28,11 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var r = new Derived(); // error ~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts:10:17: An argument for 'y' was not provided. var r2 = new Derived2(1); // error ~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts:10:28: An argument for 'z' was not provided. var r3 = new Derived('', ''); class Base2 { @@ -55,7 +57,9 @@ tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/de var d = new D2(); // error ~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts:32:17: An argument for 'y' was not provided. var d2 = new D2(new Date()); // error ~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/classes/constructorDeclarations/automaticConstructors/derivedClassWithoutExplicitConstructor3.ts:32:23: An argument for 'z' was not provided. var d3 = new D2(new Date(), new Date()); // ok \ No newline at end of file diff --git a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt index ba1b05944fd..3dd001eb82c 100644 --- a/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt +++ b/tests/baselines/reference/derivedTypeCallingBaseImplWithOptionalParams.errors.txt @@ -16,4 +16,5 @@ tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts(13,1): erro var y: MyClass = new MyClass(); y.myMethod(); // error ~~~~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/derivedTypeCallingBaseImplWithOptionalParams.ts:5:14: An argument for 'myList' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt index 27e8791f5d2..52ed6e94622 100644 --- a/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt +++ b/tests/baselines/reference/errorForwardReferenceForwadingConstructor.errors.txt @@ -8,6 +8,7 @@ tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts(4,14): error T var d1 = new derived(); ~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/errorForwardReferenceForwadingConstructor.ts:8:26: An argument for 'n' was not provided. var d2 = new derived(4); } diff --git a/tests/baselines/reference/functionCall11.errors.txt b/tests/baselines/reference/functionCall11.errors.txt index e7dc72b1488..9b3ab7153ce 100644 --- a/tests/baselines/reference/functionCall11.errors.txt +++ b/tests/baselines/reference/functionCall11.errors.txt @@ -10,6 +10,7 @@ tests/cases/compiler/functionCall11.ts(6,1): error TS2554: Expected 1-2 argument foo(); ~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall11.ts:1:14: An argument for 'a' was not provided. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall12.errors.txt b/tests/baselines/reference/functionCall12.errors.txt index 3c22d0dcef7..8b6c02b4804 100644 --- a/tests/baselines/reference/functionCall12.errors.txt +++ b/tests/baselines/reference/functionCall12.errors.txt @@ -10,6 +10,7 @@ tests/cases/compiler/functionCall12.ts(7,15): error TS2345: Argument of type '3' foo(); ~~~~~ !!! error TS2554: Expected 1-3 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall12.ts:1:14: An argument for 'a' was not provided. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall13.errors.txt b/tests/baselines/reference/functionCall13.errors.txt index c53f63b7d78..8e7b5ecc97a 100644 --- a/tests/baselines/reference/functionCall13.errors.txt +++ b/tests/baselines/reference/functionCall13.errors.txt @@ -9,6 +9,7 @@ tests/cases/compiler/functionCall13.ts(5,5): error TS2345: Argument of type '1' foo(); ~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall13.ts:1:14: An argument for 'a' was not provided. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall16.errors.txt b/tests/baselines/reference/functionCall16.errors.txt index b3345d82779..220e2017b67 100644 --- a/tests/baselines/reference/functionCall16.errors.txt +++ b/tests/baselines/reference/functionCall16.errors.txt @@ -13,6 +13,7 @@ tests/cases/compiler/functionCall16.ts(6,5): error TS2345: Argument of type '1' foo(); ~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall16.ts:1:14: An argument for 'a' was not provided. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall17.errors.txt b/tests/baselines/reference/functionCall17.errors.txt index c672c092677..5d1bfe98edd 100644 --- a/tests/baselines/reference/functionCall17.errors.txt +++ b/tests/baselines/reference/functionCall17.errors.txt @@ -13,6 +13,7 @@ tests/cases/compiler/functionCall17.ts(6,12): error TS2345: Argument of type '1' foo(); ~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall17.ts:1:14: An argument for 'a' was not provided. foo(1, 'bar'); ~ !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. diff --git a/tests/baselines/reference/functionCall18.errors.txt b/tests/baselines/reference/functionCall18.errors.txt index 99d7415425c..1744c76982f 100644 --- a/tests/baselines/reference/functionCall18.errors.txt +++ b/tests/baselines/reference/functionCall18.errors.txt @@ -8,4 +8,5 @@ tests/cases/compiler/functionCall18.ts(4,1): error TS2554: Expected 2 arguments, foo("hello"); ~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/compiler/functionCall18.ts:2:31: An argument for 'b' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall6.errors.txt b/tests/baselines/reference/functionCall6.errors.txt index 5200a5a3e6f..106681177d8 100644 --- a/tests/baselines/reference/functionCall6.errors.txt +++ b/tests/baselines/reference/functionCall6.errors.txt @@ -15,4 +15,5 @@ tests/cases/compiler/functionCall6.ts(5,1): error TS2554: Expected 1 arguments, foo(); ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall6.ts:1:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionCall7.errors.txt b/tests/baselines/reference/functionCall7.errors.txt index 78f2a3384db..b7e96b70159 100644 --- a/tests/baselines/reference/functionCall7.errors.txt +++ b/tests/baselines/reference/functionCall7.errors.txt @@ -17,4 +17,5 @@ tests/cases/compiler/functionCall7.ts(7,1): error TS2554: Expected 1 arguments, foo(); ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionCall7.ts:2:14: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads29.errors.txt b/tests/baselines/reference/functionOverloads29.errors.txt index 2423f53165f..908380417f9 100644 --- a/tests/baselines/reference/functionOverloads29.errors.txt +++ b/tests/baselines/reference/functionOverloads29.errors.txt @@ -8,4 +8,5 @@ tests/cases/compiler/functionOverloads29.ts(4,9): error TS2554: Expected 1 argum var x = foo(); ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionOverloads29.ts:1:14: An argument for 'bar' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads34.errors.txt b/tests/baselines/reference/functionOverloads34.errors.txt index c47eabef592..1d032b7c34d 100644 --- a/tests/baselines/reference/functionOverloads34.errors.txt +++ b/tests/baselines/reference/functionOverloads34.errors.txt @@ -8,4 +8,5 @@ tests/cases/compiler/functionOverloads34.ts(4,9): error TS2554: Expected 1 argum var x = foo(); ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionOverloads34.ts:1:14: An argument for 'bar' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads37.errors.txt b/tests/baselines/reference/functionOverloads37.errors.txt index 523c4912e80..9f0ac5ee0e5 100644 --- a/tests/baselines/reference/functionOverloads37.errors.txt +++ b/tests/baselines/reference/functionOverloads37.errors.txt @@ -8,4 +8,5 @@ tests/cases/compiler/functionOverloads37.ts(4,9): error TS2554: Expected 1 argum var x = foo(); ~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionOverloads37.ts:1:14: An argument for 'bar' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/functionParameterArityMismatch.errors.txt b/tests/baselines/reference/functionParameterArityMismatch.errors.txt index 07c9c8845c6..b547ea802df 100644 --- a/tests/baselines/reference/functionParameterArityMismatch.errors.txt +++ b/tests/baselines/reference/functionParameterArityMismatch.errors.txt @@ -13,6 +13,7 @@ tests/cases/compiler/functionParameterArityMismatch.ts(14,1): error TS2554: Expe f1(); ~~~~ !!! error TS2554: Expected 1-3 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/functionParameterArityMismatch.ts:1:21: An argument for 'a' was not provided. f1(1, 2); ~~~~~~~~ !!! error TS2575: No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments. diff --git a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt index d7dfc18d40f..c4c1ce048c2 100644 --- a/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt +++ b/tests/baselines/reference/genericFunctionsWithOptionalParameters2.errors.txt @@ -11,6 +11,7 @@ tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts(7,1): error TS25 utils.fold(); // error ~~~~~~~~~~~~ !!! error TS2554: Expected 1-3 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/genericFunctionsWithOptionalParameters2.ts:2:15: An argument for 'c' was not provided. utils.fold(null); // no error utils.fold(null, null); // no error utils.fold(null, null, null); // error: Unable to invoke type with no call signatures diff --git a/tests/baselines/reference/genericRestArity.errors.txt b/tests/baselines/reference/genericRestArity.errors.txt index 71b814e324f..eced8398ae7 100644 --- a/tests/baselines/reference/genericRestArity.errors.txt +++ b/tests/baselines/reference/genericRestArity.errors.txt @@ -12,6 +12,7 @@ tests/cases/conformance/types/rest/genericRestArity.ts(8,1): error TS2554: Expec call((x: number, y: number) => x + y); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/rest/genericRestArity.ts:5:5: An argument for 'args' was not provided. call((x: number, y: number) => x + y, 1, 2, 3, 4, 5, 6, 7); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 3 arguments, but got 8. diff --git a/tests/baselines/reference/genericRestParameters1.errors.txt b/tests/baselines/reference/genericRestParameters1.errors.txt index 6b6d7f60845..d0a09ee4638 100644 --- a/tests/baselines/reference/genericRestParameters1.errors.txt +++ b/tests/baselines/reference/genericRestParameters1.errors.txt @@ -49,6 +49,7 @@ tests/cases/conformance/types/rest/genericRestParameters1.ts(164,1): error TS232 f2(...ns, true); // Error, tuple spread only expanded when last ~~~~~~~~~~~~~~~ !!! error TS2556: Expected 3 arguments, but got 1 or more. +!!! related TS6210 tests/cases/conformance/types/rest/genericRestParameters1.ts:2:30: An argument for 'x1' was not provided. declare function f10(...args: T): T; diff --git a/tests/baselines/reference/genericRestParameters3.errors.txt b/tests/baselines/reference/genericRestParameters3.errors.txt index 1f028153397..f02446b9d22 100644 --- a/tests/baselines/reference/genericRestParameters3.errors.txt +++ b/tests/baselines/reference/genericRestParameters3.errors.txt @@ -95,6 +95,7 @@ tests/cases/conformance/types/rest/genericRestParameters3.ts(53,5): error TS2345 foo>(); // Error ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/rest/genericRestParameters3.ts:27:39: An argument for 'cb' was not provided. foo>(100); // Error ~~~ !!! error TS2345: Argument of type '100' is not assignable to parameter of type '(...args: CoolArray) => void'. diff --git a/tests/baselines/reference/iteratorSpreadInCall.errors.txt b/tests/baselines/reference/iteratorSpreadInCall.errors.txt index 93a4f4df01a..a882306ad60 100644 --- a/tests/baselines/reference/iteratorSpreadInCall.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall.errors.txt @@ -18,4 +18,5 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts(15,1): error TS2556: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2556: Expected 1 arguments, but got 0 or more. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/es6/spread/iteratorSpreadInCall.ts:1:14: An argument for 's' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt index 2012a878549..6212b53606d 100644 --- a/tests/baselines/reference/iteratorSpreadInCall10.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall10.errors.txt @@ -18,4 +18,5 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts(15,1): error TS2556 foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2556: Expected 1 arguments, but got 0 or more. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/es6/spread/iteratorSpreadInCall10.ts:1:17: An argument for 's' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt index 32559883e67..00662075451 100644 --- a/tests/baselines/reference/iteratorSpreadInCall2.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall2.errors.txt @@ -18,4 +18,5 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts(15,1): error TS2556: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2556: Expected 1 arguments, but got 0 or more. \ No newline at end of file +!!! error TS2556: Expected 1 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/es6/spread/iteratorSpreadInCall2.ts:1:14: An argument for 's' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt index 17a76cce148..03ed0e839ab 100644 --- a/tests/baselines/reference/iteratorSpreadInCall4.errors.txt +++ b/tests/baselines/reference/iteratorSpreadInCall4.errors.txt @@ -18,4 +18,5 @@ tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts(15,1): error TS2557: foo(...new SymbolIterator); ~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2557: Expected at least 1 arguments, but got 0 or more. \ No newline at end of file +!!! error TS2557: Expected at least 1 arguments, but got 0 or more. +!!! related TS6210 tests/cases/conformance/es6/spread/iteratorSpreadInCall4.ts:1:14: An argument for 's1' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt index 5a308a61b0f..dda54d6dbe3 100644 --- a/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt +++ b/tests/baselines/reference/jsFileFunctionParametersAsOptional2.errors.txt @@ -16,12 +16,15 @@ tests/cases/compiler/bar.ts(3,1): error TS2554: Expected 3 arguments, but got 2. f(); // Error ~~~ !!! error TS2554: Expected 3 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/foo.js:6:12: An argument for 'a' was not provided. f(1); // Error ~~~~ !!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/compiler/foo.js:6:15: An argument for 'b' was not provided. f(1, 2); // Error ~~~~~~~ !!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6210 tests/cases/compiler/foo.js:6:18: An argument for 'c' was not provided. f(1, 2, 3); // OK \ No newline at end of file diff --git a/tests/baselines/reference/jsdocTypeTagRequiredParameters.errors.txt b/tests/baselines/reference/jsdocTypeTagRequiredParameters.errors.txt index 4afde4e5037..3658797f87f 100644 --- a/tests/baselines/reference/jsdocTypeTagRequiredParameters.errors.txt +++ b/tests/baselines/reference/jsdocTypeTagRequiredParameters.errors.txt @@ -17,10 +17,13 @@ tests/cases/conformance/jsdoc/a.js(13,1): error TS2554: Expected 1 arguments, bu f() // should error ~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/jsdoc/a.js:1:21: An argument for '0' was not provided. g() // should error ~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/jsdoc/a.js:5:12: An argument for 's' was not provided. h() ~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/jsdoc/a.js:8:12: An argument for 's' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/moduleExportWithExportPropertyAssignment.errors.txt b/tests/baselines/reference/moduleExportWithExportPropertyAssignment.errors.txt index aab334e77f3..e40138407d8 100644 --- a/tests/baselines/reference/moduleExportWithExportPropertyAssignment.errors.txt +++ b/tests/baselines/reference/moduleExportWithExportPropertyAssignment.errors.txt @@ -8,6 +8,7 @@ tests/cases/conformance/salsa/a.js(4,1): error TS2554: Expected 1 arguments, but mod1.f() // error, not enough arguments ~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 /.src/tests/cases/conformance/salsa/mod1.js:4:30: An argument for 'a' was not provided. ==== tests/cases/conformance/salsa/requires.d.ts (0 errors) ==== declare var module: { exports: any }; diff --git a/tests/baselines/reference/optionalParamArgsTest.errors.txt b/tests/baselines/reference/optionalParamArgsTest.errors.txt index 7a3e044e6fd..4b5546260b6 100644 --- a/tests/baselines/reference/optionalParamArgsTest.errors.txt +++ b/tests/baselines/reference/optionalParamArgsTest.errors.txt @@ -139,15 +139,19 @@ tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2554: Expected 1-2 c1o1.C1M2(); ~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:23:17: An argument for 'C1M2A1' was not provided. i1o1.C1M2(); ~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:11:10: An argument for 'C1M2A1' was not provided. F2(); ~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:45:13: An argument for 'F2A1' was not provided. L2(); ~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:50:20: An argument for 'L2A1' was not provided. c1o1.C1M2(1,2); ~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 2. @@ -175,15 +179,19 @@ tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2554: Expected 1-2 c1o1.C1M4(); ~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:29:17: An argument for 'C1M4A1' was not provided. i1o1.C1M4(); ~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:13:10: An argument for 'C1M4A1' was not provided. F4(); ~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:47:13: An argument for 'F4A1' was not provided. L4(); ~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/optionalParamArgsTest.ts:52:20: An argument for 'L4A1' was not provided. function fnOpt1(id: number, children: number[] = [], expectedPath: number[] = [], isRoot?: boolean): void {} function fnOpt2(id: number, children?: number[], expectedPath?: number[], isRoot?: boolean): void {} diff --git a/tests/baselines/reference/overload1.errors.txt b/tests/baselines/reference/overload1.errors.txt index 2f118e59f64..be0df0f5af4 100644 --- a/tests/baselines/reference/overload1.errors.txt +++ b/tests/baselines/reference/overload1.errors.txt @@ -47,6 +47,7 @@ tests/cases/compiler/overload1.ts(34,9): error TS2345: Argument of type '2' is n z=x.g(); // no match ~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/overload1.ts:17:11: An argument for 'n' was not provided. z=x.g(new O.B()); // ambiguous (up and down conversion) ~ !!! error TS2322: Type 'C' is not assignable to type 'string'. diff --git a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt index 05c196377f9..1993a6d7f2c 100644 --- a/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt +++ b/tests/baselines/reference/overloadsAndTypeArgumentArityErrors.errors.txt @@ -19,4 +19,5 @@ tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts(9,1): error TS2554: f(); // wrong number of arguments (#25683) ~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/overloadsAndTypeArgumentArityErrors.ts:8:31: An argument for 'arg' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/requiredInitializedParameter1.errors.txt b/tests/baselines/reference/requiredInitializedParameter1.errors.txt index 31c0f70ee8d..f9baca7a1b5 100644 --- a/tests/baselines/reference/requiredInitializedParameter1.errors.txt +++ b/tests/baselines/reference/requiredInitializedParameter1.errors.txt @@ -16,6 +16,7 @@ tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2554: Expec f1(0, 1); ~~~~~~~~ !!! error TS2554: Expected 3 arguments, but got 2. +!!! related TS6210 tests/cases/compiler/requiredInitializedParameter1.ts:1:23: An argument for 'c' was not provided. f2(0, 1); f3(0, 1); f4(0, 1); @@ -23,6 +24,7 @@ tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2554: Expec f1(0); ~~~~~ !!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/compiler/requiredInitializedParameter1.ts:1:16: An argument for 'b' was not provided. f2(0); f3(0); f4(0); \ No newline at end of file diff --git a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt index cccbba2f4b5..5bbcf92f702 100644 --- a/tests/baselines/reference/restParamsWithNonRestParams.errors.txt +++ b/tests/baselines/reference/restParamsWithNonRestParams.errors.txt @@ -8,5 +8,6 @@ tests/cases/compiler/restParamsWithNonRestParams.ts(4,1): error TS2555: Expected foo2(); // should be an error ~~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/restParamsWithNonRestParams.ts:3:15: An argument for 'a' was not provided. function foo3(a?:string, ...b:number[]){} foo3(); // error but shouldn't be \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt index e7fb6ea1241..a3be7fbc7f7 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3.errors.txt @@ -57,6 +57,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio fn3 ``; // Error ~~~~~~ !!! error TS2554: Expected 2-4 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3.ts:28:45: An argument for 'n' was not provided. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt index 76a6186cdda..a4ba377af29 100644 --- a/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt +++ b/tests/baselines/reference/taggedTemplateStringsWithOverloadResolution3_ES6.errors.txt @@ -57,6 +57,7 @@ tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolutio fn3 ``; // Error ~~~~~~ !!! error TS2554: Expected 2-4 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/es6/templates/taggedTemplateStringsWithOverloadResolution3_ES6.ts:28:45: An argument for 'n' was not provided. // Generic overloads with constraints function fn4(strs: TemplateStringsArray, n: T, m: U); diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index e77addd5ab1..da1a8de6fd6 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -188,6 +188,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e ok.f(); // not enough arguments ~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts:61:46: An argument for 'x' was not provided. ok.f('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. @@ -208,6 +209,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e c.explicitC(); // not enough arguments ~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts:9:24: An argument for 'm' was not provided. c.explicitC('wrong type'); ~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type"' is not assignable to parameter of type 'number'. @@ -217,6 +219,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e c.explicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts:3:30: An argument for 'm' was not provided. c.explicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. @@ -226,6 +229,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e c.implicitThis(); // not enough arguments ~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts:6:18: An argument for 'm' was not provided. c.implicitThis('wrong type 2'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 2"' is not assignable to parameter of type 'number'. @@ -235,6 +239,7 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e c.explicitProperty(); // not enough arguments ~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts:12:41: An argument for 'm' was not provided. c.explicitProperty('wrong type 3'); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '"wrong type 3"' is not assignable to parameter of type 'number'. diff --git a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt index 0df5d91865d..551b863c604 100644 --- a/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt +++ b/tests/baselines/reference/typeAssertionToGenericFunctionType.errors.txt @@ -12,4 +12,5 @@ tests/cases/compiler/typeAssertionToGenericFunctionType.ts(6,1): error TS2554: E !!! error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. x.b(); // error ~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/compiler/typeAssertionToGenericFunctionType.ts:3:12: An argument for 'x' was not provided. \ No newline at end of file diff --git a/tests/baselines/reference/typesWithPublicConstructor.errors.txt b/tests/baselines/reference/typesWithPublicConstructor.errors.txt index d3b03740bf2..9aa44dea89d 100644 --- a/tests/baselines/reference/typesWithPublicConstructor.errors.txt +++ b/tests/baselines/reference/typesWithPublicConstructor.errors.txt @@ -24,4 +24,5 @@ tests/cases/conformance/types/members/typesWithPublicConstructor.ts(15,10): erro var c2 = new C2(); ~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/members/typesWithPublicConstructor.ts:11:24: An argument for 'x' was not provided. var r2: (x: number) => void = c2.constructor; \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures.errors.txt b/tests/baselines/reference/unionTypeCallSignatures.errors.txt index c123dc8da56..3f0ac662013 100644 --- a/tests/baselines/reference/unionTypeCallSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures.errors.txt @@ -56,6 +56,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:12:37: An argument for 'a' was not provided. var unionOfDifferentParameterTypes: { (a: number): number; } | { (a: string): Date; }; unionOfDifferentParameterTypes(10);// error - no call signatures @@ -72,6 +73,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:23:44: An argument for 'a' was not provided. unionOfDifferentNumberOfSignatures(10); // error - no call signatures unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -97,11 +99,13 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:33:37: An argument for 'a' was not provided. var unionWithOptionalParameter2: { (a: string, b?: number): string; } | { (a: string, b: number): number }; strOrNum = unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:39:87: An argument for 'b' was not provided. strOrNum = unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ @@ -109,6 +113,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:39:76: An argument for 'a' was not provided. var unionWithOptionalParameter3: { (a: string, b?: number): string; } | { (a: string): number; }; strOrNum = unionWithOptionalParameter3('hello'); @@ -121,6 +126,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:45:76: An argument for 'a' was not provided. var unionWithRestParameter1: { (a: string, ...b: number[]): string; } | { (a: string, ...b: number[]): number }; strOrNum = unionWithRestParameter1('hello'); @@ -132,11 +138,13 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:51:33: An argument for 'a' was not provided. var unionWithRestParameter2: { (a: string, ...b: number[]): string; } | { (a: string, b: number): number }; strOrNum = unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:58:87: An argument for 'b' was not provided. strOrNum = unionWithRestParameter2('hello', 10); // error no call signature strOrNum = unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -147,6 +155,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:58:76: An argument for 'a' was not provided. var unionWithRestParameter3: { (a: string, ...b: number[]): string; } | { (a: string): number }; strOrNum = unionWithRestParameter3('hello'); @@ -162,10 +171,12 @@ tests/cases/conformance/types/union/unionTypeCallSignatures.ts(73,12): error TS2 strOrNum = unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:65:76: An argument for 'a' was not provided. var unionWithRestParameter4: { (...a: string[]): string; } | { (a: string, b: string): number; }; strOrNum = unionWithRestParameter4("hello"); // error supplied parameters do not match any call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures.ts:72:76: An argument for 'b' was not provided. strOrNum = unionWithRestParameter4("hello", "world"); \ No newline at end of file diff --git a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt index 1d9c3d272f0..9d2ca23bbbd 100644 --- a/tests/baselines/reference/unionTypeCallSignatures4.errors.txt +++ b/tests/baselines/reference/unionTypeCallSignatures4.errors.txt @@ -34,6 +34,7 @@ tests/cases/conformance/types/union/unionTypeCallSignatures4.ts(25,1): error TS2 f12345("a"); // error ~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeCallSignatures4.ts:5:23: An argument for 'b' was not provided. f12345("a", "b"); f12345("a", "b", "c"); // error ~~~~~~~~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt index 8b4c6f9aa0c..67973c3c206 100644 --- a/tests/baselines/reference/unionTypeConstructSignatures.errors.txt +++ b/tests/baselines/reference/unionTypeConstructSignatures.errors.txt @@ -55,6 +55,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro new unionOfDifferentReturnType1(); // error missing parameter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:12:41: An argument for 'a' was not provided. var unionOfDifferentParameterTypes: { new (a: number): number; } | { new (a: string): Date; }; new unionOfDifferentParameterTypes(10);// error - no call signatures @@ -71,6 +72,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro new unionOfDifferentNumberOfSignatures(); // error - no call signatures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:23:48: An argument for 'a' was not provided. new unionOfDifferentNumberOfSignatures(10); // error - no call signatures new unionOfDifferentNumberOfSignatures("hello"); // error - no call signatures ~~~~~~~ @@ -96,11 +98,13 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1-2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:33:41: An argument for 'a' was not provided. var unionWithOptionalParameter2: { new (a: string, b?: number): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithOptionalParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:39:95: An argument for 'b' was not provided. strOrNum = new unionWithOptionalParameter2('hello', 10); // error no call signature strOrNum = new unionWithOptionalParameter2('hello', "hello"); // error no call signature ~~~~~~~ @@ -108,6 +112,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:39:84: An argument for 'a' was not provided. var unionWithOptionalParameter3: { new (a: string, b?: number): string; } | { new (a: string): number; }; strOrNum = new unionWithOptionalParameter3('hello'); // error no call signature @@ -120,6 +125,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithOptionalParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:45:84: An argument for 'a' was not provided. var unionWithRestParameter1: { new (a: string, ...b: number[]): string; } | { new (a: string, ...b: number[]): number }; strOrNum = new unionWithRestParameter1('hello'); @@ -131,11 +137,13 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithRestParameter1(); // error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2555: Expected at least 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:51:37: An argument for 'a' was not provided. var unionWithRestParameter2: { new (a: string, ...b: number[]): string; } | { new (a: string, b: number): number }; strOrNum = new unionWithRestParameter2('hello'); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:58:95: An argument for 'b' was not provided. strOrNum = new unionWithRestParameter2('hello', 10); // error no call signature strOrNum = new unionWithRestParameter2('hello', 10, 11); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -146,6 +154,7 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro strOrNum = new unionWithRestParameter2(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2554: Expected 2 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:58:84: An argument for 'a' was not provided. var unionWithRestParameter3: { new (a: string, ...b: number[]): string; } | { new (a: string): number }; strOrNum = new unionWithRestParameter3('hello'); // error no call signature @@ -160,4 +169,5 @@ tests/cases/conformance/types/union/unionTypeConstructSignatures.ts(70,12): erro !!! error TS2554: Expected 1 arguments, but got 2. strOrNum = new unionWithRestParameter3(); // error no call signature ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2554: Expected 1 arguments, but got 0. \ No newline at end of file +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/types/union/unionTypeConstructSignatures.ts:65:84: An argument for 'a' was not provided. \ No newline at end of file diff --git a/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts b/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts new file mode 100644 index 00000000000..c82b8c493cc --- /dev/null +++ b/tests/cases/compiler/arityErrorRelatedSpanBindingPattern.ts @@ -0,0 +1,7 @@ +function foo(a, b, {c}): void {} + +function bar(a, b, [c]): void {} + +foo("", 0); + +bar("", 0); From 6c57ebd00b6e84dba3059832b8a8e466aef783cf Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 10 Sep 2018 16:17:52 -0700 Subject: [PATCH 078/146] Update watches to wild card directories, input files, config files when project invalidates --- src/compiler/tsbuild.ts | 110 +++++++++++------ src/compiler/utilities.ts | 2 +- src/testRunner/unittests/tsbuildWatchMode.ts | 122 +++++++++++++------ 3 files changed, 155 insertions(+), 79 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index fd0f7350abe..9eada3eeb6f 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -399,7 +399,9 @@ namespace ts { let reportFileChangeDetected = false; // Watches for the solution - const existingWatchersForWildcards = createFileMap>(toPath); + const allWatchedWildcardDirectories = createFileMap>(toPath); + const allWatchedInputFiles = createFileMap>(toPath); + const allWatchedConfigFiles = createFileMap(toPath); return { buildAllProjects, @@ -439,7 +441,9 @@ namespace ts { timerToBuildInvalidatedProject = undefined; } reportFileChangeDetected = false; - existingWatchersForWildcards.forEach(wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf)); + clearMap(allWatchedWildcardDirectories, wildCardWatches => clearMap(wildCardWatches, closeFileWatcherOf)); + clearMap(allWatchedInputFiles, inputFileWatches => clearMap(inputFileWatches, closeFileWatcher)); + clearMap(allWatchedConfigFiles, closeFileWatcher); } function isParsedCommandLine(entry: ConfigFileCacheEntry): entry is ParsedCommandLine { @@ -493,48 +497,73 @@ namespace ts { const cfg = parseConfigFile(resolved); if (cfg) { // Watch this file - hostWithWatch.watchFile(resolved, () => { - configFileCache.removeKey(resolved); - invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); - }); + watchConfigFile(resolved); // Update watchers for wildcard directories - if (cfg.configFileSpecs) { - const existingWatches = existingWatchersForWildcards.getValue(resolved); - let newWatches: Map | undefined; - if (!existingWatches) { - newWatches = createMap(); - existingWatchersForWildcards.setValue(resolved, newWatches); - } - updateWatchingWildcardDirectories(existingWatches || newWatches!, createMapFromTemplate(cfg.configFileSpecs.wildcardDirectories), (dir, flags) => { - return hostWithWatch.watchDirectory(dir, fileOrDirectory => { - const fileOrDirectoryPath = toPath(fileOrDirectory); - if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, cfg.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); - return; - } - - if (isOutputFile(fileOrDirectory, cfg)) { - // writeLog(`${fileOrDirectory} is output file`); - return; - } - - invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial); - }, !!(flags & WatchDirectoryFlags.Recursive)); - }); - } + watchWildCardDirectories(resolved, cfg); // Watch input files - for (const input of cfg.fileNames) { - hostWithWatch.watchFile(input, () => { - invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None); - }); - } + watchInputFiles(resolved, cfg); } } } + function watchConfigFile(resolved: ResolvedConfigFileName) { + if (!allWatchedConfigFiles.hasKey(resolved)) { + allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, () => { + configFileCache.removeKey(resolved); + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); + })); + } + } + + function getOrCreateExistingWatches(resolved: ResolvedConfigFileName, allWatches: ConfigFileMap>) { + const existingWatches = allWatches.getValue(resolved); + let newWatches: Map | undefined; + if (!existingWatches) { + newWatches = createMap(); + allWatches.setValue(resolved, newWatches); + } + return existingWatches || newWatches!; + } + + function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + updateWatchingWildcardDirectories( + getOrCreateExistingWatches(resolved, allWatchedWildcardDirectories), + createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), + (dir, flags) => { + return hostWithWatch.watchDirectory(dir, fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + return; + } + + if (isOutputFile(fileOrDirectory, parsed)) { + // writeLog(`${fileOrDirectory} is output file`); + return; + } + + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Partial); + }, !!(flags & WatchDirectoryFlags.Recursive)); + } + ); + } + + function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + mutateMap( + getOrCreateExistingWatches(resolved, allWatchedInputFiles), + arrayToMap(parsed.fileNames, toPath), + { + createNewValue: (_key, input) => hostWithWatch.watchFile(input, () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None); + }), + onDeleteValue: closeFileWatcher, + } + ); + } + function isOutputFile(fileName: string, configFile: ParsedCommandLine) { if (configFile.options.noEmit) return false; @@ -879,10 +908,12 @@ namespace ts { if (!resolved) return; // ?? const proj = parseConfigFile(resolved); if (!proj) return; // ? - // TODO:: If full reload , update watch for wild cards - // TODO:: If full or partial reload, update watch for input files - - if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + watchConfigFile(resolved); + watchWildCardDirectories(resolved, proj); + watchInputFiles(resolved, proj); + } + else if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { // Update file names const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(project), proj.options, parseConfigFileHost); if (result.fileNames.length !== 0) { @@ -892,6 +923,7 @@ namespace ts { proj.errors.push(getErrorForNoInputFiles(proj.configFileSpecs!, resolved)); } proj.fileNames = result.fileNames; + watchInputFiles(resolved, proj); } const status = getUpToDateStatus(proj); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5191fe1cc47..baf45da1516 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4329,7 +4329,7 @@ namespace ts { /** * clears already present map by calling onDeleteExistingValue callback before deleting that key/value */ - export function clearMap(map: Map, onDeleteValue: (valueInMap: T, key: string) => void) { + export function clearMap(map: { forEach: Map["forEach"]; clear: Map["clear"]; }, onDeleteValue: (valueInMap: T, key: string) => void) { // Remove all map.forEach(onDeleteValue); map.clear(); diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index c9c57379ec2..bc1bc4f373d 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -62,13 +62,17 @@ namespace ts.tscWatch { return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => [f, host.getModifiedTime(f)] as OutputFileStamp); } - function getOutputFileStamps(host: WatchedSystem): OutputFileStamp[] { - return [ + function getOutputFileStamps(host: WatchedSystem, additionalFiles?: ReadonlyArray<[SubProject, string]>): OutputFileStamp[] { + const result = [ ...getOutputStamps(host, SubProject.core, "anotherModule"), ...getOutputStamps(host, SubProject.core, "index"), ...getOutputStamps(host, SubProject.logic, "index"), ...getOutputStamps(host, SubProject.tests, "index"), ]; + if (additionalFiles) { + additionalFiles.forEach(([subProject, baseFileNameWithoutExtension]) => result.push(...getOutputStamps(host, subProject, baseFileNameWithoutExtension))); + } + return result; } function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: string[]) { @@ -108,49 +112,89 @@ namespace ts.tscWatch { createSolutionInWatchMode(); }); - it("change builds changes and reports found errors message", () => { - const host = createSolutionInWatchMode(); - verifyChange(`${core[1].content} + describe("validates the changes and watched files", () => { + const newFileWithoutExtension = "newFile"; + const newFile: File = { + path: projectFilePath(SubProject.core, `${newFileWithoutExtension}.ts`), + content: `export const newFileConst = 30;` + }; + + function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { + const host = createSolutionInWatchMode(); + return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; + + function verifyChangeWithFile(fileName: string, content: string) { + const outputFileStamps = getOutputFileStamps(host, additionalFiles); + host.writeFile(fileName, content); + verifyChangeAfterTimeout(outputFileStamps); + } + + function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedTests, changedCore, [ + ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedLogic, changedTests, [ + ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function verifyWatches() { + checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); + } + } + + it("change builds changes and reports found errors message", () => { + const { host, verifyChangeWithFile, verifyChangeAfterTimeout } = createSolutionInWatchModeToVerifyChanges(); + verifyChange(`${core[1].content} export class someClass { }`); - // Another change requeues and builds it - verifyChange(core[1].content); + // Another change requeues and builds it + verifyChange(core[1].content); - // Two changes together report only single time message: File change detected. Starting incremental compilation... - const outputFileStamps = getOutputFileStamps(host); - const change1 = `${core[1].content} -export class someClass { }`; - host.writeFile(core[1].path, change1); - host.writeFile(core[1].path, `${change1} -export class someClass2 { }`); - verifyChangeAfterTimeout(outputFileStamps); - - function verifyChange(coreContent: string) { + // Two changes together report only single time message: File change detected. Starting incremental compilation... const outputFileStamps = getOutputFileStamps(host); - host.writeFile(core[1].path, coreContent); + const change1 = `${core[1].content} +export class someClass { }`; + host.writeFile(core[1].path, change1); + host.writeFile(core[1].path, `${change1} +export class someClass2 { }`); verifyChangeAfterTimeout(outputFileStamps); - } - function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { - host.checkTimeoutQueueLengthAndRun(1); // Builds core - const changedCore = getOutputFileStamps(host); - verifyChangedFiles(changedCore, outputFileStamps, [ - ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really - ...getOutputFileNames(SubProject.core, "index") - ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds tests - const changedTests = getOutputFileStamps(host); - verifyChangedFiles(changedTests, changedCore, [ - ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written - ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds logic - const changedLogic = getOutputFileStamps(host); - verifyChangedFiles(changedLogic, changedTests, [ - ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written - ]); - host.checkTimeoutQueueLength(0); - checkOutputErrorsIncremental(host, emptyArray); - } + function verifyChange(coreContent: string) { + verifyChangeWithFile(core[1].path, coreContent); + } + }); + + it("builds when new file is added, and its subsequent updates", () => { + const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; + const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); + verifyChange(newFile.content); + + // Another change requeues and builds it + verifyChange(`${newFile.content} +export class someClass2 { }`); + + function verifyChange(newFileContent: string) { + verifyChangeWithFile(newFile.path, newFileContent); + } + }); + }); // TODO: write tests reporting errors but that will have more involved work since file From 6b2ea463b2251d0452029f4b108e502d7f3030f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Tue, 11 Sep 2018 14:35:01 +0800 Subject: [PATCH 079/146] improve Diagnostics for accidentally calling type-assertion expressions --- src/compiler/checker.ts | 7 +++ src/compiler/diagnosticMessages.json | 4 ++ ...CallingTypeAssertionExpressions.errors.txt | 35 ++++++++++++++ ...dentallyCallingTypeAssertionExpressions.js | 19 ++++++++ ...llyCallingTypeAssertionExpressions.symbols | 20 ++++++++ ...tallyCallingTypeAssertionExpressions.types | 48 +++++++++++++++++++ ...dentallyCallingTypeAssertionExpressions.ts | 11 +++++ 7 files changed, 144 insertions(+) create mode 100644 tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt create mode 100644 tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js create mode 100644 tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols create mode 100644 tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types create mode 100644 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ae0124616a4..2b146e230ff 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19655,6 +19655,13 @@ namespace ts { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { + if (node.arguments.length === 1 && isTypeAssertion(first(node.arguments))) { + const text = getSourceFileOfNode(node).text; + const pos = skipTrivia(text, node.expression.end, /* stepAfterLineBreak */ true) - 1; + if (isLineBreak(text.charCodeAt(pos))) { + error(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + } + } invocationError(node, apparentType, SignatureKind.Call); } return resolveErrorCall(node); diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 4384167a4e0..399afb4ebc6 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2457,6 +2457,10 @@ "category": "Error", "code": 2733 }, + "It is highly likely that you are missing a semicolon.": { + "category": "Error", + "code": 2734 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt new file mode 100644 index 00000000000..b27c6b06d48 --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2734: It is highly likely that you are missing a semicolon. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2734: It is highly likely that you are missing a semicolon. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + +==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (6 errors) ==== + declare function foo(): string; + + foo()(1 as number).toString(); + ~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() (1 as number).toString(); + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() + ~~~~~ +!!! error TS2734: It is highly likely that you are missing a semicolon. + ~~~~~ + (1 as number).toString(); + ~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() + ~~~~~ +!!! error TS2734: It is highly likely that you are missing a semicolon. + ~~~~~~~~ + (1 as number).toString(); + ~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + \ No newline at end of file diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js new file mode 100644 index 00000000000..ff22844b48b --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js @@ -0,0 +1,19 @@ +//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.ts] +declare function foo(): string; + +foo()(1 as number).toString(); + +foo() (1 as number).toString(); + +foo() +(1 as number).toString(); + +foo() + (1 as number).toString(); + + +//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.js] +foo()(1).toString(); +foo()(1).toString(); +foo()(1).toString(); +foo()(1).toString(); diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols new file mode 100644 index 00000000000..fb49ecd070a --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols @@ -0,0 +1,20 @@ +=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === +declare function foo(): string; +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo()(1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo() (1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + +(1 as number).toString(); + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + + (1 as number).toString(); + diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types new file mode 100644 index 00000000000..a9569a9dadf --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types @@ -0,0 +1,48 @@ +=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === +declare function foo(): string; +>foo : () => string + +foo()(1 as number).toString(); +>foo()(1 as number).toString() : any +>foo()(1 as number).toString : any +>foo()(1 as number) : any +>foo() : string +>foo : () => string +>1 as number : number +>1 : 1 +>toString : any + +foo() (1 as number).toString(); +>foo() (1 as number).toString() : any +>foo() (1 as number).toString : any +>foo() (1 as number) : any +>foo() : string +>foo : () => string +>1 as number : number +>1 : 1 +>toString : any + +foo() +>foo()(1 as number).toString() : any +>foo()(1 as number).toString : any +>foo()(1 as number) : any +>foo() : string +>foo : () => string + +(1 as number).toString(); +>1 as number : number +>1 : 1 +>toString : any + +foo() +>foo() (1 as number).toString() : any +>foo() (1 as number).toString : any +>foo() (1 as number) : any +>foo() : string +>foo : () => string + + (1 as number).toString(); +>1 as number : number +>1 : 1 +>toString : any + diff --git a/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts new file mode 100644 index 00000000000..957dc5cab75 --- /dev/null +++ b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts @@ -0,0 +1,11 @@ +declare function foo(): string; + +foo()(1 as number).toString(); + +foo() (1 as number).toString(); + +foo() +(1 as number).toString(); + +foo() + (1 as number).toString(); From 66a401ae648b51e0553dcf5a208a849dadf05b83 Mon Sep 17 00:00:00 2001 From: Klaus Meinhardt Date: Tue, 11 Sep 2018 09:39:11 +0200 Subject: [PATCH 080/146] Fix FunctionType emit when only parameter has no type Fixes: #27018 --- src/compiler/emitter.ts | 3 ++- .../reference/printerApi/printsNodeCorrectly.functionTypes.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 8cb1d4f34a9..55e690f8ae8 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2818,7 +2818,8 @@ namespace ts { const parameter = singleOrUndefined(parameters); return parameter && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter - && !(isArrowFunction(parentNode) && parentNode.type) // arrow function may not have return type annotation + && isArrowFunction(parentNode) // only arrow functions may have simple arrow head + && !parentNode.type // arrow function may not have return type annotation && !some(parentNode.decorators) // parent may not have decorators && !some(parentNode.modifiers) // parent may not have modifiers && !some(parentNode.typeParameters) // parent may not have type parameters diff --git a/tests/baselines/reference/printerApi/printsNodeCorrectly.functionTypes.js b/tests/baselines/reference/printerApi/printsNodeCorrectly.functionTypes.js index 5bfda3ba7c9..10ca78d89c8 100644 --- a/tests/baselines/reference/printerApi/printsNodeCorrectly.functionTypes.js +++ b/tests/baselines/reference/printerApi/printsNodeCorrectly.functionTypes.js @@ -1 +1 @@ -[args => any, (args) => any, (...args) => any, (args?) => any, (args: any) => any, ({}) => any] \ No newline at end of file +[(args) => any, (args) => any, (...args) => any, (args?) => any, (args: any) => any, ({}) => any] \ No newline at end of file From 2cf2bbd5f77a7756e6861fd2942e68e279046b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Tue, 11 Sep 2018 16:20:38 +0800 Subject: [PATCH 081/146] improve test case and add related diagnostic --- src/compiler/checker.ts | 19 ++++++++++--------- ...CallingTypeAssertionExpressions.errors.txt | 18 +++++++++++------- ...dentallyCallingTypeAssertionExpressions.js | 4 ++++ ...llyCallingTypeAssertionExpressions.symbols | 5 +++++ ...tallyCallingTypeAssertionExpressions.types | 12 ++++++++++++ ...dentallyCallingTypeAssertionExpressions.ts | 3 +++ 6 files changed, 45 insertions(+), 16 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2b146e230ff..96e72a9e07e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -19655,14 +19655,14 @@ namespace ts { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { + let relatedInformation: DiagnosticRelatedInformation | undefined; if (node.arguments.length === 1 && isTypeAssertion(first(node.arguments))) { const text = getSourceFileOfNode(node).text; - const pos = skipTrivia(text, node.expression.end, /* stepAfterLineBreak */ true) - 1; - if (isLineBreak(text.charCodeAt(pos))) { - error(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); + if (isLineBreak(text.charCodeAt(skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) { + relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.It_is_highly_likely_that_you_are_missing_a_semicolon); } } - invocationError(node, apparentType, SignatureKind.Call); + invocationError(node, apparentType, SignatureKind.Call, relatedInformation); } return resolveErrorCall(node); } @@ -19832,11 +19832,12 @@ namespace ts { return true; } - function invocationError(node: Node, apparentType: Type, kind: SignatureKind) { - invocationErrorRecovery(apparentType, kind, error(node, kind === SignatureKind.Call - ? Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures - : Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature - , typeToString(apparentType))); + function invocationError(node: Node, apparentType: Type, kind: SignatureKind, relatedInformation?: DiagnosticRelatedInformation) { + const diagnostic = error(node, (kind === SignatureKind.Call ? + Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures : + Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature + ), typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic); } function invocationErrorRecovery(apparentType: Type, kind: SignatureKind, diagnostic: Diagnostic) { diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt index b27c6b06d48..023e40a70da 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt @@ -1,12 +1,11 @@ tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2734: It is highly likely that you are missing a semicolon. tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2734: It is highly likely that you are missing a semicolon. tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(13,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (6 errors) ==== +==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (5 errors) ==== declare function foo(): string; foo()(1 as number).toString(); @@ -19,17 +18,22 @@ tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.t foo() ~~~~~ -!!! error TS2734: It is highly likely that you are missing a semicolon. - ~~~~~ (1 as number).toString(); ~~~~~~~~~~~~~ !!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:7:1: It is highly likely that you are missing a semicolon. foo() - ~~~~~ -!!! error TS2734: It is highly likely that you are missing a semicolon. ~~~~~~~~ (1 as number).toString(); ~~~~~~~~~~~~~~~~~ !!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:10:1: It is highly likely that you are missing a semicolon. + + foo() + ~~~~~~~~ + (1).toString(); + ~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:13:1: It is highly likely that you are missing a semicolon. \ No newline at end of file diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js index ff22844b48b..877ed539e71 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js @@ -10,6 +10,9 @@ foo() foo() (1 as number).toString(); + +foo() + (1).toString(); //// [betterErrorForAccidentallyCallingTypeAssertionExpressions.js] @@ -17,3 +20,4 @@ foo()(1).toString(); foo()(1).toString(); foo()(1).toString(); foo()(1).toString(); +foo()(1).toString(); diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols index fb49ecd070a..9dc2e676937 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols @@ -18,3 +18,8 @@ foo() (1 as number).toString(); +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) + + (1).toString(); + diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types index a9569a9dadf..54564d7462c 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types +++ b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types @@ -46,3 +46,15 @@ foo() >1 : 1 >toString : any +foo() +>foo() (1).toString() : any +>foo() (1).toString : any +>foo() (1) : any +>foo() : string +>foo : () => string + + (1).toString(); +>1 : number +>1 : 1 +>toString : any + diff --git a/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts index 957dc5cab75..42c3025c8e3 100644 --- a/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts +++ b/tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts @@ -9,3 +9,6 @@ foo() foo() (1 as number).toString(); + +foo() + (1).toString(); From 8c9e8666ed6f02b5f7c29430e475cbe4a4ad4444 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 6 Sep 2018 15:53:05 -0700 Subject: [PATCH 082/146] Miscellaneous cleanup --- .../codefixes/convertToAsyncFunction.ts | 27 +++++++------------ src/services/suggestionDiagnostics.ts | 14 +++------- src/services/utilities.ts | 2 +- 3 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 76cdf471466..9d4d6f74be4 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -81,19 +81,14 @@ namespace ts.codefix { } for (const statement of returnStatements) { - if (isCallExpression(statement)) { - startTransformation(statement, statement); - } - else { - forEachChild(statement, function visit(node: Node) { - if (isCallExpression(node)) { - startTransformation(node, statement); - } - else if (!isFunctionLike(node)) { - forEachChild(node, visit); - } - }); - } + forEachChild(statement, function visit(node: Node) { + if (isCallExpression(node)) { + startTransformation(node, statement); + } + else if (!isFunctionLike(node)) { + forEachChild(node, visit); + } + }); } } @@ -344,11 +339,8 @@ namespace ts.codefix { return [createTry(tryBlock, catchClause, /* finallyBlock */ undefined) as Statement]; } - else { - return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); - } - return []; + return transformExpression(node.expression, transformer, node, argNameRes).concat(transformationBody); } function getFlagOfIdentifier(node: Identifier, constIdentifiers: Identifier[]): NodeFlags { @@ -513,6 +505,7 @@ namespace ts.codefix { name = getMapEntryIfExists(param); } } + // currently not relevant, since we don't produce a valid transformation if the argument to a promise operation is a CallExpression else if (isCallExpression(funcNode) && funcNode.arguments.length > 0 && isIdentifier(funcNode.arguments[0])) { name = { identifier: funcNode.arguments[0] as Identifier, types, numberOfAssignmentsOriginal }; } diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 167bcb6bbac..c1af35eefa8 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -141,8 +141,8 @@ namespace ts { } /** @internal */ - export function getReturnStatementsWithPromiseHandlers(node: Node): Node[] { - const returnStatements: Node[] = []; + export function getReturnStatementsWithPromiseHandlers(node: Node): ReturnStatement[] { + const returnStatements: ReturnStatement[] = []; if (isFunctionLike(node)) { forEachChild(node, visit); } @@ -155,14 +155,8 @@ namespace ts { return; } - if (isReturnStatement(child)) { - forEachChild(child, addHandlers); - } - - function addHandlers(returnChild: Node) { - if (isPromiseHandler(returnChild)) { - returnStatements.push(child as ReturnStatement); - } + if (isReturnStatement(child) && child.expression && isPromiseHandler(child.expression)) { + returnStatements.push(child); } forEachChild(child, visit); diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 1c10bc983fd..4559a88881e 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1671,7 +1671,7 @@ namespace ts { } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node) callback(node!, clone); + if (callback && node && clone) callback(node!, clone); return clone as T; } From 7466ac1cd58b102547833f2a7c0b9037c2315d2b Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 6 Sep 2018 15:53:13 -0700 Subject: [PATCH 083/146] [WIP] add test --- src/testRunner/unittests/convertToAsyncFunction.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 99788e1310e..d1655824216 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1194,6 +1194,11 @@ const [#|foo|] = function () { } `); + _testConvertToAsyncFunction("convertToAsyncFunction_catchBlockUniqueParams", ` +function [#|f|]() { + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} +`); }); From a4c87df821259ef03fd92b9993b93e10aee7fab8 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Fri, 7 Sep 2018 16:28:47 -0700 Subject: [PATCH 084/146] [WIP] Use original identifier name to count up from when renaming collisions --- src/services/codefixes/convertToAsyncFunction.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 9d4d6f74be4..97658fd3e2f 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -240,7 +240,7 @@ namespace ts.codefix { } function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifier[]): SynthIdentifier { - const numVarsSameName = allVarNames.filter(elem => elem.identifier.text === name.text).length; + const numVarsSameName = allVarNames.filter(elem => elem.symbol.name === name.text).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); return { identifier, types: [], numberOfAssignmentsOriginal }; @@ -426,7 +426,7 @@ namespace ts.codefix { if (hasPrevArgName && !shouldReturn) { const type = transformer.checker.getTypeAtLocation(func); - const returnType = getLastCallSignature(type, transformer.checker).getReturnType(); + const returnType = getLastCallSignature(type, transformer.checker)!.getReturnType(); const varDeclOrAssignment = createVariableDeclarationOrAssignment(prevArgName!, getSynthesizedDeepClone(funcBody) as Expression, transformer); prevArgName!.types.push(returnType); return varDeclOrAssignment; @@ -440,7 +440,7 @@ namespace ts.codefix { return createNodeArray([]); } - function getLastCallSignature(type: Type, checker: TypeChecker): Signature { + function getLastCallSignature(type: Type, checker: TypeChecker): Signature | undefined { const callSignatures = type && checker.getSignaturesOfType(type, SignatureKind.Call); return callSignatures && callSignatures[callSignatures.length - 1]; } From 92edc2db56693186d7acf405c279c2e1898fecb5 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Fri, 7 Sep 2018 17:04:34 -0700 Subject: [PATCH 085/146] [WIP] Record original name of renamed variable --- .../codefixes/convertToAsyncFunction.ts | 22 ++++++++++--------- ...tToAsyncFunction_catchBlockUniqueParams.js | 19 ++++++++++++++++ ...tToAsyncFunction_catchBlockUniqueParams.ts | 19 ++++++++++++++++ 3 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 97658fd3e2f..d8d6fa05d1f 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -25,15 +25,16 @@ namespace ts.codefix { numberOfAssignmentsOriginal: number; } - interface SymbolAndIdentifier { + interface SymbolAndIdentifierAndOriginalName { identifier: Identifier; symbol: Symbol; + originalName: string; } interface Transformer { checker: TypeChecker; synthNamesMap: Map; // keys are the symbol id of the identifier - allVarNames: SymbolAndIdentifier[]; + allVarNames: SymbolAndIdentifierAndOriginalName[]; setOfExpressionsToReturn: Map; // keys are the node ids of the expressions constIdentifiers: Identifier[]; originalTypeMap: Map; // keys are the node id of the identifier @@ -60,7 +61,7 @@ namespace ts.codefix { const synthNamesMap: Map = createMap(); const originalTypeMap: Map = createMap(); - const allVarNames: SymbolAndIdentifier[] = []; + const allVarNames: SymbolAndIdentifierAndOriginalName[] = []; const isInJSFile = isInJavaScriptFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); @@ -157,7 +158,7 @@ namespace ts.codefix { This function collects all existing identifier names and names of identifiers that will be created in the refactor. It then checks for any collisions and renames them through getSynthesizedDeepClone */ - function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifier[]): FunctionLikeDeclaration { + function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifierAndOriginalName[]): FunctionLikeDeclaration { const identsToRenameMap: Map = createMap(); // key is the symbol id forEachChild(nodeToRename, function visit(node: Node) { @@ -177,26 +178,27 @@ namespace ts.codefix { // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { + const name = lastCallSignature.parameters[0].name; const synthName = getNewNameIfConflict(createIdentifier(lastCallSignature.parameters[0].name), allVarNames); synthNamesMap.set(symbolIdString, synthName); - allVarNames.push({ identifier: synthName.identifier, symbol }); + allVarNames.push({ identifier: synthName.identifier, symbol, originalName: name }); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(ident => ident.identifier.text === node.text && ident.symbol !== symbol)) { + if (allVarNames.some(ident => ident.originalName === node.text && ident.symbol !== symbol)) { const newName = getNewNameIfConflict(node, allVarNames); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - allVarNames.push({ identifier: newName.identifier, symbol }); + allVarNames.push({ identifier: newName.identifier, symbol, originalName: node.text }); } else { const identifier = getSynthesizedDeepClone(node); identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { - allVarNames.push({ identifier, symbol }); + allVarNames.push({ identifier, symbol, originalName: node.text }); } } } @@ -239,8 +241,8 @@ namespace ts.codefix { } - function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifier[]): SynthIdentifier { - const numVarsSameName = allVarNames.filter(elem => elem.symbol.name === name.text).length; + function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifierAndOriginalName[]): SynthIdentifier { + const numVarsSameName = allVarNames.filter(elem => elem.originalName === name.text).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); return { identifier, types: [], numberOfAssignmentsOriginal }; diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js new file mode 100644 index 00000000000..2600adec16b --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.js @@ -0,0 +1,19 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + let x_2; + try { + const x = await Promise.resolve(); + x_2 = 1; + } + catch (x_1) { + x_2 = "a"; + } + return !!x_2; +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts new file mode 100644 index 00000000000..5c4daf076a0 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_catchBlockUniqueParams.ts @@ -0,0 +1,19 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + let x_2: string | number; + try { + const x = await Promise.resolve(); + x_2 = 1; + } + catch (x_1) { + x_2 = "a"; + } + return !!x_2; +} From 9079df1a4d3f6c67990674545079a1fa13eafc67 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Tue, 11 Sep 2018 11:09:31 -0700 Subject: [PATCH 086/146] Update baselines --- .../convertToAsyncFunction_InnerVarNameConflict.ts | 2 +- .../convertToAsyncFunction_MultipleReturns2.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts index 3570a90a0b1..119d9d408bb 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts @@ -13,5 +13,5 @@ function /*[#|*/f/*|]*/(): Promise { async function f(): Promise { const resp = await fetch("https://typescriptlang.org"); var blob = resp.blob().then(blob_1 => blob_1.byteOffset).catch(err => 'Error'); - return blob_1.toString(); + return blob_2.toString(); } diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts index 6569c1fb0ef..389faf61891 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts @@ -21,6 +21,6 @@ async function f(): Promise { } const resp = await x; var blob = resp.blob().then(blob_1 => blob_1.byteOffset).catch(err => 'Error'); - const res_1 = await fetch("https://micorosft.com"); + const res_2 = await fetch("https://micorosft.com"); return console.log("Another one!"); } From a172751bf9cf16a4652ed03f44858a73ff13bc32 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 12:56:23 -0700 Subject: [PATCH 087/146] Always resolve the config file to ResolvedConfigFile if its json, otherwise combine tsconfig.json --- src/compiler/program.ts | 13 ++-- src/compiler/tsbuild.ts | 62 ++++++------------- src/testRunner/unittests/tsbuild.ts | 2 +- src/tsc/tsc.ts | 12 +--- .../reference/api/tsserverlibrary.d.ts | 5 +- tests/baselines/reference/api/typescript.d.ts | 5 +- 6 files changed, 28 insertions(+), 71 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c24f570819e..c6cdceeb550 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2341,7 +2341,7 @@ namespace ts { function parseProjectReferenceConfigFile(ref: ProjectReference): { commandLine: ParsedCommandLine, sourceFile: SourceFile } | undefined { // The actual filename (i.e. add "/tsconfig.json" if necessary) - const refPath = resolveProjectReferencePath(host, ref); + const refPath = resolveProjectReferencePath(ref); // An absolute path pointing to the containing directory of the config file const basePath = getNormalizedAbsolutePath(getDirectoryPath(refPath), host.getCurrentDirectory()); const sourceFile = host.getSourceFile(refPath, ScriptTarget.JSON) as JsonSourceFile | undefined; @@ -2820,18 +2820,13 @@ namespace ts { }; } - export interface ResolveProjectReferencePathHost { - fileExists(fileName: string): boolean; - } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName { - if (!host.fileExists(ref.path)) { - return combinePaths(ref.path, "tsconfig.json") as ResolvedConfigFileName; - } - return ref.path as ResolvedConfigFileName; + // TODO: Does this need to be exposed + export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName { + return resolveConfigFileProjectName(ref.path); } /* @internal */ diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 599b6ddd882..54cd97644f6 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -598,7 +598,7 @@ namespace ts { function invalidateProjectAndScheduleBuilds(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { reportFileChangeDetected = true; - invalidateProject(resolved, reloadLevel); + invalidateResolvedProject(resolved, reloadLevel); scheduleBuildInvalidatedProject(); } @@ -716,7 +716,7 @@ namespace ts { if (project.projectReferences) { for (const ref of project.projectReferences) { usesPrepend = usesPrepend || !!(ref.prepend); - const resolvedRef = resolveProjectReferencePath(host, ref); + const resolvedRef = resolveProjectReferencePath(ref); const refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); // An upstream project is blocked @@ -795,16 +795,10 @@ namespace ts { } function invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel) { - const resolved = resolveProjectName(configFileName); - if (resolved === undefined) { - // If this was a rootName, we need to track it as missing. - // Otherwise we can just ignore it and have it possibly surface as an error in any downstream projects, - // if they exist - - // TODO: do those things - return; - } + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { projectStatus.removeKey(resolved); if (options.watch) { diagnostics.removeKey(resolved); @@ -901,11 +895,9 @@ namespace ts { } } - function buildSingleInvalidatedProject(project: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { + function buildSingleInvalidatedProject(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { // TODO:: handle this in better way later - const resolved = resolveProjectName(project); - if (!resolved) return; // ?? const proj = parseConfigFile(resolved); if (!proj) return; // ? if (reloadLevel === ConfigFileProgramReloadLevel.Full) { @@ -915,7 +907,7 @@ namespace ts { } else if (reloadLevel === ConfigFileProgramReloadLevel.Partial) { // Update file names - const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(project), proj.options, parseConfigFileHost); + const result = getFileNamesFromConfigSpecs(proj.configFileSpecs!, getDirectoryPath(resolved), proj.options, parseConfigFileHost); if (result.fileNames.length !== 0) { filterMutate(proj.errors, error => !isErrorNoInputFiles(error)); } @@ -927,14 +919,14 @@ namespace ts { } const status = getUpToDateStatus(proj); - verboseReportProjectStatus(project, status); + verboseReportProjectStatus(resolved, status); if (status.type === UpToDateStatusType.UpstreamBlocked) { if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } - buildSingleProject(project); + buildSingleProject(resolved); } function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined { @@ -982,10 +974,6 @@ namespace ts { if (parsed.projectReferences) { for (const ref of parsed.projectReferences) { const resolvedRefPath = resolveProjectName(ref.path); - if (resolvedRefPath === undefined) { - hadError = true; - break; - } visit(resolvedRefPath, inCircularContext || ref.circular); graph.addReference(projPath, resolvedRefPath); } @@ -1184,30 +1172,12 @@ namespace ts { return ExitStatus.Success; } - function resolveProjectName(name: string): ResolvedConfigFileName | undefined { - const fullPath = resolvePath(host.getCurrentDirectory(), name); - if (host.fileExists(fullPath)) { - return fullPath as ResolvedConfigFileName; - } - const fullPathWithTsconfig = combinePaths(fullPath, "tsconfig.json"); - if (host.fileExists(fullPathWithTsconfig)) { - return fullPathWithTsconfig as ResolvedConfigFileName; - } - // TODO(shkamat): right now this is accounted as 1 error in config file, but we need to do better - host.reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_not_found, relName(fullPath))); - return undefined; + function resolveProjectName(name: string): ResolvedConfigFileName { + return resolveConfigFileProjectName(resolvePath(host.getCurrentDirectory(), name)); } function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] | undefined { - const resolvedNames: ResolvedConfigFileName[] = []; - for (const name of configFileNames) { - const resolved = resolveProjectName(name); - if (resolved === undefined) { - return undefined; - } - resolvedNames.push(resolved); - } - return resolvedNames; + return configFileNames.map(resolveProjectName); } function buildAllProjects(): ExitStatus { @@ -1300,6 +1270,14 @@ namespace ts { } } + export function resolveConfigFileProjectName(project: string): ResolvedConfigFileName { + if (fileExtensionIs(project, Extension.Json)) { + return project as ResolvedConfigFileName; + } + + return combinePaths(project, "tsconfig.json") as ResolvedConfigFileName; + } + export function getAllProjectOutputs(project: ParsedCommandLine): ReadonlyArray { if (project.options.outFile) { return getOutFileOutputs(project); diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index 6d6f95ce19c..bb620fc776b 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -199,7 +199,7 @@ namespace ts { tick(); touch(fs, "/src/logic/index.ts"); // Because we haven't reset the build context, the builder should assume there's nothing to do right now - const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")!); + const status = builder.getUpToDateStatusOfFile(builder.resolveProjectName("/src/logic")); assert.equal(status.type, UpToDateStatusType.UpToDate, "Project should be assumed to be up-to-date"); // Rebuild this project diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index d3966071265..523fcefd88c 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -165,7 +165,7 @@ namespace ts { } function performBuild(args: string[]): number | undefined { - const { buildOptions, projects: buildProjects, errors } = parseBuildCommand(args); + const { buildOptions, projects, errors } = parseBuildCommand(args); if (errors.length > 0) { errors.forEach(reportDiagnostic); return ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -179,16 +179,6 @@ namespace ts { // Update to pretty if host supports it updateReportDiagnostic(); - const projects = mapDefined(buildProjects, project => { - const fileName = resolvePath(sys.getCurrentDirectory(), project); - const refPath = resolveProjectReferencePath(sys, { path: fileName }); - if (!sys.fileExists(refPath)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, fileName)); - return undefined; - } - return refPath; - }); - if (projects.length === 0) { printVersion(); printHelp(buildOpts, "--build "); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index a2fbf9ac944..1202a0847b6 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4182,14 +4182,11 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { - fileExists(fileName: string): boolean; - } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 6ab352033f3..18293f58e0a 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4182,14 +4182,11 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; - interface ResolveProjectReferencePathHost { - fileExists(fileName: string): boolean; - } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { From 324073a1b28a15319b0704fa0720c9a0ce3ed8b4 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 13:17:32 -0700 Subject: [PATCH 088/146] Remove dead code and rearrange code to handle resolveProjectNames always returns array of resolved config file name --- src/compiler/tsbuild.ts | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 54cd97644f6..83a2794cfc8 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -607,10 +607,7 @@ namespace ts { } function getBuildGraph(configFileNames: ReadonlyArray) { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; - - return createDependencyGraph(resolvedNames); + return createDependencyGraph(resolveProjectNames(configFileNames)); } function getGlobalDependencyGraph() { @@ -1114,12 +1111,9 @@ namespace ts { projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } - function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { - const resolvedNames: ResolvedConfigFileName[] | undefined = resolveProjectNames(configFileNames); - if (resolvedNames === undefined) return undefined; - + function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { // Get the same graph for cleaning we'd use for building - const graph = createDependencyGraph(resolvedNames); + const graph = getBuildGraph(configFileNames); if (graph === undefined) return undefined; const filesToDelete: string[] = []; @@ -1139,22 +1133,8 @@ namespace ts { return filesToDelete; } - function getAllProjectsInScope(): ReadonlyArray | undefined { - const resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) return undefined; - const graph = createDependencyGraph(resolvedNames); - if (graph === undefined) return undefined; - return graph.buildQueue; - } - function cleanAllProjects() { - const resolvedNames: ReadonlyArray | undefined = getAllProjectsInScope(); - if (resolvedNames === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - - const filesToDelete = getFilesToClean(resolvedNames); + const filesToDelete = getFilesToClean(rootNames); if (filesToDelete === undefined) { reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); return ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -1176,7 +1156,7 @@ namespace ts { return resolveConfigFileProjectName(resolvePath(host.getCurrentDirectory(), name)); } - function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] | undefined { + function resolveProjectNames(configFileNames: ReadonlyArray): ResolvedConfigFileName[] { return configFileNames.map(resolveProjectName); } From ec6c9ea00404d370058025e5861cc563278968df Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 13:32:45 -0700 Subject: [PATCH 089/146] Start shaping SolutionBuilder API --- src/compiler/tsbuild.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 83a2794cfc8..d138e43f9a1 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -335,6 +335,22 @@ namespace ts { export interface SolutionBuilderWithWatchHost extends SolutionBuilderHost, WatchHost { } + export interface SolutionBuilder { + buildAllProjects(): ExitStatus; + cleanAllProjects(): ExitStatus; + + /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; + /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; + /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph | undefined; + + /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; + /*@internal*/ buildInvalidatedProject(): void; + + /*@internal*/ resetBuildContext(opts?: BuildOptions): void; + + /*@internal*/ startWatching(): void; + } + /** * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic */ @@ -373,7 +389,7 @@ namespace ts { * TODO: use SolutionBuilderWithWatchHost => watchedSolution * use SolutionBuilderHost => Solution */ - export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions) { + export function createSolutionBuilder(host: SolutionBuilderHost, rootNames: ReadonlyArray, defaultOptions: BuildOptions): SolutionBuilder { const hostWithWatch = host as SolutionBuilderWithWatchHost; const currentDirectory = host.getCurrentDirectory(); const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); @@ -405,7 +421,6 @@ namespace ts { return { buildAllProjects, - getUpToDateStatus, getUpToDateStatusOfFile, cleanAllProjects, resetBuildContext, From 5029a61983ec80bbfa15976414b78c3aca10d8b6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 13:52:26 -0700 Subject: [PATCH 090/146] Cache global dependency graph and invalidate it only if doing full reload of the project or resetting builder context --- src/compiler/tsbuild.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index d138e43f9a1..65dfa88256f 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -404,6 +404,7 @@ namespace ts { /** Map from config file name to up-to-date status */ const projectStatus = createFileMap(toPath); const missingRoots = createMap(); + let globalDependencyGraph: DependencyGraph | false | undefined; // Watch state // TODO(shkamat): this should be really be diagnostics but thats for later time @@ -446,6 +447,7 @@ namespace ts { unchangedOutputs.clear(); projectStatus.clear(); missingRoots.clear(); + globalDependencyGraph = undefined; diagnostics.clear(); projectPendingBuild.clear(); @@ -527,7 +529,6 @@ namespace ts { function watchConfigFile(resolved: ResolvedConfigFileName) { if (!allWatchedConfigFiles.hasKey(resolved)) { allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, () => { - configFileCache.removeKey(resolved); invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); })); } @@ -626,7 +627,10 @@ namespace ts { } function getGlobalDependencyGraph() { - return getBuildGraph(rootNames); + if (globalDependencyGraph === undefined) { + globalDependencyGraph = getBuildGraph(rootNames) || false; + } + return globalDependencyGraph || undefined; } function getUpToDateStatus(project: ParsedCommandLine | undefined): UpToDateStatus { @@ -811,12 +815,17 @@ namespace ts { } function invalidateResolvedProject(resolved: ResolvedConfigFileName, reloadLevel?: ConfigFileProgramReloadLevel) { + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } projectStatus.removeKey(resolved); if (options.watch) { diagnostics.removeKey(resolved); } if (addProjToQueue(resolved, reloadLevel)) { + // TODO: instead of adding the dependent project to queue right away postpone this const dependencyGraph = getGlobalDependencyGraph(); if (dependencyGraph) { queueBuildForDownstreamReferences(resolved, dependencyGraph); @@ -1126,9 +1135,9 @@ namespace ts { projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } - function getFilesToClean(configFileNames: ReadonlyArray): string[] | undefined { + function getFilesToClean(): string[] | undefined { // Get the same graph for cleaning we'd use for building - const graph = getBuildGraph(configFileNames); + const graph = getGlobalDependencyGraph(); if (graph === undefined) return undefined; const filesToDelete: string[] = []; @@ -1149,7 +1158,7 @@ namespace ts { } function cleanAllProjects() { - const filesToDelete = getFilesToClean(rootNames); + const filesToDelete = getFilesToClean(); if (filesToDelete === undefined) { reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); return ExitStatus.DiagnosticsPresent_OutputsSkipped; From 1c1379252ea60dfab715d40c83cb238826fdc0c7 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 11 Sep 2018 14:11:31 -0700 Subject: [PATCH 091/146] Prefer elaborating on expressions which could be called to produce a correct type by suggesting such (#27016) * Prefer elaborating on expressions which could be called to produce a correct type by suggesting such * Pass relation through elaboration machinery --- src/compiler/checker.ts | 58 +++++++++---- src/compiler/diagnosticMessages.json | 8 ++ ...orExpressionsWhichCouldBeCalled.errors.txt | 51 +++++++++++ ...rationsForExpressionsWhichCouldBeCalled.js | 52 +++++++++++ ...nsForExpressionsWhichCouldBeCalled.symbols | 71 +++++++++++++++ ...ionsForExpressionsWhichCouldBeCalled.types | 86 +++++++++++++++++++ ...ctionSignatureAssignmentCompat1.errors.txt | 5 +- .../invalidAssignmentsToVoid.errors.txt | 7 +- .../reference/invalidVoidValues.errors.txt | 7 +- .../optionalParamAssignmentCompat.errors.txt | 5 +- .../reference/parser536727.errors.txt | 14 +-- ...cMemberOfAnotherClassAssignment.errors.txt | 10 ++- ...ConstrainsPropertyDeclarations2.errors.txt | 12 +-- .../baselines/reference/typeMatch1.errors.txt | 5 +- tests/baselines/reference/weakType.errors.txt | 3 + ...rationsForExpressionsWhichCouldBeCalled.ts | 27 ++++++ 16 files changed, 376 insertions(+), 45 deletions(-) create mode 100644 tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.errors.txt create mode 100644 tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js create mode 100644 tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.symbols create mode 100644 tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.types create mode 100644 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ff7306855ce..19ca10e83be 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10573,7 +10573,7 @@ namespace ts { function checkTypeRelatedToAndOptionallyElaborate(source: Type, target: Type, relation: Map, errorNode: Node | undefined, expr: Expression | undefined, headMessage?: DiagnosticMessage, containingMessageChain?: () => DiagnosticMessageChain | undefined): boolean { if (isTypeRelatedTo(source, target, relation)) return true; - if (!errorNode || !elaborateError(expr, source, target)) { + if (!errorNode || !elaborateError(expr, source, target, relation)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; @@ -10583,25 +10583,49 @@ namespace ts { return !!(type.flags & TypeFlags.Conditional || (type.flags & TypeFlags.Intersection && some((type as IntersectionType).types, isOrHasGenericConditional))); } - function elaborateError(node: Expression | undefined, source: Type, target: Type): boolean { + function elaborateError(node: Expression | undefined, source: Type, target: Type, relation: Map): boolean { if (!node || isOrHasGenericConditional(target)) return false; + if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined) && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation)) { + return true; + } switch (node.kind) { case SyntaxKind.JsxExpression: case SyntaxKind.ParenthesizedExpression: - return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target); + return elaborateError((node as ParenthesizedExpression | JsxExpression).expression, source, target, relation); case SyntaxKind.BinaryExpression: switch ((node as BinaryExpression).operatorToken.kind) { case SyntaxKind.EqualsToken: case SyntaxKind.CommaToken: - return elaborateError((node as BinaryExpression).right, source, target); + return elaborateError((node as BinaryExpression).right, source, target, relation); } break; case SyntaxKind.ObjectLiteralExpression: - return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target); + return elaborateObjectLiteral(node as ObjectLiteralExpression, source, target, relation); case SyntaxKind.ArrayLiteralExpression: - return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target); + return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target, relation); case SyntaxKind.JsxAttributes: - return elaborateJsxAttributes(node as JsxAttributes, source, target); + return elaborateJsxAttributes(node as JsxAttributes, source, target, relation); + } + return false; + } + + function elaborateDidYouMeanToCallOrConstruct(node: Expression, source: Type, target: Type, relation: Map): boolean { + const callSignatures = getSignaturesOfType(source, SignatureKind.Call); + const constructSignatures = getSignaturesOfType(source, SignatureKind.Construct); + for (const signatures of [constructSignatures, callSignatures]) { + if (some(signatures, s => { + const returnType = getReturnTypeOfSignature(s); + return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); + })) { + const resultObj: { error?: Diagnostic } = {}; + checkTypeAssignableTo(source, target, node, /*errorMessage*/ undefined, /*containingChain*/ undefined, resultObj); + const diagnostic = resultObj.error!; + addRelatedInfo(diagnostic, createDiagnosticForNode( + node, + signatures === constructSignatures ? Diagnostics.Did_you_mean_to_use_new_with_this_expression : Diagnostics.Did_you_mean_to_call_this_expression + )); + return true; + } } return false; } @@ -10612,7 +10636,7 @@ namespace ts { * If that element would issue an error, we first attempt to dive into that element's inner expression and issue a more specific error by recuring into `elaborateError` * Otherwise, we issue an error on _every_ element which fail the assignability check */ - function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type) { + function elaborateElementwise(iterator: ElaborationIterator, source: Type, target: Type, relation: Map) { // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span let reportedError = false; for (let status = iterator.next(); !status.done; status = iterator.next()) { @@ -10620,7 +10644,7 @@ namespace ts { const sourcePropType = getIndexedAccessType(source, nameType, /*accessNode*/ undefined, errorType); const targetPropType = getIndexedAccessType(target, nameType, /*accessNode*/ undefined, errorType); if (sourcePropType !== errorType && targetPropType !== errorType && !isTypeAssignableTo(sourcePropType, targetPropType)) { - const elaborated = next && elaborateError(next, sourcePropType, targetPropType); + const elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation); if (elaborated) { reportedError = true; } @@ -10629,10 +10653,10 @@ namespace ts { const resultObj: { error?: Diagnostic } = {}; // Use the expression type, if available const specificSource = next ? checkExpressionForMutableLocation(next, CheckMode.Normal, sourcePropType) : sourcePropType; - const result = checkTypeAssignableTo(specificSource, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + const result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); if (result && specificSource !== sourcePropType) { // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType - checkTypeAssignableTo(sourcePropType, targetPropType, prop, errorMessage, /*containingChain*/ undefined, resultObj); + checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, /*containingChain*/ undefined, resultObj); } if (resultObj.error) { const reportedDiag = resultObj.error; @@ -10674,8 +10698,8 @@ namespace ts { } } - function elaborateJsxAttributes(node: JsxAttributes, source: Type, target: Type) { - return elaborateElementwise(generateJsxAttributes(node), source, target); + function elaborateJsxAttributes(node: JsxAttributes, source: Type, target: Type, relation: Map) { + return elaborateElementwise(generateJsxAttributes(node), source, target, relation); } function *generateLimitedTupleElements(node: ArrayLiteralExpression, target: Type): ElaborationIterator { @@ -10691,9 +10715,9 @@ namespace ts { } } - function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type) { + function elaborateArrayLiteral(node: ArrayLiteralExpression, source: Type, target: Type, relation: Map) { if (isTupleLikeType(source)) { - return elaborateElementwise(generateLimitedTupleElements(node, target), source, target); + return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation); } return false; } @@ -10722,8 +10746,8 @@ namespace ts { } } - function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type) { - return elaborateElementwise(generateObjectLiteralElements(node), source, target); + function elaborateObjectLiteral(node: ObjectLiteralExpression, source: Type, target: Type, relation: Map) { + return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation); } /** diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 2bc47138d80..f3dec7287d5 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3720,6 +3720,14 @@ "category": "Message", "code": 6211 }, + "Did you mean to call this expression?": { + "category": "Message", + "code": 6212 + }, + "Did you mean to use `new` with this expression?": { + "category": "Message", + "code": 6213 + }, "Projects to reference": { "category": "Message", diff --git a/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.errors.txt b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.errors.txt new file mode 100644 index 00000000000..9f1f60b9d1e --- /dev/null +++ b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.errors.txt @@ -0,0 +1,51 @@ +tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(10,8): error TS2322: Type 'typeof Bar' is not assignable to type 'Bar'. + Property 'x' is missing in type 'typeof Bar'. +tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(11,8): error TS2322: Type 'DateConstructor' is not assignable to type 'Date'. + Property 'toDateString' is missing in type 'DateConstructor'. +tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(17,4): error TS2322: Type '() => number' is not assignable to type 'number'. +tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts(26,5): error TS2322: Type '() => number' is not assignable to type 'number'. + + +==== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts (4 errors) ==== + class Bar { + x!: string; + } + + declare function getNum(): number; + + declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; + + foo({ + x: Bar, + ~~~ +!!! error TS2322: Type 'typeof Bar' is not assignable to type 'Bar'. +!!! error TS2322: Property 'x' is missing in type 'typeof Bar'. +!!! related TS6213 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:10:8: Did you mean to use `new` with this expression? + y: Date + ~~~~ +!!! error TS2322: Type 'DateConstructor' is not assignable to type 'Date'. +!!! error TS2322: Property 'toDateString' is missing in type 'DateConstructor'. +!!! related TS6213 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:11:8: Did you mean to use `new` with this expression? + }, getNum()); + + foo({ + x: new Bar(), + y: new Date() + }, getNum); + ~~~~~~ +!!! error TS2322: Type '() => number' is not assignable to type 'number'. +!!! related TS6212 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:17:4: Did you mean to call this expression? + + + foo({ + x: new Bar(), + y: new Date() + }, getNum(), [ + 1, + 2, + getNum + ~~~~~~ +!!! error TS2322: Type '() => number' is not assignable to type 'number'. +!!! related TS6212 tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts:26:5: Did you mean to call this expression? + ]); + \ No newline at end of file diff --git a/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js new file mode 100644 index 00000000000..3e2aaec27a4 --- /dev/null +++ b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js @@ -0,0 +1,52 @@ +//// [didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts] +class Bar { + x!: string; +} + +declare function getNum(): number; + +declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; + +foo({ + x: Bar, + y: Date +}, getNum()); + +foo({ + x: new Bar(), + y: new Date() +}, getNum); + + +foo({ + x: new Bar(), + y: new Date() +}, getNum(), [ + 1, + 2, + getNum +]); + + +//// [didYouMeanElaborationsForExpressionsWhichCouldBeCalled.js] +var Bar = /** @class */ (function () { + function Bar() { + } + return Bar; +}()); +foo({ + x: Bar, + y: Date +}, getNum()); +foo({ + x: new Bar(), + y: new Date() +}, getNum); +foo({ + x: new Bar(), + y: new Date() +}, getNum(), [ + 1, + 2, + getNum +]); diff --git a/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.symbols b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.symbols new file mode 100644 index 00000000000..d7f6457c262 --- /dev/null +++ b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.symbols @@ -0,0 +1,71 @@ +=== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts === +class Bar { +>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0)) + + x!: string; +>x : Symbol(Bar.x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 11)) +} + +declare function getNum(): number; +>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1)) + +declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; +>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34)) +>arg : Symbol(arg, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 21)) +>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 27)) +>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0)) +>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 35)) +>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --)) +>item : Symbol(item, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 46)) +>items : Symbol(items, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 6, 60)) + +foo({ +>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34)) + + x: Bar, +>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 8, 5)) +>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0)) + + y: Date +>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 9, 11)) +>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --)) + +}, getNum()); +>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1)) + +foo({ +>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34)) + + x: new Bar(), +>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 13, 5)) +>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0)) + + y: new Date() +>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 14, 17)) +>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --)) + +}, getNum); +>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1)) + + +foo({ +>foo : Symbol(foo, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 4, 34)) + + x: new Bar(), +>x : Symbol(x, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 19, 5)) +>Bar : Symbol(Bar, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 0, 0)) + + y: new Date() +>y : Symbol(y, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 20, 17)) +>Date : Symbol(Date, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.scripthost.d.ts, --, --)) + +}, getNum(), [ +>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1)) + + 1, + 2, + getNum +>getNum : Symbol(getNum, Decl(didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts, 2, 1)) + +]); + diff --git a/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.types b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.types new file mode 100644 index 00000000000..bd60a278645 --- /dev/null +++ b/tests/baselines/reference/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.types @@ -0,0 +1,86 @@ +=== tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts === +class Bar { +>Bar : Bar + + x!: string; +>x : string +} + +declare function getNum(): number; +>getNum : () => number + +declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; +>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void +>arg : { x: Bar; y: Date; } +>x : Bar +>y : Date +>item : number +>items : [number, number, number] + +foo({ +>foo({ x: Bar, y: Date}, getNum()) : void +>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void +>{ x: Bar, y: Date} : { x: typeof Bar; y: DateConstructor; } + + x: Bar, +>x : typeof Bar +>Bar : typeof Bar + + y: Date +>y : DateConstructor +>Date : DateConstructor + +}, getNum()); +>getNum() : number +>getNum : () => number + +foo({ +>foo({ x: new Bar(), y: new Date()}, getNum) : void +>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void +>{ x: new Bar(), y: new Date()} : { x: Bar; y: Date; } + + x: new Bar(), +>x : Bar +>new Bar() : Bar +>Bar : typeof Bar + + y: new Date() +>y : Date +>new Date() : Date +>Date : DateConstructor + +}, getNum); +>getNum : () => number + + +foo({ +>foo({ x: new Bar(), y: new Date()}, getNum(), [ 1, 2, getNum]) : void +>foo : (arg: { x: Bar; y: Date; }, item: number, items?: [number, number, number]) => void +>{ x: new Bar(), y: new Date()} : { x: Bar; y: Date; } + + x: new Bar(), +>x : Bar +>new Bar() : Bar +>Bar : typeof Bar + + y: new Date() +>y : Date +>new Date() : Date +>Date : DateConstructor + +}, getNum(), [ +>getNum() : number +>getNum : () => number +>[ 1, 2, getNum] : (number | (() => number))[] + + 1, +>1 : 1 + + 2, +>2 : 2 + + getNum +>getNum : () => number + +]); + diff --git a/tests/baselines/reference/functionSignatureAssignmentCompat1.errors.txt b/tests/baselines/reference/functionSignatureAssignmentCompat1.errors.txt index f91a4f91547..bc2dc17dfbc 100644 --- a/tests/baselines/reference/functionSignatureAssignmentCompat1.errors.txt +++ b/tests/baselines/reference/functionSignatureAssignmentCompat1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,5): error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'. +tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,21): error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'. Types of parameters 'delimiter' and 'eventEmitter' are incompatible. Type 'number' is not assignable to type 'string'. @@ -14,8 +14,9 @@ tests/cases/compiler/functionSignatureAssignmentCompat1.ts(10,5): error TS2322: var parsers: Parsers; var c: ParserFunc = parsers.raw; // ok! var d: ParserFunc = parsers.readline; // not ok - ~ + ~~~~~~~~~~~~~~~~ !!! error TS2322: Type '(delimiter?: string) => ParserFunc' is not assignable to type 'ParserFunc'. !!! error TS2322: Types of parameters 'delimiter' and 'eventEmitter' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! related TS6212 tests/cases/compiler/functionSignatureAssignmentCompat1.ts:10:21: Did you mean to call this expression? var e: ParserFunc = parsers.readline(); // ok \ No newline at end of file diff --git a/tests/baselines/reference/invalidAssignmentsToVoid.errors.txt b/tests/baselines/reference/invalidAssignmentsToVoid.errors.txt index 4b9b316e010..fd3fa48c01b 100644 --- a/tests/baselines/reference/invalidAssignmentsToVoid.errors.txt +++ b/tests/baselines/reference/invalidAssignmentsToVoid.errors.txt @@ -7,7 +7,7 @@ tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(10,1): tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(14,1): error TS2322: Type 'I' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(17,1): error TS2322: Type 'typeof M' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(20,5): error TS2322: Type 'T' is not assignable to type 'void'. -tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,1): error TS2322: Type '(a: T) => void' is not assignable to type 'void'. +tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,5): error TS2322: Type '(a: T) => void' is not assignable to type 'void'. ==== tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts (10 errors) ==== @@ -51,5 +51,6 @@ tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts(22,1): !!! error TS2322: Type 'T' is not assignable to type 'void'. } x = f; - ~ -!!! error TS2322: Type '(a: T) => void' is not assignable to type 'void'. \ No newline at end of file + ~ +!!! error TS2322: Type '(a: T) => void' is not assignable to type 'void'. +!!! related TS6212 tests/cases/conformance/types/primitives/void/invalidAssignmentsToVoid.ts:22:5: Did you mean to call this expression? \ No newline at end of file diff --git a/tests/baselines/reference/invalidVoidValues.errors.txt b/tests/baselines/reference/invalidVoidValues.errors.txt index 8fc015f692f..51155152864 100644 --- a/tests/baselines/reference/invalidVoidValues.errors.txt +++ b/tests/baselines/reference/invalidVoidValues.errors.txt @@ -8,7 +8,7 @@ tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(16,1): error tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(18,1): error TS2322: Type '{ f(): void; }' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(21,1): error TS2322: Type 'typeof M' is not assignable to type 'void'. tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(24,5): error TS2322: Type 'T' is not assignable to type 'void'. -tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,1): error TS2322: Type '(a: T) => void' is not assignable to type 'void'. +tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,5): error TS2322: Type '(a: T) => void' is not assignable to type 'void'. ==== tests/cases/conformance/types/primitives/void/invalidVoidValues.ts (11 errors) ==== @@ -58,5 +58,6 @@ tests/cases/conformance/types/primitives/void/invalidVoidValues.ts(26,1): error !!! error TS2322: Type 'T' is not assignable to type 'void'. } x = f; - ~ -!!! error TS2322: Type '(a: T) => void' is not assignable to type 'void'. \ No newline at end of file + ~ +!!! error TS2322: Type '(a: T) => void' is not assignable to type 'void'. +!!! related TS6212 tests/cases/conformance/types/primitives/void/invalidVoidValues.ts:26:5: Did you mean to call this expression? \ No newline at end of file diff --git a/tests/baselines/reference/optionalParamAssignmentCompat.errors.txt b/tests/baselines/reference/optionalParamAssignmentCompat.errors.txt index 5ab492540ac..10222bc5d8f 100644 --- a/tests/baselines/reference/optionalParamAssignmentCompat.errors.txt +++ b/tests/baselines/reference/optionalParamAssignmentCompat.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/optionalParamAssignmentCompat.ts(10,5): error TS2322: Type '(p1?: string) => I1' is not assignable to type 'I1'. +tests/cases/compiler/optionalParamAssignmentCompat.ts(10,13): error TS2322: Type '(p1?: string) => I1' is not assignable to type 'I1'. Types of parameters 'p1' and 'p1' are incompatible. Type 'number' is not assignable to type 'string'. @@ -14,8 +14,9 @@ tests/cases/compiler/optionalParamAssignmentCompat.ts(10,5): error TS2322: Type var i2: I2; var c: I1 = i2.p1; // should be ok var d: I1 = i2.m1; // should error - ~ + ~~~~~ !!! error TS2322: Type '(p1?: string) => I1' is not assignable to type 'I1'. !!! error TS2322: Types of parameters 'p1' and 'p1' are incompatible. !!! error TS2322: Type 'number' is not assignable to type 'string'. +!!! related TS6212 tests/cases/compiler/optionalParamAssignmentCompat.ts:10:13: Did you mean to call this expression? \ No newline at end of file diff --git a/tests/baselines/reference/parser536727.errors.txt b/tests/baselines/reference/parser536727.errors.txt index 4204e62c93b..6cdf152582f 100644 --- a/tests/baselines/reference/parser536727.errors.txt +++ b/tests/baselines/reference/parser536727.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts(7,5): error TS2345: Argument of type '() => (x: string) => string' is not assignable to parameter of type '(x: string) => string'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts(7,5): error TS2322: Type '() => (x: string) => string' is not assignable to type '(x: string) => string'. Type '(x: string) => string' is not assignable to type 'string'. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts(8,5): error TS2345: Argument of type '() => (x: string) => string' is not assignable to parameter of type '(x: string) => string'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts(8,5): error TS2322: Type '() => (x: string) => string' is not assignable to type '(x: string) => string'. Type '(x: string) => string' is not assignable to type 'string'. @@ -13,10 +13,12 @@ tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts(8,5): foo(g); foo(() => g); ~~~~~~~ -!!! error TS2345: Argument of type '() => (x: string) => string' is not assignable to parameter of type '(x: string) => string'. -!!! error TS2345: Type '(x: string) => string' is not assignable to type 'string'. +!!! error TS2322: Type '() => (x: string) => string' is not assignable to type '(x: string) => string'. +!!! error TS2322: Type '(x: string) => string' is not assignable to type 'string'. +!!! related TS6212 tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts:7:5: Did you mean to call this expression? foo(x); ~ -!!! error TS2345: Argument of type '() => (x: string) => string' is not assignable to parameter of type '(x: string) => string'. -!!! error TS2345: Type '(x: string) => string' is not assignable to type 'string'. +!!! error TS2322: Type '() => (x: string) => string' is not assignable to type '(x: string) => string'. +!!! error TS2322: Type '(x: string) => string' is not assignable to type 'string'. +!!! related TS6212 tests/cases/conformance/parser/ecmascript5/RegressionTests/parser536727.ts:8:5: Did you mean to call this expression? \ No newline at end of file diff --git a/tests/baselines/reference/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.errors.txt b/tests/baselines/reference/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.errors.txt index 36ead708331..734ef74c218 100644 --- a/tests/baselines/reference/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.errors.txt +++ b/tests/baselines/reference/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(12,1): error TS2322: Type 'C' is not assignable to type 'A'. Property 'prop' is missing in type 'C'. -tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(13,1): error TS2322: Type 'typeof B' is not assignable to type 'A'. +tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(13,5): error TS2322: Type 'typeof B' is not assignable to type 'A'. Property 'prop' is missing in type 'typeof B'. tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(16,5): error TS2322: Type 'C' is not assignable to type 'B'. Property 'prop' is missing in type 'C'. -tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(17,1): error TS2322: Type 'typeof B' is not assignable to type 'B'. +tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts(17,5): error TS2322: Type 'typeof B' is not assignable to type 'B'. Property 'prop' is missing in type 'typeof B'. @@ -25,9 +25,10 @@ tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment. !!! error TS2322: Type 'C' is not assignable to type 'A'. !!! error TS2322: Property 'prop' is missing in type 'C'. a = B; // error prop is missing - ~ + ~ !!! error TS2322: Type 'typeof B' is not assignable to type 'A'. !!! error TS2322: Property 'prop' is missing in type 'typeof B'. +!!! related TS6213 tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts:13:5: Did you mean to use `new` with this expression? a = C; var b: B = new C(); // error prop is missing @@ -35,9 +36,10 @@ tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment. !!! error TS2322: Type 'C' is not assignable to type 'B'. !!! error TS2322: Property 'prop' is missing in type 'C'. b = B; // error prop is missing - ~ + ~ !!! error TS2322: Type 'typeof B' is not assignable to type 'B'. !!! error TS2322: Property 'prop' is missing in type 'typeof B'. +!!! related TS6213 tests/cases/compiler/staticMemberOfClassAndPublicMemberOfAnotherClassAssignment.ts:17:5: Did you mean to use `new` with this expression? b = C; b = a; diff --git a/tests/baselines/reference/stringIndexerConstrainsPropertyDeclarations2.errors.txt b/tests/baselines/reference/stringIndexerConstrainsPropertyDeclarations2.errors.txt index 3a33fe74056..511a1ef68a8 100644 --- a/tests/baselines/reference/stringIndexerConstrainsPropertyDeclarations2.errors.txt +++ b/tests/baselines/reference/stringIndexerConstrainsPropertyDeclarations2.errors.txt @@ -4,9 +4,9 @@ tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerCon tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(24,5): error TS2411: Property 'd' of type 'string' is not assignable to string index type 'A'. tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(31,5): error TS2411: Property 'c' of type 'number' is not assignable to string index type 'A'. tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(32,5): error TS2411: Property 'd' of type 'string' is not assignable to string index type 'A'. -tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(37,5): error TS2322: Type 'typeof A' is not assignable to type 'A'. +tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(37,8): error TS2322: Type 'typeof A' is not assignable to type 'A'. Property 'foo' is missing in type 'typeof A'. -tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(38,5): error TS2322: Type 'typeof B' is not assignable to type 'A'. +tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts(38,8): error TS2322: Type 'typeof B' is not assignable to type 'A'. Property 'foo' is missing in type 'typeof B'. @@ -60,13 +60,13 @@ tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerCon // error var b: { [x: string]: A } = { a: A, - ~ + ~ !!! error TS2322: Type 'typeof A' is not assignable to type 'A'. !!! error TS2322: Property 'foo' is missing in type 'typeof A'. -!!! related TS6501 tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts:36:10: The expected type comes from this index signature. +!!! related TS6213 tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts:37:8: Did you mean to use `new` with this expression? b: B - ~ + ~ !!! error TS2322: Type 'typeof B' is not assignable to type 'A'. !!! error TS2322: Property 'foo' is missing in type 'typeof B'. -!!! related TS6501 tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts:36:10: The expected type comes from this index signature. +!!! related TS6213 tests/cases/conformance/types/objectTypeLiteral/indexSignatures/stringIndexerConstrainsPropertyDeclarations2.ts:38:8: Did you mean to use `new` with this expression? } \ No newline at end of file diff --git a/tests/baselines/reference/typeMatch1.errors.txt b/tests/baselines/reference/typeMatch1.errors.txt index 7025fd0c3b2..598d9f97483 100644 --- a/tests/baselines/reference/typeMatch1.errors.txt +++ b/tests/baselines/reference/typeMatch1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/typeMatch1.ts(18,1): error TS2322: Type 'D' is not assignable to type 'C'. Types have separate declarations of a private property 'x'. -tests/cases/compiler/typeMatch1.ts(19,1): error TS2322: Type 'typeof C' is not assignable to type 'C'. +tests/cases/compiler/typeMatch1.ts(19,4): error TS2322: Type 'typeof C' is not assignable to type 'C'. Property 'x' is missing in type 'typeof C'. tests/cases/compiler/typeMatch1.ts(20,1): error TS2367: This condition will always return 'false' since the types 'typeof C' and 'typeof D' have no overlap. @@ -28,9 +28,10 @@ tests/cases/compiler/typeMatch1.ts(20,1): error TS2367: This condition will alwa !!! error TS2322: Type 'D' is not assignable to type 'C'. !!! error TS2322: Types have separate declarations of a private property 'x'. x6=C; - ~~ + ~ !!! error TS2322: Type 'typeof C' is not assignable to type 'C'. !!! error TS2322: Property 'x' is missing in type 'typeof C'. +!!! related TS6213 tests/cases/compiler/typeMatch1.ts:19:4: Did you mean to use `new` with this expression? C==D; ~~~~ !!! error TS2367: This condition will always return 'false' since the types 'typeof C' and 'typeof D' have no overlap. diff --git a/tests/baselines/reference/weakType.errors.txt b/tests/baselines/reference/weakType.errors.txt index ffc1d237593..869f60cd924 100644 --- a/tests/baselines/reference/weakType.errors.txt +++ b/tests/baselines/reference/weakType.errors.txt @@ -29,12 +29,15 @@ tests/cases/compiler/weakType.ts(62,5): error TS2322: Type '{ properties: { wron doSomething(getDefaultSettings); ~~~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type '() => { timeout: number; }' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6212 tests/cases/compiler/weakType.ts:15:13: Did you mean to call this expression? doSomething(() => ({ timeout: 1000 })); ~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type '() => { timeout: number; }' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6212 tests/cases/compiler/weakType.ts:16:13: Did you mean to call this expression? doSomething(null as CtorOnly); ~~~~~~~~~~~~~~~~ !!! error TS2560: Value of type 'CtorOnly' has no properties in common with type 'Settings'. Did you mean to call it? +!!! related TS6213 tests/cases/compiler/weakType.ts:17:13: Did you mean to use `new` with this expression? doSomething(12); ~~ !!! error TS2559: Type '12' has no properties in common with type 'Settings'. diff --git a/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts b/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts new file mode 100644 index 00000000000..392f3461d9a --- /dev/null +++ b/tests/cases/compiler/didYouMeanElaborationsForExpressionsWhichCouldBeCalled.ts @@ -0,0 +1,27 @@ +class Bar { + x!: string; +} + +declare function getNum(): number; + +declare function foo(arg: { x: Bar, y: Date }, item: number, items?: [number, number, number]): void; + +foo({ + x: Bar, + y: Date +}, getNum()); + +foo({ + x: new Bar(), + y: new Date() +}, getNum); + + +foo({ + x: new Bar(), + y: new Date() +}, getNum(), [ + 1, + 2, + getNum +]); From 5d79704931989a3a53adc4f4e31e7bd883809e05 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Tue, 11 Sep 2018 14:19:28 -0700 Subject: [PATCH 092/146] Sanitize module resolution logs for typesVersions entries --- src/compiler/utilities.ts | 9 +++++++++ src/harness/utils.ts | 15 +++++++++++++++ src/testRunner/compilerRunner.ts | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 5191fe1cc47..18b45d682db 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7671,6 +7671,15 @@ namespace ts { // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future // proof. const reservedCharacterPattern = /[^\w\s\/]/g; + + export function regExpEscape(text: string) { + return text.replace(reservedCharacterPattern, escapeRegExpCharacter); + } + + function escapeRegExpCharacter(match: string) { + return "\\" + match; + } + const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question]; export function hasExtension(fileName: string): boolean { diff --git a/src/harness/utils.ts b/src/harness/utils.ts index 14820f10529..5938db7d62c 100644 --- a/src/harness/utils.ts +++ b/src/harness/utils.ts @@ -7,6 +7,21 @@ namespace utils { return text !== undefined ? text.replace(testPathPrefixRegExp, (_, scheme) => scheme || (retainTrailingDirectorySeparator ? "/" : "")) : undefined!; // TODO: GH#18217 } + function createDiagnosticMessageReplacer string[]>(diagnosticMessage: ts.DiagnosticMessage, replacer: R) { + const messageParts = diagnosticMessage.message.split(/{\d+}/g); + const regExp = new RegExp(`^(?:${messageParts.map(ts.regExpEscape).join("(.*?)")})$`); + type Args = R extends (messageArgs: string[], ...args: infer A) => string[] ? A : []; + return (text: string, ...args: Args) => text.replace(regExp, (_, ...fixedArgs) => ts.formatStringFromArgs(diagnosticMessage.message, replacer(fixedArgs, ...args))); + } + + const replaceTypesVersionsMessage = createDiagnosticMessageReplacer( + ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_matches_compiler_version_1_looking_for_a_pattern_to_match_module_name_2, + ([entry, , moduleName], compilerVersion) => [entry, compilerVersion, moduleName]); + + export function sanitizeTraceResolutionLogEntry(text: string) { + return text && removeTestPathPrefixes(replaceTypesVersionsMessage(text, "3.1.0-dev")); + } + /** * Removes leading indentation from a template literal string. */ diff --git a/src/testRunner/compilerRunner.ts b/src/testRunner/compilerRunner.ts index a0af5d88f3b..bb481eca03e 100644 --- a/src/testRunner/compilerRunner.ts +++ b/src/testRunner/compilerRunner.ts @@ -208,7 +208,7 @@ class CompilerTest { public verifyModuleResolution() { if (this.options.traceResolution) { Harness.Baseline.runBaseline(this.justName.replace(/\.tsx?$/, ".trace.json"), - utils.removeTestPathPrefixes(JSON.stringify(this.result.traces, undefined, 4))); + JSON.stringify(this.result.traces.map(utils.sanitizeTraceResolutionLogEntry), undefined, 4)); } } From c8cdb8146a8a63127db55fdc6ed0f686e64b7d0e Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 14:27:25 -0700 Subject: [PATCH 093/146] Always create dependency graph and build order --- src/compiler/diagnosticMessages.json | 4 -- src/compiler/tsbuild.ts | 66 +++++++--------------------- src/testRunner/unittests/tsbuild.ts | 1 - 3 files changed, 15 insertions(+), 56 deletions(-) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 7a57b89d320..56a255bead6 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3838,10 +3838,6 @@ "category": "Error", "code": 6370 }, - "Skipping clean because not all projects could be located": { - "category": "Error", - "code": 6371 - }, "The expected type comes from property '{0}' which is declared here on type '{1}'": { "category": "Message", diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 65dfa88256f..f61ef42c7cb 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -341,7 +341,7 @@ namespace ts { /*@internal*/ resolveProjectName(name: string): ResolvedConfigFileName; /*@internal*/ getUpToDateStatusOfFile(configFileName: ResolvedConfigFileName): UpToDateStatus; - /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph | undefined; + /*@internal*/ getBuildGraph(configFileNames: ReadonlyArray): DependencyGraph; /*@internal*/ invalidateProject(configFileName: string, reloadLevel?: ConfigFileProgramReloadLevel): void; /*@internal*/ buildInvalidatedProject(): void; @@ -404,7 +404,7 @@ namespace ts { /** Map from config file name to up-to-date status */ const projectStatus = createFileMap(toPath); const missingRoots = createMap(); - let globalDependencyGraph: DependencyGraph | false | undefined; + let globalDependencyGraph: DependencyGraph | undefined; // Watch state // TODO(shkamat): this should be really be diagnostics but thats for later time @@ -504,12 +504,7 @@ namespace ts { } function startWatching() { - const graph = getGlobalDependencyGraph()!; - if (!graph.buildQueue) { - // Everything is broken - we don't even know what to watch. Give up. - return; - } - + const graph = getGlobalDependencyGraph(); for (const resolved of graph.buildQueue) { const cfg = parseConfigFile(resolved); if (cfg) { @@ -627,10 +622,7 @@ namespace ts { } function getGlobalDependencyGraph() { - if (globalDependencyGraph === undefined) { - globalDependencyGraph = getBuildGraph(rootNames) || false; - } - return globalDependencyGraph || undefined; + return globalDependencyGraph || (globalDependencyGraph = getBuildGraph(rootNames)); } function getUpToDateStatus(project: ParsedCommandLine | undefined): UpToDateStatus { @@ -826,10 +818,7 @@ namespace ts { if (addProjToQueue(resolved, reloadLevel)) { // TODO: instead of adding the dependent project to queue right away postpone this - const dependencyGraph = getGlobalDependencyGraph(); - if (dependencyGraph) { - queueBuildForDownstreamReferences(resolved, dependencyGraph); - } + queueBuildForDownstreamReferences(resolved, getGlobalDependencyGraph()); } } @@ -950,49 +939,36 @@ namespace ts { buildSingleProject(resolved); } - function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph | undefined { - const temporaryMarks: { [path: string]: true } = {}; - const permanentMarks: { [path: string]: true } = {}; + function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph { + const temporaryMarks = createFileMap(toPath); + const permanentMarks = createFileMap(toPath); const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; const graph = createDependencyMapper(toPath); - - let hadError = false; - for (const root of roots) { visit(root); } - if (hadError) { - return undefined; - } - return { buildQueue: buildOrder, - dependencyMap: graph + dependencyMap: graph, }; function visit(projPath: ResolvedConfigFileName, inCircularContext = false) { // Already visited - if (permanentMarks[projPath]) return; + if (permanentMarks.hasKey(projPath)) return; // Circular - if (temporaryMarks[projPath]) { + if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { - hadError = true; - // TODO(shkamat): Account for this error reportStatus(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); return; } } - temporaryMarks[projPath] = true; + temporaryMarks.setValue(projPath, true); circularityReportStack.push(projPath); const parsed = parseConfigFile(projPath); - if (parsed === undefined) { - hadError = true; - return; - } - if (parsed.projectReferences) { + if (parsed && parsed.projectReferences) { for (const ref of parsed.projectReferences) { const resolvedRefPath = resolveProjectName(ref.path); visit(resolvedRefPath, inCircularContext || ref.circular); @@ -1001,7 +977,7 @@ namespace ts { } circularityReportStack.pop(); - permanentMarks[projPath] = true; + permanentMarks.setValue(projPath, true); buildOrder.push(projPath); } } @@ -1135,11 +1111,9 @@ namespace ts { projectStatus.setValue(proj.options.configFilePath as ResolvedConfigFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); } - function getFilesToClean(): string[] | undefined { + function getFilesToClean(): string[] { // Get the same graph for cleaning we'd use for building const graph = getGlobalDependencyGraph(); - if (graph === undefined) return undefined; - const filesToDelete: string[] = []; for (const proj of graph.buildQueue) { const parsed = parseConfigFile(proj); @@ -1159,11 +1133,6 @@ namespace ts { function cleanAllProjects() { const filesToDelete = getFilesToClean(); - if (filesToDelete === undefined) { - reportStatus(Diagnostics.Skipping_clean_because_not_all_projects_could_be_located); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(f => `\r\n * ${f}`).join("")); return ExitStatus.Success; @@ -1187,11 +1156,6 @@ namespace ts { function buildAllProjects(): ExitStatus { if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } const graph = getGlobalDependencyGraph(); - if (graph === undefined) { - reportErrorSummary(); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; - } - const queue = graph.buildQueue; reportBuildQueue(graph); let anyFailed = false; diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index bb620fc776b..a9993aabc40 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -377,7 +377,6 @@ namespace ts { const projFileNames = rootNames.map(getProjectFileName); const graph = builder.getBuildGraph(projFileNames); - if (graph === undefined) throw new Error("Graph shouldn't be undefined"); assert.sameMembers(graph.buildQueue, expectedBuildSet.map(getProjectFileName)); From 31374d21bf8b37c0c3745365f83d91c9888be47a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 11 Sep 2018 14:42:17 -0700 Subject: [PATCH 094/146] Provide suggestions for common can-not-find-name errors (#27034) --- src/compiler/checker.ts | 39 +++++- src/compiler/diagnosticMessages.json | 24 ++++ .../reference/ES5For-ofTypeCheck10.errors.txt | 4 +- .../reference/ES5SymbolProperty2.errors.txt | 4 +- .../reference/ES5SymbolProperty6.errors.txt | 8 +- .../reference/anonymousModules.errors.txt | 12 +- .../argumentsObjectIterator02_ES5.errors.txt | 4 +- ...onflictingCommonJSES2015Exports.errors.txt | 4 +- ...torWithIncompleteTypeAnnotation.errors.txt | 14 +- ...tadataNoLibIsolatedModulesTypes.errors.txt | 4 +- .../didYouMeanSuggestionErrors.errors.txt | 88 ++++++++++++ .../reference/didYouMeanSuggestionErrors.js | 55 ++++++++ .../didYouMeanSuggestionErrors.symbols | 57 ++++++++ .../didYouMeanSuggestionErrors.types | 125 ++++++++++++++++++ .../reference/externModule.errors.txt | 4 +- .../reference/fixSignatureCaching.errors.txt | 12 +- .../reference/innerModExport1.errors.txt | 4 +- .../reference/innerModExport2.errors.txt | 4 +- .../reference/jsxAndTypeAssertion.errors.txt | 4 +- .../reference/metadataImportType.errors.txt | 4 +- ...mUsingES6FeaturesWithOnlyES5Lib.errors.txt | 20 +-- ...bolWithOutES6WellknownSymbolLib.errors.txt | 4 +- .../reference/moduleExports1.errors.txt | 8 +- .../moduleKeywordRepeatError.errors.txt | 4 +- .../noAssertForUnparseableTypedefs.errors.txt | 4 +- ...adingStaticFunctionsInFunctions.errors.txt | 12 +- .../reference/parser509534.errors.txt | 8 +- .../reference/parser509693.errors.txt | 8 +- .../reference/parser519458.errors.txt | 6 +- .../reference/parser521128.errors.txt | 4 +- .../parserCommaInTypeMemberList2.errors.txt | 4 +- .../parserES5SymbolProperty1.errors.txt | 4 +- .../parserES5SymbolProperty2.errors.txt | 4 +- .../parserES5SymbolProperty3.errors.txt | 4 +- .../parserES5SymbolProperty4.errors.txt | 4 +- .../parserES5SymbolProperty5.errors.txt | 4 +- .../parserES5SymbolProperty6.errors.txt | 4 +- .../parserES5SymbolProperty7.errors.txt | 4 +- .../parserES5SymbolProperty8.errors.txt | 4 +- .../parserES5SymbolProperty9.errors.txt | 4 +- .../parserMissingLambdaOpenBrace1.errors.txt | 4 +- .../reference/parserharness.errors.txt | 8 +- .../reference/reservedWords2.errors.txt | 8 +- .../reference/staticsInAFunction.errors.txt | 12 +- .../templateStringInModuleName.errors.txt | 8 +- .../templateStringInModuleNameES6.errors.txt | 8 +- .../reference/typecheckIfCondition.errors.txt | 8 +- .../compiler/didYouMeanSuggestionErrors.ts | 29 ++++ 48 files changed, 544 insertions(+), 133 deletions(-) create mode 100644 tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt create mode 100644 tests/baselines/reference/didYouMeanSuggestionErrors.js create mode 100644 tests/baselines/reference/didYouMeanSuggestionErrors.symbols create mode 100644 tests/baselines/reference/didYouMeanSuggestionErrors.types create mode 100644 tests/cases/compiler/didYouMeanSuggestionErrors.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 19ca10e83be..a856df2854a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1657,7 +1657,10 @@ namespace ts { } const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); if (symbol && !(symbol.flags & SymbolFlags.NamespaceModule)) { - error(errorLocation, Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, unescapeLeadingUnderscores(name)); + const message = (name === "Promise" || name === "Symbol") + ? Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later + : Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here; + error(errorLocation, message, unescapeLeadingUnderscores(name)); return true; } } @@ -2081,7 +2084,7 @@ namespace ts { const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(name) ? meaning & SymbolFlags.Value : 0); let symbol: Symbol | undefined; if (name.kind === SyntaxKind.Identifier) { - const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; + const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); const symbolFromJSPrototype = isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -13842,6 +13845,36 @@ namespace ts { // EXPRESSION TYPE CHECKING + function getCannotFindNameDiagnosticForName(name: __String): DiagnosticMessage { + switch (name) { + case "document": + case "console": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom; + case "$": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_types_Slashjquery; + case "describe": + case "suite": + case "it": + case "test": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_types_Slashjest_or_npm_i_types_Slashmocha; + case "process": + case "require": + case "Buffer": + case "module": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_types_Slashnode; + case "Map": + case "Set": + case "Promise": + case "Symbol": + case "WeakMap": + case "WeakSet": + case "Iterator": + case "AsyncIterator": + return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_es2015_or_later; + default: return Diagnostics.Cannot_find_name_0; + } + } + function getResolvedSymbol(node: Identifier): Symbol { const links = getNodeLinks(node); if (!links.resolvedSymbol) { @@ -13850,7 +13883,7 @@ namespace ts { node, node.escapedText, SymbolFlags.Value | SymbolFlags.ExportValue, - Diagnostics.Cannot_find_name_0, + getCannotFindNameDiagnosticForName(node.escapedText), node, !isWriteOnlyAccess(node), /*excludeGlobals*/ false, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index f3dec7287d5..18b64b74e0a 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2088,6 +2088,30 @@ "category": "Error", "code": 2577 }, + "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": { + "category": "Error", + "code": 2580 + }, + "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.": { + "category": "Error", + "code": 2581 + }, + "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.": { + "category": "Error", + "code": 2582 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2583 + }, + "Cannot find name '{0}'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'.": { + "category": "Error", + "code": 2584 + }, + "'{0}' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later.": { + "category": "Error", + "code": 2585 + }, "JSX element attributes type '{0}' may not be a union type.": { "category": "Error", "code": 2600 diff --git a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt index 232f476f66c..6622033a687 100644 --- a/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt +++ b/tests/baselines/reference/ES5For-ofTypeCheck10.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(9,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,15): error TS2569: Type 'StringIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. @@ -13,7 +13,7 @@ tests/cases/conformance/statements/for-ofStatements/ES5For-ofTypeCheck10.ts(14,1 } [Symbol.iterator]() { ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. return this; } } diff --git a/tests/baselines/reference/ES5SymbolProperty2.errors.txt b/tests/baselines/reference/ES5SymbolProperty2.errors.txt index 0535da56f06..2115ed99979 100644 --- a/tests/baselines/reference/ES5SymbolProperty2.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty2.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(5,10): error TS2471: A computed property name of the form 'Symbol.iterator' must be of type 'symbol'. -tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/Symbols/ES5SymbolProperty2.ts (2 errors) ==== @@ -16,4 +16,4 @@ tests/cases/conformance/Symbols/ES5SymbolProperty2.ts(10,11): error TS2693: 'Sym (new M.C)[Symbol.iterator]; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. \ No newline at end of file +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. \ No newline at end of file diff --git a/tests/baselines/reference/ES5SymbolProperty6.errors.txt b/tests/baselines/reference/ES5SymbolProperty6.errors.txt index e359f9b73ba..4357fe6a62f 100644 --- a/tests/baselines/reference/ES5SymbolProperty6.errors.txt +++ b/tests/baselines/reference/ES5SymbolProperty6.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. -tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/conformance/Symbols/ES5SymbolProperty6.ts(5,9): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/Symbols/ES5SymbolProperty6.ts (2 errors) ==== class C { [Symbol.iterator]() { } ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } (new C)[Symbol.iterator] ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. \ No newline at end of file +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. \ No newline at end of file diff --git a/tests/baselines/reference/anonymousModules.errors.txt b/tests/baselines/reference/anonymousModules.errors.txt index 4893a0c80aa..b81513cfbbd 100644 --- a/tests/baselines/reference/anonymousModules.errors.txt +++ b/tests/baselines/reference/anonymousModules.errors.txt @@ -1,22 +1,22 @@ -tests/cases/compiler/anonymousModules.ts(1,1): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(4,2): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(10,2): error TS2304: Cannot find name 'module'. +tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. ==== tests/cases/compiler/anonymousModules.ts (6 errors) ==== module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. export var foo = 1; module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. export var bar = 1; @@ -26,7 +26,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. var x = bar; diff --git a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt index 92764ddf90b..4ae19920e37 100644 --- a/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt +++ b/tests/baselines/reference/argumentsObjectIterator02_ES5.errors.txt @@ -1,11 +1,11 @@ -tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/compiler/argumentsObjectIterator02_ES5.ts(2,26): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/compiler/argumentsObjectIterator02_ES5.ts (1 errors) ==== function doubleAndReturnAsArray(x: number, y: number, z: number): [number, number, number] { let blah = arguments[Symbol.iterator]; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. let result = []; for (let arg of blah()) { diff --git a/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt b/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt index 88b1890d6d8..2f47712c9db 100644 --- a/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt +++ b/tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/salsa/bug24934.js(2,1): error TS2304: Cannot find name 'module'. +tests/cases/conformance/salsa/bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/salsa/bug24934.js (1 errors) ==== export function abc(a, b, c) { return 5; } module.exports = { abc }; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/salsa/use.js (0 errors) ==== import { abc } from './bug24934'; abc(1, 2, 3); diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 46eaa413c2e..1b0034a3063 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2304: Cannot find name 'module'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2503: Cannot find namespace 'module'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -21,8 +21,8 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,41): error TS tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,45): error TS1002: Unterminated string literal. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(41,21): error TS2304: Cannot find name 'retValue'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(46,13): error TS1005: 'try' expected. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(47,17): error TS2304: Cannot find name 'console'. -tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(53,13): error TS2304: Cannot find name 'console'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(47,17): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(53,13): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(58,5): error TS1128: Declaration or statement expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(69,13): error TS1109: Expression expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(72,37): error TS1127: Invalid character. @@ -103,9 +103,9 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS import fs = module("fs"); ~~~~~~ -!!! error TS2304: Cannot find name 'module'. - ~~~~~~ !!! error TS2503: Cannot find namespace 'module'. + ~~~~~~ +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. @@ -188,7 +188,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS !!! error TS1005: 'try' expected. console.log(e); ~~~~~~~ -!!! error TS2304: Cannot find name 'console'. +!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. } finally { @@ -196,7 +196,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS console.log('Done'); ~~~~~~~ -!!! error TS2304: Cannot find name 'console'. +!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. return 0; diff --git a/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.errors.txt b/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.errors.txt index 1af8d3f7102..a99536c582b 100644 --- a/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.errors.txt +++ b/tests/baselines/reference/decoratorMetadataNoLibIsolatedModulesTypes.errors.txt @@ -7,7 +7,7 @@ error TS2318: Cannot find global type 'Object'. error TS2318: Cannot find global type 'RegExp'. error TS2318: Cannot find global type 'String'. tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(2,6): error TS2304: Cannot find name 'Decorate'. -tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error TS2304: Cannot find name 'Map'. +tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. !!! error TS2318: Cannot find global type 'Array'. @@ -25,6 +25,6 @@ tests/cases/compiler/decoratorMetadataNoLibIsolatedModulesTypes.ts(3,13): error !!! error TS2304: Cannot find name 'Decorate'. member: Map; ~~~ -!!! error TS2304: Cannot find name 'Map'. +!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt b/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt new file mode 100644 index 00000000000..a41b19ecd9d --- /dev/null +++ b/tests/baselines/reference/didYouMeanSuggestionErrors.errors.txt @@ -0,0 +1,88 @@ +tests/cases/compiler/didYouMeanSuggestionErrors.ts(1,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(2,5): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(3,19): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(7,1): error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(8,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,9): error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(9,21): error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(10,9): error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(12,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(13,19): error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(14,19): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(16,23): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(17,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(18,23): error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(19,23): error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(20,19): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(21,19): error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(23,18): error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/didYouMeanSuggestionErrors.ts(24,18): error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + + +==== tests/cases/compiler/didYouMeanSuggestionErrors.ts (19 errors) ==== + describe("my test suite", () => { + ~~~~~~~~ +!!! error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. + it("should run", () => { + ~~ +!!! error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. + const a = $(".thing"); + ~ +!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. + }); + }); + + suite("another suite", () => { + ~~~~~ +!!! error TS2582: Cannot find name 'suite'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. + test("everything else", () => { + ~~~~ +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. + console.log(process.env); + ~~~~~~~ +!!! error TS2584: Cannot find name 'console'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. + ~~~~~~~ +!!! error TS2580: Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i @types/node`. + document.createElement("div"); + ~~~~~~~~ +!!! error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the `lib` compiler option to include 'dom'. + + const x = require("fs"); + ~~~~~~~ +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. + const y = Buffer.from([]); + ~~~~~~ +!!! error TS2580: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i @types/node`. + const z = module.exports; + ~~~~~~ +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. + + const a = new Map(); + ~~~ +!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const b = new Set(); + ~~~ +!!! error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const c = new WeakMap(); + ~~~~~~~ +!!! error TS2583: Cannot find name 'WeakMap'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const d = new WeakSet(); + ~~~~~~~ +!!! error TS2583: Cannot find name 'WeakSet'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const e = Symbol(); + ~~~~~~ +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const f = Promise.resolve(0); + ~~~~~~~ +!!! error TS2585: 'Promise' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + + const i: Iterator = null as any; + ~~~~~~~~ +!!! error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const j: AsyncIterator = null as any; + ~~~~~~~~~~~~~ +!!! error TS2583: Cannot find name 'AsyncIterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. + const k: Symbol = null as any; + const l: Promise = null as any; + }); + }); \ No newline at end of file diff --git a/tests/baselines/reference/didYouMeanSuggestionErrors.js b/tests/baselines/reference/didYouMeanSuggestionErrors.js new file mode 100644 index 00000000000..fb13a31bb98 --- /dev/null +++ b/tests/baselines/reference/didYouMeanSuggestionErrors.js @@ -0,0 +1,55 @@ +//// [didYouMeanSuggestionErrors.ts] +describe("my test suite", () => { + it("should run", () => { + const a = $(".thing"); + }); +}); + +suite("another suite", () => { + test("everything else", () => { + console.log(process.env); + document.createElement("div"); + + const x = require("fs"); + const y = Buffer.from([]); + const z = module.exports; + + const a = new Map(); + const b = new Set(); + const c = new WeakMap(); + const d = new WeakSet(); + const e = Symbol(); + const f = Promise.resolve(0); + + const i: Iterator = null as any; + const j: AsyncIterator = null as any; + const k: Symbol = null as any; + const l: Promise = null as any; + }); +}); + +//// [didYouMeanSuggestionErrors.js] +describe("my test suite", function () { + it("should run", function () { + var a = $(".thing"); + }); +}); +suite("another suite", function () { + test("everything else", function () { + console.log(process.env); + document.createElement("div"); + var x = require("fs"); + var y = Buffer.from([]); + var z = module.exports; + var a = new Map(); + var b = new Set(); + var c = new WeakMap(); + var d = new WeakSet(); + var e = Symbol(); + var f = Promise.resolve(0); + var i = null; + var j = null; + var k = null; + var l = null; + }); +}); diff --git a/tests/baselines/reference/didYouMeanSuggestionErrors.symbols b/tests/baselines/reference/didYouMeanSuggestionErrors.symbols new file mode 100644 index 00000000000..8f63b2addd5 --- /dev/null +++ b/tests/baselines/reference/didYouMeanSuggestionErrors.symbols @@ -0,0 +1,57 @@ +=== tests/cases/compiler/didYouMeanSuggestionErrors.ts === +describe("my test suite", () => { + it("should run", () => { + const a = $(".thing"); +>a : Symbol(a, Decl(didYouMeanSuggestionErrors.ts, 2, 13)) + + }); +}); + +suite("another suite", () => { + test("everything else", () => { + console.log(process.env); + document.createElement("div"); + + const x = require("fs"); +>x : Symbol(x, Decl(didYouMeanSuggestionErrors.ts, 11, 13)) + + const y = Buffer.from([]); +>y : Symbol(y, Decl(didYouMeanSuggestionErrors.ts, 12, 13)) + + const z = module.exports; +>z : Symbol(z, Decl(didYouMeanSuggestionErrors.ts, 13, 13)) + + const a = new Map(); +>a : Symbol(a, Decl(didYouMeanSuggestionErrors.ts, 15, 13)) + + const b = new Set(); +>b : Symbol(b, Decl(didYouMeanSuggestionErrors.ts, 16, 13)) + + const c = new WeakMap(); +>c : Symbol(c, Decl(didYouMeanSuggestionErrors.ts, 17, 13)) + + const d = new WeakSet(); +>d : Symbol(d, Decl(didYouMeanSuggestionErrors.ts, 18, 13)) + + const e = Symbol(); +>e : Symbol(e, Decl(didYouMeanSuggestionErrors.ts, 19, 13)) + + const f = Promise.resolve(0); +>f : Symbol(f, Decl(didYouMeanSuggestionErrors.ts, 20, 13)) + + const i: Iterator = null as any; +>i : Symbol(i, Decl(didYouMeanSuggestionErrors.ts, 22, 13)) + + const j: AsyncIterator = null as any; +>j : Symbol(j, Decl(didYouMeanSuggestionErrors.ts, 23, 13)) + + const k: Symbol = null as any; +>k : Symbol(k, Decl(didYouMeanSuggestionErrors.ts, 24, 13)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --)) + + const l: Promise = null as any; +>l : Symbol(l, Decl(didYouMeanSuggestionErrors.ts, 25, 13)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --)) + + }); +}); diff --git a/tests/baselines/reference/didYouMeanSuggestionErrors.types b/tests/baselines/reference/didYouMeanSuggestionErrors.types new file mode 100644 index 00000000000..60259cde734 --- /dev/null +++ b/tests/baselines/reference/didYouMeanSuggestionErrors.types @@ -0,0 +1,125 @@ +=== tests/cases/compiler/didYouMeanSuggestionErrors.ts === +describe("my test suite", () => { +>describe("my test suite", () => { it("should run", () => { const a = $(".thing"); });}) : any +>describe : any +>"my test suite" : "my test suite" +>() => { it("should run", () => { const a = $(".thing"); });} : () => void + + it("should run", () => { +>it("should run", () => { const a = $(".thing"); }) : any +>it : any +>"should run" : "should run" +>() => { const a = $(".thing"); } : () => void + + const a = $(".thing"); +>a : any +>$(".thing") : any +>$ : any +>".thing" : ".thing" + + }); +}); + +suite("another suite", () => { +>suite("another suite", () => { test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator = null as any; const j: AsyncIterator = null as any; const k: Symbol = null as any; const l: Promise = null as any; });}) : any +>suite : any +>"another suite" : "another suite" +>() => { test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator = null as any; const j: AsyncIterator = null as any; const k: Symbol = null as any; const l: Promise = null as any; });} : () => void + + test("everything else", () => { +>test("everything else", () => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator = null as any; const j: AsyncIterator = null as any; const k: Symbol = null as any; const l: Promise = null as any; }) : any +>test : any +>"everything else" : "everything else" +>() => { console.log(process.env); document.createElement("div"); const x = require("fs"); const y = Buffer.from([]); const z = module.exports; const a = new Map(); const b = new Set(); const c = new WeakMap(); const d = new WeakSet(); const e = Symbol(); const f = Promise.resolve(0); const i: Iterator = null as any; const j: AsyncIterator = null as any; const k: Symbol = null as any; const l: Promise = null as any; } : () => void + + console.log(process.env); +>console.log(process.env) : any +>console.log : any +>console : any +>log : any +>process.env : any +>process : any +>env : any + + document.createElement("div"); +>document.createElement("div") : any +>document.createElement : any +>document : any +>createElement : any +>"div" : "div" + + const x = require("fs"); +>x : any +>require("fs") : any +>require : any +>"fs" : "fs" + + const y = Buffer.from([]); +>y : any +>Buffer.from([]) : any +>Buffer.from : any +>Buffer : any +>from : any +>[] : undefined[] + + const z = module.exports; +>z : any +>module.exports : any +>module : any +>exports : any + + const a = new Map(); +>a : any +>new Map() : any +>Map : any + + const b = new Set(); +>b : any +>new Set() : any +>Set : any + + const c = new WeakMap(); +>c : any +>new WeakMap() : any +>WeakMap : any + + const d = new WeakSet(); +>d : any +>new WeakSet() : any +>WeakSet : any + + const e = Symbol(); +>e : any +>Symbol() : any +>Symbol : any + + const f = Promise.resolve(0); +>f : any +>Promise.resolve(0) : any +>Promise.resolve : any +>Promise : any +>resolve : any +>0 : 0 + + const i: Iterator = null as any; +>i : any +>null as any : any +>null : null + + const j: AsyncIterator = null as any; +>j : any +>null as any : any +>null : null + + const k: Symbol = null as any; +>k : Symbol +>null as any : any +>null : null + + const l: Promise = null as any; +>l : Promise +>null as any : any +>null : null + + }); +}); diff --git a/tests/baselines/reference/externModule.errors.txt b/tests/baselines/reference/externModule.errors.txt index 329ef0a8862..1ca359d5d1d 100644 --- a/tests/baselines/reference/externModule.errors.txt +++ b/tests/baselines/reference/externModule.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/externModule.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/compiler/externModule.ts(1,9): error TS1005: ';' expected. -tests/cases/compiler/externModule.ts(1,9): error TS2304: Cannot find name 'module'. +tests/cases/compiler/externModule.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/externModule.ts(1,16): error TS1005: ';' expected. tests/cases/compiler/externModule.ts(3,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/externModule.ts(4,10): error TS2391: Function implementation is missing or not immediately following the declaration. @@ -21,7 +21,7 @@ tests/cases/compiler/externModule.ts(37,3): error TS2552: Cannot find name 'XDat ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. export class XDate { diff --git a/tests/baselines/reference/fixSignatureCaching.errors.txt b/tests/baselines/reference/fixSignatureCaching.errors.txt index b1d26a73682..bf4400313b2 100644 --- a/tests/baselines/reference/fixSignatureCaching.errors.txt +++ b/tests/baselines/reference/fixSignatureCaching.errors.txt @@ -50,9 +50,9 @@ tests/cases/conformance/fixSignatureCaching.ts(915,36): error TS2339: Property ' tests/cases/conformance/fixSignatureCaching.ts(915,53): error TS2339: Property 'mobileDetectRules' does not exist on type '{}'. tests/cases/conformance/fixSignatureCaching.ts(955,42): error TS2339: Property 'mobileGrade' does not exist on type '{}'. tests/cases/conformance/fixSignatureCaching.ts(964,57): error TS2339: Property 'getDeviceSmallerSide' does not exist on type '{}'. -tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2304: Cannot find name 'module'. -tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2304: Cannot find name 'module'. -tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2304: Cannot find name 'module'. +tests/cases/conformance/fixSignatureCaching.ts(978,16): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/fixSignatureCaching.ts(978,42): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/fixSignatureCaching.ts(979,37): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/fixSignatureCaching.ts(980,23): error TS2304: Cannot find name 'define'. tests/cases/conformance/fixSignatureCaching.ts(980,48): error TS2304: Cannot find name 'define'. tests/cases/conformance/fixSignatureCaching.ts(981,16): error TS2304: Cannot find name 'define'. @@ -1143,12 +1143,12 @@ tests/cases/conformance/fixSignatureCaching.ts(983,44): error TS2339: Property ' })((function (undefined) { if (typeof module !== 'undefined' && module.exports) { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. return function (factory) { module.exports = factory(); }; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. } else if (typeof define === 'function' && define.amd) { ~~~~~~ !!! error TS2304: Cannot find name 'define'. diff --git a/tests/baselines/reference/innerModExport1.errors.txt b/tests/baselines/reference/innerModExport1.errors.txt index b4f06cc998a..29ce225dfa2 100644 --- a/tests/baselines/reference/innerModExport1.errors.txt +++ b/tests/baselines/reference/innerModExport1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/innerModExport1.ts(5,5): error TS2304: Cannot find name 'module'. +tests/cases/compiler/innerModExport1.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected. @@ -9,7 +9,7 @@ tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected. var non_export_var: number; module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. var non_export_var = 0; diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index f9568bb45a4..21cc583c5d3 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'module'. +tests/cases/compiler/innerModExport2.ts(5,5): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. @@ -12,7 +12,7 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport var non_export_var: number; module { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. var non_export_var = 0; diff --git a/tests/baselines/reference/jsxAndTypeAssertion.errors.txt b/tests/baselines/reference/jsxAndTypeAssertion.errors.txt index 5aa92086c37..6d3f6874a88 100644 --- a/tests/baselines/reference/jsxAndTypeAssertion.errors.txt +++ b/tests/baselines/reference/jsxAndTypeAssertion.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,6): error TS17008: JSX element 'any' has no corresponding closing tag. -tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,13): error TS2304: Cannot find name 'test'. +tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,13): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(6,17): error TS1005: '}' expected. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(8,6): error TS17008: JSX element 'any' has no corresponding closing tag. tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(10,6): error TS17008: JSX element 'foo' has no corresponding closing tag. @@ -24,7 +24,7 @@ tests/cases/conformance/jsx/jsxAndTypeAssertion.tsx(21,1): error TS1005: ' void'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(20,6): error TS2551: Property 'sign' does not exist on type 'Math'. Did you mean 'sin'? -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(25,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(29,18): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(33,13): error TS2304: Cannot find name 'Proxy'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(36,1): error TS2304: Cannot find name 'Reflect'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(40,5): error TS2339: Property 'flags' does not exist on type 'RegExp'. tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(44,5): error TS2339: Property 'includes' does not exist on type 'string'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(47,9): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(51,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(47,9): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts(51,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.ts (12 errors) ==== @@ -26,7 +26,7 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 collection var m = new Map(); ~~~ -!!! error TS2304: Cannot find name 'Map'. +!!! error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. m.clear(); // Using ES6 iterable m.keys(); @@ -48,13 +48,13 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t a: 2, [Symbol.hasInstance](value: any) { ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. return false; } }; o.hasOwnProperty(Symbol.hasInstance); ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. // Using Es6 proxy var t = {} @@ -82,13 +82,13 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingES6FeaturesWithOnlyES5Lib.t // Using ES6 symbol var s = Symbol(); ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. // Using ES6 wellknown-symbol const o1 = { [Symbol.hasInstance](value: any) { ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. return false; } } \ No newline at end of file diff --git a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.errors.txt b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.errors.txt index c2b9abc56f1..aab5dbc8b83 100644 --- a/tests/baselines/reference/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.errors.txt +++ b/tests/baselines/reference/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.ts(7,1): error TS2322: Type 'false' is not assignable to type 'string'. -tests/cases/compiler/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.ts(7,3): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/compiler/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.ts(7,3): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/compiler/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6WellknownSymbolLib.ts (2 errors) ==== @@ -13,4 +13,4 @@ tests/cases/compiler/modularizeLibrary_ErrorFromUsingWellknownSymbolWithOutES6We ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type 'false' is not assignable to type 'string'. ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. \ No newline at end of file +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. \ No newline at end of file diff --git a/tests/baselines/reference/moduleExports1.errors.txt b/tests/baselines/reference/moduleExports1.errors.txt index 18b65654cea..03d21d86b8a 100644 --- a/tests/baselines/reference/moduleExports1.errors.txt +++ b/tests/baselines/reference/moduleExports1.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/moduleExports1.ts(13,6): error TS2304: Cannot find name 'module'. -tests/cases/compiler/moduleExports1.ts(13,22): error TS2304: Cannot find name 'module'. +tests/cases/compiler/moduleExports1.ts(13,6): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/moduleExports1.ts(13,22): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/compiler/moduleExports1.ts (2 errors) ==== @@ -17,6 +17,6 @@ tests/cases/compiler/moduleExports1.ts(13,22): error TS2304: Cannot find name 'm if (!module.exports) module.exports = ""; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. \ No newline at end of file +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. \ No newline at end of file diff --git a/tests/baselines/reference/moduleKeywordRepeatError.errors.txt b/tests/baselines/reference/moduleKeywordRepeatError.errors.txt index d77acf4f4d1..65a81c19213 100644 --- a/tests/baselines/reference/moduleKeywordRepeatError.errors.txt +++ b/tests/baselines/reference/moduleKeywordRepeatError.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/moduleKeywordRepeatError.ts(3,1): error TS2304: Cannot find name 'module'. +tests/cases/compiler/moduleKeywordRepeatError.ts(3,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/moduleKeywordRepeatError.ts(3,15): error TS1005: ';' expected. @@ -7,6 +7,6 @@ tests/cases/compiler/moduleKeywordRepeatError.ts(3,15): error TS1005: ';' expect module.module { } ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt b/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt index 4876d5276f7..b131c8adac0 100644 --- a/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt +++ b/tests/baselines/reference/noAssertForUnparseableTypedefs.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/jsdoc/bug26693.js(1,15): error TS2304: Cannot find name 'module'. +tests/cases/conformance/jsdoc/bug26693.js(1,15): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/jsdoc/bug26693.js(1,21): error TS1005: '}' expected. tests/cases/conformance/jsdoc/bug26693.js(2,22): error TS2307: Cannot find module 'nope'. @@ -6,7 +6,7 @@ tests/cases/conformance/jsdoc/bug26693.js(2,22): error TS2307: Cannot find modul ==== tests/cases/conformance/jsdoc/bug26693.js (3 errors) ==== /** @typedef {module:locale} hi */ ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: '}' expected. import { nope } from 'nope'; diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt index cded9c44a3d..56adb4706f1 100644 --- a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(1,14): error TS1005: '(' expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,3): error TS1128: Declaration or statement expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,10): error TS2304: Cannot find name 'test'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(2,10): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,3): error TS1128: Declaration or statement expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2304: Cannot find name 'test'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,10): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,19): error TS1005: ',' expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(3,20): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,3): error TS1128: Declaration or statement expected. -tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2304: Cannot find name 'test'. +tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,10): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,15): error TS2304: Cannot find name 'name'. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,20): error TS1109: Expression expected. tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,21): error TS2693: 'any' only refers to a type, but is being used as a value here. @@ -22,12 +22,12 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. static test(name:string) ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ @@ -38,7 +38,7 @@ tests/cases/compiler/overloadingStaticFunctionsInFunctions.ts(4,25): error TS100 ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ diff --git a/tests/baselines/reference/parser509534.errors.txt b/tests/baselines/reference/parser509534.errors.txt index 78d56d1413e..ff5eb131b5c 100644 --- a/tests/baselines/reference/parser509534.errors.txt +++ b/tests/baselines/reference/parser509534.errors.txt @@ -1,15 +1,15 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509534.ts(2,14): error TS2304: Cannot find name 'require'. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509534.ts(3,1): error TS2304: Cannot find name 'module'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509534.ts(2,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509534.ts(3,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509534.ts (2 errors) ==== "use strict"; var config = require("../config"); ~~~~~~~ -!!! error TS2304: Cannot find name 'require'. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. module.exports.route = function (server) { ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. // General Login Page server.get(config.env.siteRoot + "/auth/login", function (req, res, next) { diff --git a/tests/baselines/reference/parser509693.errors.txt b/tests/baselines/reference/parser509693.errors.txt index b910af1c2e6..b6fbff74f33 100644 --- a/tests/baselines/reference/parser509693.errors.txt +++ b/tests/baselines/reference/parser509693.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509693.ts(1,6): error TS2304: Cannot find name 'module'. -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509693.ts(1,22): error TS2304: Cannot find name 'module'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509693.ts(1,6): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509693.ts(1,22): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser509693.ts (2 errors) ==== if (!module.exports) module.exports = ""; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. \ No newline at end of file +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. \ No newline at end of file diff --git a/tests/baselines/reference/parser519458.errors.txt b/tests/baselines/reference/parser519458.errors.txt index 66dae596b81..ee13350fcbb 100644 --- a/tests/baselines/reference/parser519458.errors.txt +++ b/tests/baselines/reference/parser519458.errors.txt @@ -1,14 +1,14 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,15): error TS2304: Cannot find name 'module'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,15): error TS2503: Cannot find namespace 'module'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,15): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,21): error TS1005: ';' expected. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts (3 errors) ==== import rect = module("rect"); var bar = new rect.Rect(); ~~~~~~ -!!! error TS2304: Cannot find name 'module'. - ~~~~~~ !!! error TS2503: Cannot find namespace 'module'. + ~~~~~~ +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parser521128.errors.txt b/tests/baselines/reference/parser521128.errors.txt index 93491af588d..910c4217b4f 100644 --- a/tests/baselines/reference/parser521128.errors.txt +++ b/tests/baselines/reference/parser521128.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/RegressionTests/parser521128.ts(1,1): error TS2304: Cannot find name 'module'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser521128.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser521128.ts(1,15): error TS1005: ';' expected. ==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser521128.ts (2 errors) ==== module.module { } ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserCommaInTypeMemberList2.errors.txt b/tests/baselines/reference/parserCommaInTypeMemberList2.errors.txt index 931bd87293d..f2f695e0120 100644 --- a/tests/baselines/reference/parserCommaInTypeMemberList2.errors.txt +++ b/tests/baselines/reference/parserCommaInTypeMemberList2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserCommaInTypeMemberList2.ts(1,9): error TS2304: Cannot find name '$'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserCommaInTypeMemberList2.ts(1,9): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. ==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserCommaInTypeMemberList2.ts (1 errors) ==== var s = $.extend< { workItem: any }, { workItem: any, width: string }>({ workItem: this._workItem }, {}); ~ -!!! error TS2304: Cannot find name '$'. +!!! error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`. \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty1.errors.txt b/tests/baselines/reference/parserES5SymbolProperty1.errors.txt index 1d7d361ef3a..3082110db28 100644 --- a/tests/baselines/reference/parserES5SymbolProperty1.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty1.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty1.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty1.ts (1 errors) ==== interface I { [Symbol.iterator]: string; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty2.errors.txt b/tests/baselines/reference/parserES5SymbolProperty2.errors.txt index 581f65b0a49..cc0a80c7889 100644 --- a/tests/baselines/reference/parserES5SymbolProperty2.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty2.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty2.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty2.ts (1 errors) ==== interface I { [Symbol.unscopables](): string; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty3.errors.txt b/tests/baselines/reference/parserES5SymbolProperty3.errors.txt index 8db74c51255..894ffc0bb8f 100644 --- a/tests/baselines/reference/parserES5SymbolProperty3.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty3.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty3.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty3.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty3.ts (1 errors) ==== declare class C { [Symbol.unscopables](): string; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty4.errors.txt b/tests/baselines/reference/parserES5SymbolProperty4.errors.txt index 1fd929502e3..2cc89cefd71 100644 --- a/tests/baselines/reference/parserES5SymbolProperty4.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty4.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty4.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty4.ts (1 errors) ==== declare class C { [Symbol.isRegExp]: string; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty5.errors.txt b/tests/baselines/reference/parserES5SymbolProperty5.errors.txt index a4b25f4b64d..f37f0e0d028 100644 --- a/tests/baselines/reference/parserES5SymbolProperty5.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty5.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty5.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty5.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty5.ts (1 errors) ==== class C { [Symbol.isRegExp]: string; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty6.errors.txt b/tests/baselines/reference/parserES5SymbolProperty6.errors.txt index 26a4d1e8efe..08d48f2c02a 100644 --- a/tests/baselines/reference/parserES5SymbolProperty6.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty6.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty6.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty6.ts (1 errors) ==== class C { [Symbol.toStringTag]: string = ""; ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty7.errors.txt b/tests/baselines/reference/parserES5SymbolProperty7.errors.txt index 5ecf3495fa9..3a5fd74e20a 100644 --- a/tests/baselines/reference/parserES5SymbolProperty7.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty7.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty7.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty7.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty7.ts (1 errors) ==== class C { [Symbol.toStringTag](): void { } ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty8.errors.txt b/tests/baselines/reference/parserES5SymbolProperty8.errors.txt index 5b4c0b99b51..90e0df0211f 100644 --- a/tests/baselines/reference/parserES5SymbolProperty8.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty8.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty8.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty8.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty8.ts (1 errors) ==== var x: { [Symbol.toPrimitive](): string ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolProperty9.errors.txt b/tests/baselines/reference/parserES5SymbolProperty9.errors.txt index 6ff6f65f0cd..9a21a7942cb 100644 --- a/tests/baselines/reference/parserES5SymbolProperty9.errors.txt +++ b/tests/baselines/reference/parserES5SymbolProperty9.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty9.ts(2,6): error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty9.ts(2,6): error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolProperty9.ts (1 errors) ==== var x: { [Symbol.toPrimitive]: string ~~~~~~ -!!! error TS2693: 'Symbol' only refers to a type, but is being used as a value here. +!!! error TS2585: 'Symbol' only refers to a type, but is being used as a value here. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. } \ No newline at end of file diff --git a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt index 728295b76cb..c724b594159 100644 --- a/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt +++ b/tests/baselines/reference/parserMissingLambdaOpenBrace1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,19): error TS2304: Cannot find name 'Iterator'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,19): error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,28): error TS2304: Cannot find name 'T'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,42): error TS2304: Cannot find name 'Query'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpenBrace1.ts(2,48): error TS2304: Cannot find name 'T'. @@ -11,7 +11,7 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserMissingLambdaOpen class C { where(filter: Iterator): Query { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Iterator'. +!!! error TS2583: Cannot find name 'Iterator'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. ~ !!! error TS2304: Cannot find name 'T'. ~~~~~ diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index 5ec35021fef..990fa5816c7 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -5,8 +5,8 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(19,21): er tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(21,29): error TS2694: Namespace 'Harness' has no exported member 'Assert'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(25,17): error TS2304: Cannot find name 'IIO'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(41,12): error TS2304: Cannot find name 'ActiveXObject'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(43,19): error TS2304: Cannot find name 'require'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(44,14): error TS2304: Cannot find name 'require'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(43,19): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(44,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(341,13): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(347,13): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(351,17): error TS2662: Cannot find name 'errorHandlerStack'. Did you mean the static member 'Runnable.errorHandlerStack'? @@ -169,10 +169,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): eval(typescriptServiceFile); } else if (typeof require === "function") { ~~~~~~~ -!!! error TS2304: Cannot find name 'require'. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. var vm = require('vm'); ~~~~~~~ -!!! error TS2304: Cannot find name 'require'. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. vm.runInThisContext(typescriptServiceFile, 'typescriptServices.js'); } else { throw new Error('Unknown context'); diff --git a/tests/baselines/reference/reservedWords2.errors.txt b/tests/baselines/reference/reservedWords2.errors.txt index 0760e1e2566..437b414a69d 100644 --- a/tests/baselines/reference/reservedWords2.errors.txt +++ b/tests/baselines/reference/reservedWords2.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/reservedWords2.ts(1,8): error TS1109: Expression expected. tests/cases/compiler/reservedWords2.ts(1,14): error TS1005: '(' expected. -tests/cases/compiler/reservedWords2.ts(1,16): error TS2304: Cannot find name 'require'. +tests/cases/compiler/reservedWords2.ts(1,16): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/reservedWords2.ts(1,31): error TS1005: ')' expected. tests/cases/compiler/reservedWords2.ts(2,12): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(2,12): error TS2567: Enum declarations can only merge with namespace or other enum declarations. @@ -14,7 +14,7 @@ tests/cases/compiler/reservedWords2.ts(5,9): error TS2300: Duplicate identifier tests/cases/compiler/reservedWords2.ts(5,9): error TS2567: Enum declarations can only merge with namespace or other enum declarations. tests/cases/compiler/reservedWords2.ts(5,10): error TS1003: Identifier expected. tests/cases/compiler/reservedWords2.ts(5,18): error TS1005: '=>' expected. -tests/cases/compiler/reservedWords2.ts(6,1): error TS2304: Cannot find name 'module'. +tests/cases/compiler/reservedWords2.ts(6,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/reservedWords2.ts(6,8): error TS1005: ';' expected. tests/cases/compiler/reservedWords2.ts(7,11): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(7,11): error TS1005: ':' expected. @@ -39,7 +39,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. ~ !!! error TS1005: '(' expected. ~~~~~~~ -!!! error TS2304: Cannot find name 'require'. +!!! error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ')' expected. import * as while from "foo" @@ -72,7 +72,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. !!! error TS1005: '=>' expected. module void {} ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~ !!! error TS1005: ';' expected. var {while, return} = { while: 1, return: 2 }; diff --git a/tests/baselines/reference/staticsInAFunction.errors.txt b/tests/baselines/reference/staticsInAFunction.errors.txt index 254f321913b..499ab91e93f 100644 --- a/tests/baselines/reference/staticsInAFunction.errors.txt +++ b/tests/baselines/reference/staticsInAFunction.errors.txt @@ -1,13 +1,13 @@ tests/cases/compiler/staticsInAFunction.ts(1,13): error TS1005: '(' expected. tests/cases/compiler/staticsInAFunction.ts(2,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(2,11): error TS2304: Cannot find name 'test'. +tests/cases/compiler/staticsInAFunction.ts(2,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/staticsInAFunction.ts(3,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2304: Cannot find name 'test'. +tests/cases/compiler/staticsInAFunction.ts(3,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/staticsInAFunction.ts(3,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(3,20): error TS1005: ',' expected. tests/cases/compiler/staticsInAFunction.ts(3,21): error TS2693: 'string' only refers to a type, but is being used as a value here. tests/cases/compiler/staticsInAFunction.ts(4,4): error TS1128: Declaration or statement expected. -tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2304: Cannot find name 'test'. +tests/cases/compiler/staticsInAFunction.ts(4,11): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. tests/cases/compiler/staticsInAFunction.ts(4,16): error TS2304: Cannot find name 'name'. tests/cases/compiler/staticsInAFunction.ts(4,21): error TS1109: Expression expected. tests/cases/compiler/staticsInAFunction.ts(4,22): error TS2693: 'any' only refers to a type, but is being used as a value here. @@ -22,12 +22,12 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. static test(name:string) ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ @@ -38,7 +38,7 @@ tests/cases/compiler/staticsInAFunction.ts(4,26): error TS1005: ';' expected. ~~~~~~ !!! error TS1128: Declaration or statement expected. ~~~~ -!!! error TS2304: Cannot find name 'test'. +!!! error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. ~~~~ !!! error TS2304: Cannot find name 'name'. ~ diff --git a/tests/baselines/reference/templateStringInModuleName.errors.txt b/tests/baselines/reference/templateStringInModuleName.errors.txt index 1664638d086..f684b305c52 100644 --- a/tests/baselines/reference/templateStringInModuleName.errors.txt +++ b/tests/baselines/reference/templateStringInModuleName.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS2304: Cannot find name 'module'. +tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(1,21): error TS1005: ';' expected. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS2304: Cannot find name 'module'. +tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error TS1005: ';' expected. @@ -15,7 +15,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. } @@ -26,7 +26,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleName.ts(4,24): error ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/templateStringInModuleNameES6.errors.txt b/tests/baselines/reference/templateStringInModuleNameES6.errors.txt index c46b6e5fc8c..ecd072a7579 100644 --- a/tests/baselines/reference/templateStringInModuleNameES6.errors.txt +++ b/tests/baselines/reference/templateStringInModuleNameES6.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS2304: Cannot find name 'module'. +tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(1,21): error TS1005: ';' expected. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,1): error TS2304: Cannot find name 'declare'. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS1005: ';' expected. -tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS2304: Cannot find name 'module'. +tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,9): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): error TS1005: ';' expected. @@ -15,7 +15,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): er ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. } @@ -26,7 +26,7 @@ tests/cases/conformance/es6/templates/templateStringInModuleNameES6.ts(4,24): er ~~~~~~ !!! error TS1005: ';' expected. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~ !!! error TS1005: ';' expected. } \ No newline at end of file diff --git a/tests/baselines/reference/typecheckIfCondition.errors.txt b/tests/baselines/reference/typecheckIfCondition.errors.txt index 3f23c71d247..e9c3707583e 100644 --- a/tests/baselines/reference/typecheckIfCondition.errors.txt +++ b/tests/baselines/reference/typecheckIfCondition.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2304: Cannot find name 'module'. -tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2304: Cannot find name 'module'. +tests/cases/compiler/typecheckIfCondition.ts(4,10): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/compiler/typecheckIfCondition.ts (2 errors) ==== @@ -8,9 +8,9 @@ tests/cases/compiler/typecheckIfCondition.ts(4,26): error TS2304: Cannot find na { if (!module.exports) module.exports = ""; ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ~~~~~~ -!!! error TS2304: Cannot find name 'module'. +!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. var x = null; // don't want to baseline output } \ No newline at end of file diff --git a/tests/cases/compiler/didYouMeanSuggestionErrors.ts b/tests/cases/compiler/didYouMeanSuggestionErrors.ts new file mode 100644 index 00000000000..d5af5a338d3 --- /dev/null +++ b/tests/cases/compiler/didYouMeanSuggestionErrors.ts @@ -0,0 +1,29 @@ +// @lib: es5 +describe("my test suite", () => { + it("should run", () => { + const a = $(".thing"); + }); +}); + +suite("another suite", () => { + test("everything else", () => { + console.log(process.env); + document.createElement("div"); + + const x = require("fs"); + const y = Buffer.from([]); + const z = module.exports; + + const a = new Map(); + const b = new Set(); + const c = new WeakMap(); + const d = new WeakSet(); + const e = Symbol(); + const f = Promise.resolve(0); + + const i: Iterator = null as any; + const j: AsyncIterator = null as any; + const k: Symbol = null as any; + const l: Promise = null as any; + }); +}); \ No newline at end of file From 42479ca337459c24f27114676aed9beb9afbb343 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 15:35:12 -0700 Subject: [PATCH 095/146] Maintain project references more clearly - no need to maintain map from referencing projects to references - When queueing for downstream projects, always handle build order --- src/compiler/tsbuild.ts | 82 +++++++------------- src/testRunner/unittests/tsbuildWatchMode.ts | 12 +-- 2 files changed, 33 insertions(+), 61 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index f61ef42c7cb..87c1f44430b 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -11,10 +11,9 @@ namespace ts { message(diag: DiagnosticMessage, ...args: string[]): void; } - type Mapper = ReturnType; interface DependencyGraph { buildQueue: ResolvedConfigFileName[]; - dependencyMap: Mapper; + referencingProjectsMap: ConfigFileMap>; } export interface BuildOptions { @@ -220,40 +219,18 @@ namespace ts { } } - function createDependencyMapper(toPath: ToResolvedConfigFilePath) { - const childToParents = createFileMap(toPath); - const parentToChildren = createFileMap(toPath); - - function addReference(childConfigFileName: ResolvedConfigFileName, parentConfigFileName: ResolvedConfigFileName): void { - addEntry(childToParents, childConfigFileName, parentConfigFileName); - addEntry(parentToChildren, parentConfigFileName, childConfigFileName); + function getOrCreateValueFromConfigFileMap(configFileMap: ConfigFileMap, resolved: ResolvedConfigFileName, createT: () => T): T { + const existingValue = configFileMap.getValue(resolved); + let newValue: T | undefined; + if (!existingValue) { + newValue = createT(); + configFileMap.setValue(resolved, newValue); } + return existingValue || newValue!; + } - function getReferencesTo(parentConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return parentToChildren.getValue(parentConfigFileName) || []; - } - - function getReferencesOf(childConfigFileName: ResolvedConfigFileName): ResolvedConfigFileName[] { - return childToParents.getValue(childConfigFileName) || []; - } - - function addEntry(mapToAddTo: typeof childToParents | typeof parentToChildren, key: ResolvedConfigFileName, element: ResolvedConfigFileName) { - key = normalizePath(key) as ResolvedConfigFileName; - element = normalizePath(element) as ResolvedConfigFileName; - let arr = mapToAddTo.getValue(key); - if (arr === undefined) { - mapToAddTo.setValue(key, arr = []); - } - if (arr.indexOf(element) < 0) { - arr.push(element); - } - } - - return { - addReference, - getReferencesTo, - getReferencesOf, - }; + function getOrCreateValueMapFromConfigFileMap(configFileMap: ConfigFileMap>, resolved: ResolvedConfigFileName): Map { + return getOrCreateValueFromConfigFileMap>(configFileMap, resolved, createMap); } function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine) { @@ -529,19 +506,9 @@ namespace ts { } } - function getOrCreateExistingWatches(resolved: ResolvedConfigFileName, allWatches: ConfigFileMap>) { - const existingWatches = allWatches.getValue(resolved); - let newWatches: Map | undefined; - if (!existingWatches) { - newWatches = createMap(); - allWatches.setValue(resolved, newWatches); - } - return existingWatches || newWatches!; - } - function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { updateWatchingWildcardDirectories( - getOrCreateExistingWatches(resolved, allWatchedWildcardDirectories), + getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), (dir, flags) => { return hostWithWatch.watchDirectory(dir, fileOrDirectory => { @@ -564,7 +531,7 @@ namespace ts { function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { mutateMap( - getOrCreateExistingWatches(resolved, allWatchedInputFiles), + getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), arrayToMap(parsed.fileNames, toPath), { createNewValue: (_key, input) => hostWithWatch.watchFile(input, () => { @@ -818,7 +785,7 @@ namespace ts { if (addProjToQueue(resolved, reloadLevel)) { // TODO: instead of adding the dependent project to queue right away postpone this - queueBuildForDownstreamReferences(resolved, getGlobalDependencyGraph()); + queueBuildForDownstreamReferences(resolved); } } @@ -857,12 +824,15 @@ namespace ts { } // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root: ResolvedConfigFileName, dependencyGraph: DependencyGraph) { - const deps = dependencyGraph.dependencyMap.getReferencesTo(root); - for (const ref of deps) { + function queueBuildForDownstreamReferences(root: ResolvedConfigFileName) { + const dependencyGraph = getGlobalDependencyGraph(); + const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(root); + if (!referencingProjects) return; + // Always use build order to queue projects + for (const project of dependencyGraph.buildQueue) { // Can skip circular references - if (addProjToQueue(ref)) { - queueBuildForDownstreamReferences(ref, dependencyGraph); + if (referencingProjects.hasKey(project) && addProjToQueue(project)) { + queueBuildForDownstreamReferences(project); } } } @@ -944,14 +914,14 @@ namespace ts { const permanentMarks = createFileMap(toPath); const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; - const graph = createDependencyMapper(toPath); + const referencingProjectsMap = createFileMap>(toPath); for (const root of roots) { visit(root); } return { buildQueue: buildOrder, - dependencyMap: graph, + referencingProjectsMap }; function visit(projPath: ResolvedConfigFileName, inCircularContext = false) { @@ -972,7 +942,9 @@ namespace ts { for (const ref of parsed.projectReferences) { const resolvedRefPath = resolveProjectName(ref.path); visit(resolvedRefPath, inCircularContext || ref.circular); - graph.addReference(projPath, resolvedRefPath); + // Get projects referencing resolvedRefPath and add projPath to it + const referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, () => createFileMap(toPath)); + referencingProjects.setValue(projPath, true); } } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index bc1bc4f373d..006facc0a39 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -137,16 +137,16 @@ namespace ts.tscWatch { ...getOutputFileNames(SubProject.core, "index"), ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds tests - const changedTests = getOutputFileStamps(host, additionalFiles); - verifyChangedFiles(changedTests, changedCore, [ - ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written - ]); host.checkTimeoutQueueLengthAndRun(1); // Builds logic const changedLogic = getOutputFileStamps(host, additionalFiles); - verifyChangedFiles(changedLogic, changedTests, [ + verifyChangedFiles(changedLogic, changedCore, [ ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written + ]); host.checkTimeoutQueueLength(0); checkOutputErrorsIncremental(host, emptyArray); verifyWatches(); From 8a7550f82f887dd1e28d3f0b258a3a8f34c9dae2 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 15:51:10 -0700 Subject: [PATCH 096/146] Deadcode removal --- src/compiler/tsbuild.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 87c1f44430b..33790a1ab35 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -1128,10 +1128,9 @@ namespace ts { function buildAllProjects(): ExitStatus { if (options.watch) { reportWatchStatus(Diagnostics.Starting_compilation_in_watch_mode); } const graph = getGlobalDependencyGraph(); - const queue = graph.buildQueue; reportBuildQueue(graph); let anyFailed = false; - for (const next of queue) { + for (const next of graph.buildQueue) { const proj = parseConfigFile(next); if (proj === undefined) { anyFailed = true; @@ -1188,13 +1187,9 @@ namespace ts { * Report the build ordering inferred from the current project graph if we're in verbose mode */ function reportBuildQueue(graph: DependencyGraph) { - if (!options.verbose) return; - - const names: string[] = []; - for (const name of graph.buildQueue) { - names.push(name); + if (options.verbose) { + reportStatus(Diagnostics.Projects_in_this_build_Colon_0, graph.buildQueue.map(s => "\r\n * " + relName(s)).join("")); } - if (options.verbose) reportStatus(Diagnostics.Projects_in_this_build_Colon_0, names.map(s => "\r\n * " + relName(s)).join("")); } function relName(path: string): string { From bdf1c782b2edf0cbc82b8f37bfa5f31dc5417133 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 11 Sep 2018 15:59:24 -0700 Subject: [PATCH 097/146] Report file not found error about the project and watch config file even if not present --- src/compiler/tsbuild.ts | 50 ++++++++++--------- src/testRunner/unittests/tsbuildWatchMode.ts | 52 ++++++++++++++++++-- 2 files changed, 75 insertions(+), 27 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 33790a1ab35..1aaa3e07f1c 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -483,11 +483,11 @@ namespace ts { function startWatching() { const graph = getGlobalDependencyGraph(); for (const resolved of graph.buildQueue) { + // Watch this file + watchConfigFile(resolved); + const cfg = parseConfigFile(resolved); if (cfg) { - // Watch this file - watchConfigFile(resolved); - // Update watchers for wildcard directories watchWildCardDirectories(resolved, cfg); @@ -879,7 +879,11 @@ namespace ts { // TODO:: handle this in better way later const proj = parseConfigFile(resolved); - if (!proj) return; // ? + if (!proj) { + reportParseConfigFileDiagnostic(resolved); + return; + } + if (reloadLevel === ConfigFileProgramReloadLevel.Full) { watchConfigFile(resolved); watchWildCardDirectories(resolved, proj); @@ -954,6 +958,11 @@ namespace ts { } } + function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) { + host.reportDiagnostic(configFileCache.getValue(proj) as Diagnostic); + storeErrorSummary(proj, 1); + } + function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags { if (options.dry) { reportStatus(Diagnostics.A_non_dry_build_would_build_project_0, proj); @@ -969,8 +978,7 @@ namespace ts { if (!configFile) { // Failed to read the config file resultFlags |= BuildResultFlags.ConfigFileErrors; - host.reportDiagnostic(configFileCache.getValue(proj) as Diagnostic); - storeErrorSummary(proj, 1); + reportParseConfigFileDiagnostic(proj); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Config file errors" }); return resultFlags; } @@ -995,10 +1003,7 @@ namespace ts { ...program.getSyntacticDiagnostics()]; if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; - for (const diag of syntaxDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, syntaxDiagnostics); + reportErrors(proj, syntaxDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); return resultFlags; } @@ -1008,10 +1013,7 @@ namespace ts { const declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; - for (const diag of declDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, declDiagnostics); + reportErrors(proj, declDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); return resultFlags; } @@ -1021,10 +1023,7 @@ namespace ts { const semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { resultFlags |= BuildResultFlags.TypeErrors; - for (const diag of semanticDiagnostics) { - host.reportDiagnostic(diag); - } - storeErrors(proj, semanticDiagnostics); + reportErrors(proj, semanticDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); return resultFlags; } @@ -1091,6 +1090,7 @@ namespace ts { const parsed = parseConfigFile(proj); if (parsed === undefined) { // File has gone missing; fine to ignore here + reportParseConfigFileDiagnostic(proj); continue; } const outputs = getAllProjectOutputs(parsed); @@ -1133,6 +1133,7 @@ namespace ts { for (const next of graph.buildQueue) { const proj = parseConfigFile(next); if (proj === undefined) { + reportParseConfigFileDiagnostic(next); anyFailed = true; break; } @@ -1144,7 +1145,7 @@ namespace ts { const projName = proj.options.configFilePath!; if (status.type === UpToDateStatusType.UpToDate && !options.force) { - reportErrors(errors); + reportErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1154,20 +1155,20 @@ namespace ts { } if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { - reportErrors(errors); + reportErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - reportErrors(errors); + reportErrors(next, errors); if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { - reportErrors(errors); + reportErrors(next, errors); // Do nothing continue; } @@ -1179,8 +1180,9 @@ namespace ts { return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } - function reportErrors(errors: Diagnostic[]) { - errors.forEach((err) => host.reportDiagnostic(err)); + function reportErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { + errors.forEach(err => host.reportDiagnostic(err)); + storeErrors(proj, errors); } /** diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 006facc0a39..e2abd2a0d04 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -98,9 +98,7 @@ namespace ts.tscWatch { function createSolutionInWatchMode() { const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); - checkWatchedFiles(host, testProjectExpectedWatchedFiles); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); + verifyWatches(host); checkOutputErrorsInitial(host, emptyArray); const outputFileStamps = getOutputFileStamps(host); for (const stamp of outputFileStamps) { @@ -108,6 +106,13 @@ namespace ts.tscWatch { } return host; } + + function verifyWatches(host: WatchedSystem) { + checkWatchedFiles(host, testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); + } + it("creates solution in watch mode", () => { createSolutionInWatchMode(); }); @@ -197,6 +202,47 @@ export class someClass2 { }`); }); + it("watches config files that are not present", () => { + const allFiles = [libFile, ...core, logic[1], ...tests]; + const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); + checkWatchedFiles(host, [core[0], core[1], core[2], logic[0], ...tests].map(f => f.path)); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core)], /*recursive*/ true); + checkOutputErrorsInitial(host, [ + createCompilerDiagnostic(Diagnostics.File_0_not_found, logic[0].path) + ]); + for (const f of [ + ...getOutputFileNames(SubProject.core, "anotherModule"), + ...getOutputFileNames(SubProject.core, "index") + ]) { + assert.isTrue(host.fileExists(f), `${f} expected to be present`); + } + for (const f of [ + ...getOutputFileNames(SubProject.logic, "index"), + ...getOutputFileNames(SubProject.tests, "index") + ]) { + assert.isFalse(host.fileExists(f), `${f} expected to be absent`); + } + + // Create tsconfig file for logic and see that build succeeds + const initial = getOutputFileStamps(host); + host.writeFile(logic[0].path, logic[0].content); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, initial, [ + ...getOutputFileNames(SubProject.logic, "index") + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + // TODO: write tests reporting errors but that will have more involved work since file }); } From 371ffffc6d497a04791f3c2b19e44b268f2e0ac5 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Wed, 12 Sep 2018 10:17:26 -0700 Subject: [PATCH 098/146] Update user baselines (#27048) --- .../reference/user/adonis-framework.log | 2 +- tests/baselines/reference/user/assert.log | 20 +-- tests/baselines/reference/user/async.log | 2 +- .../user/chrome-devtools-frontend.log | 6 +- .../reference/user/create-react-app.log | 16 +-- tests/baselines/reference/user/debug.log | 119 ++++++++++++------ tests/baselines/reference/user/lodash.log | 16 +-- 7 files changed, 109 insertions(+), 72 deletions(-) diff --git a/tests/baselines/reference/user/adonis-framework.log b/tests/baselines/reference/user/adonis-framework.log index 6c7272790fe..7796b296dbe 100644 --- a/tests/baselines/reference/user/adonis-framework.log +++ b/tests/baselines/reference/user/adonis-framework.log @@ -35,7 +35,7 @@ node_modules/adonis-framework/src/Env/index.js(54,15): error TS2304: Cannot find node_modules/adonis-framework/src/Env/index.js(56,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Env/index.js(80,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Event/index.js(13,21): error TS2307: Cannot find module 'adonis-fold'. -node_modules/adonis-framework/src/Event/index.js(128,5): error TS2322: Type '() => {}[]' is not assignable to type 'any[]'. +node_modules/adonis-framework/src/Event/index.js(128,12): error TS2322: Type '() => {}[]' is not assignable to type 'any[]'. Property 'pop' is missing in type '() => {}[]'. node_modules/adonis-framework/src/Event/index.js(153,25): error TS2339: Property 'wildcard' does not exist on type 'EventEmitter2'. node_modules/adonis-framework/src/Event/index.js(188,17): error TS2304: Cannot find name 'Spread'. diff --git a/tests/baselines/reference/user/assert.log b/tests/baselines/reference/user/assert.log index 37a2c42e4d6..ab73398f14c 100644 --- a/tests/baselines/reference/user/assert.log +++ b/tests/baselines/reference/user/assert.log @@ -25,17 +25,17 @@ node_modules/assert/test.js(143,10): error TS2339: Property 'a' does not exist o node_modules/assert/test.js(149,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? node_modules/assert/test.js(157,51): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'never' has no compatible call signatures. node_modules/assert/test.js(161,5): error TS2552: Cannot find name 'test'. Did you mean 'tests'? -node_modules/assert/test.js(168,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(182,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(229,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(235,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(250,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(254,5): error TS2304: Cannot find name 'test'. +node_modules/assert/test.js(168,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(182,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(229,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(235,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(250,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(254,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. node_modules/assert/test.js(256,55): error TS2345: Argument of type 'TypeError' is not assignable to parameter of type 'string'. -node_modules/assert/test.js(262,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(279,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(285,5): error TS2304: Cannot find name 'test'. -node_modules/assert/test.js(320,5): error TS2304: Cannot find name 'test'. +node_modules/assert/test.js(262,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(279,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(285,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +node_modules/assert/test.js(320,5): error TS2582: Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 3e7e3ab4c4b..791445bfddc 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -51,7 +51,7 @@ node_modules/async/autoInject.js(160,28): error TS2695: Left side of comma opera node_modules/async/autoInject.js(164,14): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/autoInject.js(168,6): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/cargo.js(62,12): error TS2304: Cannot find name 'AsyncFunction'. -node_modules/async/cargo.js(67,14): error TS2304: Cannot find name 'module'. +node_modules/async/cargo.js(67,14): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. node_modules/async/cargo.js(67,20): error TS1005: '}' expected. node_modules/async/cargo.js(92,11): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/compose.js(8,37): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index e58d2188be4..cf555239405 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -284,7 +284,7 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(811, node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(811,44): error TS2300: Duplicate identifier 'Request'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(7,11): error TS2339: Property 'AnimationScreenshotPopover' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(9,23): error TS2304: Cannot find name 'Image'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(18,39): error TS2345: Argument of type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to parameter of type 'Node'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(18,39): error TS2322: Type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to type 'Node'. Property 'baseURI' is missing in type 'new (width?: number, height?: number) => HTMLImageElement'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(19,13): error TS2339: Property 'style' does not exist on type 'new (width?: number, height?: number) => HTMLImageElement'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(22,21): error TS2339: Property 'style' does not exist on type 'new (width?: number, height?: number) => HTMLImageElement'. @@ -12007,7 +12007,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataP node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(621,36): error TS2339: Property 'preciseMillisToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(654,37): error TS2339: Property 'naturalHeight' does not exist on type 'new (width?: number, height?: number) => HTMLImageElement'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(655,39): error TS2339: Property 'naturalWidth' does not exist on type 'new (width?: number, height?: number) => HTMLImageElement'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(660,23): error TS2345: Argument of type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to parameter of type 'CanvasImageSource'. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(660,23): error TS2322: Type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to type 'CanvasImageSource'. Type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to type 'ImageBitmap'. Property 'height' is missing in type 'new (width?: number, height?: number) => HTMLImageElement'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(788,33): error TS2694: Namespace 'PerfUI.FlameChart' has no exported member 'GroupStyle'. @@ -12519,7 +12519,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1649 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1651,33): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1652,33): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1652,69): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1657,64): error TS2345: Argument of type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to parameter of type 'Node'. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1657,64): error TS2322: Type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to type 'Node'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1664,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1665,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1675,5): error TS2322: Type 'DocumentFragment' is not assignable to type 'Element'. diff --git a/tests/baselines/reference/user/create-react-app.log b/tests/baselines/reference/user/create-react-app.log index a7dc1694a90..537770fe818 100644 --- a/tests/baselines/reference/user/create-react-app.log +++ b/tests/baselines/reference/user/create-react-app.log @@ -15,9 +15,9 @@ packages/babel-preset-react-app/index.js(123,17): error TS2307: Cannot find modu packages/babel-preset-react-app/index.js(130,17): error TS2307: Cannot find module '@babel/plugin-transform-regenerator'. packages/babel-preset-react-app/index.js(137,15): error TS2307: Cannot find module '@babel/plugin-syntax-dynamic-import'. packages/babel-preset-react-app/index.js(140,17): error TS2307: Cannot find module 'babel-plugin-transform-dynamic-import'. -packages/confusing-browser-globals/test.js(14,1): error TS2304: Cannot find name 'it'. +packages/confusing-browser-globals/test.js(14,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/confusing-browser-globals/test.js(15,3): error TS2304: Cannot find name 'expect'. -packages/confusing-browser-globals/test.js(18,1): error TS2304: Cannot find name 'it'. +packages/confusing-browser-globals/test.js(18,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/confusing-browser-globals/test.js(19,3): error TS2304: Cannot find name 'expect'. packages/create-react-app/createReactApp.js(37,37): error TS2307: Cannot find module 'validate-npm-package-name'. packages/create-react-app/createReactApp.js(47,24): error TS2307: Cannot find module 'tar-pack'. @@ -35,18 +35,18 @@ packages/react-dev-utils/FileSizeReporter.js(16,24): error TS2307: Cannot find m packages/react-dev-utils/WebpackDevServerUtils.js(9,25): error TS2307: Cannot find module 'address'. packages/react-dev-utils/WebpackDevServerUtils.js(14,24): error TS2307: Cannot find module 'detect-port-alt'. packages/react-dev-utils/WebpackDevServerUtils.js(15,24): error TS2307: Cannot find module 'is-root'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2304: Cannot find name 'describe'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(12,1): error TS2582: Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(13,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(18,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(19,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(22,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(26,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(29,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(36,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/__tests__/ignoredFiles.test.js(37,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(40,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(46,5): error TS2304: Cannot find name 'expect'. -packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2304: Cannot find name 'it'. +packages/react-dev-utils/__tests__/ignoredFiles.test.js(49,3): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`. packages/react-dev-utils/__tests__/ignoredFiles.test.js(53,5): error TS2304: Cannot find name 'expect'. packages/react-dev-utils/browsersHelper.js(9,30): error TS2307: Cannot find module 'browserslist'. packages/react-dev-utils/browsersHelper.js(13,23): error TS2307: Cannot find module 'pkg-up'. diff --git a/tests/baselines/reference/user/debug.log b/tests/baselines/reference/user/debug.log index 62f54f6f17a..df15979cdb2 100644 --- a/tests/baselines/reference/user/debug.log +++ b/tests/baselines/reference/user/debug.log @@ -1,48 +1,85 @@ Exit Code: 1 Standard output: -node_modules/debug/src/browser.js(13,41): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(14,41): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(15,21): error TS2304: Cannot find name 'chrome'. -node_modules/debug/src/browser.js(48,47): error TS2339: Property 'process' does not exist on type 'Window'. -node_modules/debug/src/browser.js(48,65): error TS2339: Property 'process' does not exist on type 'Window'. -node_modules/debug/src/browser.js(59,139): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? -node_modules/debug/src/browser.js(61,73): error TS2339: Property 'firebug' does not exist on type 'Console'. -node_modules/debug/src/browser.js(187,13): error TS2304: Cannot find name 'LocalStorage'. -node_modules/debug/src/debug.js(25,1): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/debug/src/debug.js(26,1): error TS2323: Cannot redeclare exported variable 'skips'. -node_modules/debug/src/debug.js(46,13): error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'. -node_modules/debug/src/debug.js(47,57): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. -node_modules/debug/src/debug.js(51,18): error TS2339: Property 'colors' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(51,50): error TS2339: Property 'colors' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(75,10): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(76,10): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(77,10): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(112,13): error TS2551: Property 'formatArgs' does not exist on type 'typeof createDebug'. Did you mean 'formatters'? -node_modules/debug/src/debug.js(114,23): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: number; destroy: () => boolean; }'. -node_modules/debug/src/debug.js(114,38): error TS2339: Property 'log' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(120,29): error TS2339: Property 'useColors' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(125,37): error TS2339: Property 'init' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(126,13): error TS2339: Property 'init' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(153,11): error TS2339: Property 'save' does not exist on type 'typeof createDebug'. -node_modules/debug/src/debug.js(155,3): error TS2323: Cannot redeclare exported variable 'names'. -node_modules/debug/src/debug.js(156,3): error TS2323: Cannot redeclare exported variable 'skips'. -node_modules/debug/src/debug.js(217,12): error TS2304: Cannot find name 'Mixed'. -node_modules/debug/src/debug.js(218,13): error TS2304: Cannot find name 'Mixed'. -node_modules/debug/src/index.js(6,47): error TS2339: Property 'type' does not exist on type 'Process'. -node_modules/debug/src/node.js(26,1): error TS2323: Cannot redeclare exported variable 'colors'. -node_modules/debug/src/node.js(31,5): error TS2323: Cannot redeclare exported variable 'colors'. -node_modules/debug/src/node.js(60,39): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. +node_modules/debug/dist/debug.js(3,100): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/dist/debug.js(3,165): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/dist/debug.js(8,21): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(8,46): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(9,5): error TS2304: Cannot find name 'define'. +node_modules/debug/dist/debug.js(33,33): error TS2554: Expected 1 arguments, but got 2. +node_modules/debug/dist/debug.js(34,27): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'true | NodeRequire' has no compatible call signatures. +node_modules/debug/dist/debug.js(36,21): error TS2339: Property 'code' does not exist on type 'Error'. +node_modules/debug/dist/debug.js(89,38): error TS2339: Property 'length' does not exist on type 'string | number'. + Property 'length' does not exist on type 'number'. +node_modules/debug/dist/debug.js(90,24): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'string'. + Type 'number' is not assignable to type 'string'. +node_modules/debug/dist/debug.js(91,47): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(92,41): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(92,57): error TS2345: Argument of type 'string | number' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(110,11): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(116,11): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(169,13): error TS2322: Type 'undefined' is not assignable to type 'number'. +node_modules/debug/dist/debug.js(501,30): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(501,66): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(530,18): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(531,18): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(532,18): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(563,25): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. Did you mean 'formatters'? +node_modules/debug/dist/debug.js(564,30): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/dist/debug.js(564,49): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(570,41): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(577,34): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(578,25): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(609,23): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(680,19): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/dist/debug.js(681,20): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/dist/debug.js(694,40): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/dist/debug.js(733,55): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(733,74): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(733,112): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/dist/debug.js(744,146): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? +node_modules/debug/dist/debug.js(745,78): error TS2339: Property 'firebug' does not exist on type 'Console'. +node_modules/debug/dist/debug.js(851,21): error TS2304: Cannot find name 'LocalStorage'. +node_modules/debug/src/browser.js(3,100): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/src/browser.js(3,165): error TS2539: Cannot assign to '_typeof' because it is not a variable. +node_modules/debug/src/browser.js(34,47): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(34,66): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(34,104): error TS2339: Property 'process' does not exist on type 'Window'. +node_modules/debug/src/browser.js(45,138): error TS2551: Property 'WebkitAppearance' does not exist on type 'CSSStyleDeclaration'. Did you mean 'webkitAppearance'? +node_modules/debug/src/browser.js(46,70): error TS2339: Property 'firebug' does not exist on type 'Console'. +node_modules/debug/src/browser.js(152,13): error TS2304: Cannot find name 'LocalStorage'. +node_modules/debug/src/common.js(51,24): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(51,60): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(80,12): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(81,12): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(82,12): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(113,19): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. Did you mean 'formatters'? +node_modules/debug/src/common.js(114,24): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. +node_modules/debug/src/common.js(114,43): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(120,35): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(127,28): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(128,19): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(159,17): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(230,13): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/src/common.js(231,14): error TS2304: Cannot find name 'Mixed'. +node_modules/debug/src/common.js(244,34): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: any; default: any; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/index.js(7,47): error TS2339: Property 'type' does not exist on type 'Process'. +node_modules/debug/src/index.js(7,78): error TS2339: Property 'browser' does not exist on type 'Process'. +node_modules/debug/src/index.js(7,106): error TS2339: Property '__nwjs' does not exist on type 'Process'. +node_modules/debug/src/node.js(24,1): error TS2323: Cannot redeclare exported variable 'colors'. +node_modules/debug/src/node.js(32,5): error TS2323: Cannot redeclare exported variable 'colors'. +node_modules/debug/src/node.js(53,39): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/debug/src/node.js(60,45): error TS2322: Type 'true' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(61,46): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. +node_modules/debug/src/node.js(54,5): error TS2322: Type 'true' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(55,48): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/debug/src/node.js(61,52): error TS2322: Type 'false' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(62,28): error TS2322: Type 'null' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(63,8): error TS2322: Type 'number' is not assignable to type 'string | undefined'. -node_modules/debug/src/node.js(75,35): error TS2339: Property 'colors' does not exist on type 'never'. -node_modules/debug/src/node.js(76,33): error TS2339: Property 'fd' does not exist on type 'WriteStream'. -node_modules/debug/src/node.js(123,27): error TS2339: Property 'hideDate' does not exist on type '{}'. -node_modules/debug/src/node.js(163,3): error TS2322: Type 'string | undefined' is not assignable to type 'string'. +node_modules/debug/src/node.js(56,5): error TS2322: Type 'false' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(58,5): error TS2322: Type 'null' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(60,5): error TS2322: Type 'number' is not assignable to type 'string | undefined'. +node_modules/debug/src/node.js(71,108): error TS2339: Property 'fd' does not exist on type 'WriteStream'. +node_modules/debug/src/node.js(136,3): error TS2322: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index 6fd61c0fb69..0551046aec1 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -36,7 +36,7 @@ node_modules/lodash/_baseDifference.js(37,5): error TS2322: Type '(array?: any[] node_modules/lodash/_baseDifference.js(43,5): error TS2322: Type 'SetCache' is not assignable to type 'any[]'. Property 'length' is missing in type 'SetCache'. node_modules/lodash/_baseDifference.js(60,15): error TS2554: Expected 2 arguments, but got 3. -node_modules/lodash/_baseFlatten.js(19,17): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. +node_modules/lodash/_baseFlatten.js(19,29): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/_baseFlatten.js(24,22): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures. node_modules/lodash/_baseFlatten.js(24,22): error TS2532: Object is possibly 'undefined'. @@ -180,7 +180,7 @@ node_modules/lodash/cloneWith.js(39,27): error TS2345: Argument of type 'number' node_modules/lodash/conforms.js(32,41): error TS2345: Argument of type 'number' is not assignable to parameter of type 'boolean'. node_modules/lodash/core.js(68,58): error TS2339: Property 'Object' does not exist on type 'Window'. node_modules/lodash/core.js(77,82): error TS2339: Property 'nodeType' does not exist on type 'NodeModule'. -node_modules/lodash/core.js(540,19): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. +node_modules/lodash/core.js(540,31): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/core.js(545,24): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'Boolean' has no compatible call signatures. node_modules/lodash/core.js(545,24): error TS2532: Object is possibly 'undefined'. @@ -251,12 +251,12 @@ node_modules/lodash/debounce.js(86,30): error TS2532: Object is possibly 'undefi node_modules/lodash/debounce.js(111,23): error TS2532: Object is possibly 'undefined'. node_modules/lodash/debounce.js(125,65): error TS2532: Object is possibly 'undefined'. node_modules/lodash/deburr.js(42,44): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. -node_modules/lodash/difference.js(29,52): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/difference.js(29,52): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. -node_modules/lodash/differenceBy.js(40,52): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/differenceBy.js(40,52): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/differenceBy.js(40,78): error TS2554: Expected 0-1 arguments, but got 2. -node_modules/lodash/differenceWith.js(36,52): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/differenceWith.js(36,52): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/drop.js(13,10): error TS1003: Identifier expected. node_modules/lodash/drop.js(13,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. @@ -425,12 +425,12 @@ node_modules/lodash/truncate.js(78,16): error TS2454: Variable 'strSymbols' is u node_modules/lodash/truncate.js(85,7): error TS2454: Variable 'strSymbols' is used before being assigned. node_modules/lodash/unary.js(19,10): error TS2554: Expected 3 arguments, but got 2. node_modules/lodash/unescape.js(30,37): error TS2345: Argument of type 'Function' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. -node_modules/lodash/union.js(23,42): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/union.js(23,42): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. -node_modules/lodash/unionBy.js(36,42): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/unionBy.js(36,42): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/unionBy.js(36,68): error TS2554: Expected 0-1 arguments, but got 2. -node_modules/lodash/unionWith.js(31,42): error TS2345: Argument of type '(value: any) => boolean' is not assignable to parameter of type 'boolean | undefined'. +node_modules/lodash/unionWith.js(31,42): error TS2322: Type '(value: any) => boolean' is not assignable to type 'boolean | undefined'. Type '(value: any) => boolean' is not assignable to type 'true'. node_modules/lodash/uniqBy.js(28,52): error TS2554: Expected 0-1 arguments, but got 2. node_modules/lodash/words.js(15,10): error TS1003: Identifier expected. From 6bd1da20c978c6e652ec827dadecfad46d91a29f Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 12 Sep 2018 10:44:46 -0700 Subject: [PATCH 099/146] Rename JS-specific concepts (#26795) * Rename JS concepts 1. Assignment declaration -- an assignment that is treated like a declaration. Previously called [JS] special (assignment|declaration), among other things. 2. Expando -- a value that can be used as a target in assignment declarations. Currently, a class, function or empty object literal. Functions are allowed in Typescript, too. Previously called a JS container, JS initializer or expando object. 3. JavaScript -> Javascript. This is annoying to type, and looks like 'Java Script' in a camelCase world. Everything is a pure rename as far as I know. The only test change is the API baselines, which reflect the rename from SymbolFlags.JSContainer to SymbolFlags.Assignment. * Remove TODO * Rename Javascript->JS Note that this introduces a variable name collision in a couple of places, which I resolved like this: ```ts const isInJavascript = isInJSFile(node); ``` --- src/compiler/binder.ts | 52 ++-- src/compiler/checker.ts | 284 +++++++++--------- src/compiler/emitter.ts | 8 +- src/compiler/moduleNameResolver.ts | 4 +- src/compiler/moduleSpecifiers.ts | 8 +- src/compiler/program.ts | 10 +- src/compiler/transformers/declarations.ts | 12 +- src/compiler/tsbuild.ts | 4 +- src/compiler/types.ts | 12 +- src/compiler/utilities.ts | 138 ++++----- src/harness/harnessLanguageService.ts | 2 +- src/harness/vpath.ts | 6 +- src/jsTyping/jsTyping.ts | 4 +- src/server/editorServices.ts | 10 +- src/server/scriptInfo.ts | 2 +- .../codefixes/convertFunctionToEs6Class.ts | 2 +- .../codefixes/convertToAsyncFunction.ts | 6 +- .../codefixes/disableJsDiagnostics.ts | 2 +- src/services/codefixes/fixAddMissingMember.ts | 6 +- src/services/codefixes/importFixes.ts | 4 +- src/services/codefixes/inferFromUsage.ts | 2 +- src/services/completions.ts | 6 +- src/services/importTracker.ts | 6 +- src/services/jsDoc.ts | 4 +- src/services/navigationBar.ts | 16 +- src/services/refactors/extractSymbol.ts | 6 +- .../generateGetAccessorAndSetAccessor.ts | 2 +- src/services/refactors/moveToNewFile.ts | 2 +- src/services/services.ts | 2 +- src/services/signatureHelp.ts | 4 +- src/services/suggestionDiagnostics.ts | 8 +- src/services/utilities.ts | 16 +- src/testRunner/unittests/moduleResolution.ts | 6 +- src/tsserver/server.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 2 +- tests/baselines/reference/api/typescript.d.ts | 2 +- 36 files changed, 331 insertions(+), 331 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ea8fb3eea8d..489f212967d 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -288,7 +288,7 @@ namespace ts { // module.exports = ... return InternalSymbolName.ExportEquals; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) { + if (getAssignmentDeclarationKind(node as BinaryExpression) === AssignmentDeclarationKind.ModuleExports) { // module.exports = ... return InternalSymbolName.ExportEquals; } @@ -374,8 +374,8 @@ namespace ts { // prototype symbols like methods. symbolTable.set(name, symbol = createSymbol(SymbolFlags.None, name)); } - else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.JSContainer)) { - // JSContainers are allowed to merge with variables, no matter what other flags they have. + else if (!(includes & SymbolFlags.Variable && symbol.flags & SymbolFlags.Assignment)) { + // Assignment declarations are allowed to merge with variables, no matter what other flags they have. if (isNamedDeclaration(node)) { node.name.parent = node; } @@ -461,7 +461,7 @@ namespace ts { // during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation // and this case is specially handled. Module augmentations should only be merged with original module definition // and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed. - if (isJSDocTypeAlias(node)) Debug.assert(isInJavaScriptFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. + if (isJSDocTypeAlias(node)) Debug.assert(isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file. if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypeAlias(node)) { if (hasModifier(node, ModifierFlags.Default) && !getDeclarationName(node)) { return declareSymbol(container.symbol.exports!, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default! @@ -2009,7 +2009,7 @@ namespace ts { function bindJSDoc(node: Node) { if (hasJSDocNodes(node)) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { for (const j of node.jsDoc!) { bind(j); } @@ -2075,7 +2075,7 @@ namespace ts { if (isSpecialPropertyDeclaration(node as PropertyAccessExpression)) { bindSpecialPropertyDeclaration(node as PropertyAccessExpression); } - if (isInJavaScriptFile(node) && + if (isInJSFile(node) && file.commonJsModuleIndicator && isModuleExportsPropertyAccessExpression(node as PropertyAccessExpression) && !lookupSymbolForNameWorker(blockScopeContainer, "module" as __String)) { @@ -2084,27 +2084,27 @@ namespace ts { } break; case SyntaxKind.BinaryExpression: - const specialKind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const specialKind = getAssignmentDeclarationKind(node as BinaryExpression); switch (specialKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: + case AssignmentDeclarationKind.ExportsProperty: bindExportsPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: bindModuleExportsAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: bindPrototypePropertyAssignment((node as BinaryExpression).left as PropertyAccessEntityNameExpression, node); break; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: bindPrototypeAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: bindThisPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: bindSpecialPropertyAssignment(node as BinaryExpression); break; - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: // Nothing to do break; default: @@ -2184,7 +2184,7 @@ namespace ts { return bindFunctionExpression(node); case SyntaxKind.CallExpression: - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { bindCallExpression(node); } break; @@ -2361,7 +2361,7 @@ namespace ts { const lhs = node.left as PropertyAccessEntityNameExpression; const symbol = forEachIdentifierInEntityName(lhs.expression, /*parent*/ undefined, (id, symbol) => { if (symbol) { - addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.JSContainer); + addDeclarationToSymbol(symbol, id, SymbolFlags.Module | SymbolFlags.Assignment); } return symbol; }); @@ -2394,7 +2394,7 @@ namespace ts { } function bindThisPropertyAssignment(node: BinaryExpression | PropertyAccessExpression) { - Debug.assert(isInJavaScriptFile(node)); + Debug.assert(isInJSFile(node)); const thisContainer = getThisContainer(node, /*includeArrowFunctions*/ false); switch (thisContainer.kind) { case SyntaxKind.FunctionDeclaration: @@ -2482,7 +2482,7 @@ namespace ts { const lhs = node.left as PropertyAccessEntityNameExpression; // Class declarations in Typescript do not allow property declarations const parentSymbol = lookupSymbolForPropertyAccess(lhs.expression); - if (!isInJavaScriptFile(node) && !isFunctionSymbol(parentSymbol)) { + if (!isInJSFile(node) && !isFunctionSymbol(parentSymbol)) { return; } // Fix up parent pointers since we're going to use these nodes before we bind into them @@ -2515,8 +2515,8 @@ namespace ts { : propertyAccess.parent.parent.kind === SyntaxKind.SourceFile; if (!isPrototypeProperty && (!namespaceSymbol || !(namespaceSymbol.flags & SymbolFlags.Namespace)) && isToplevel) { // make symbols or add declarations for intermediate containers - const flags = SymbolFlags.Module | SymbolFlags.JSContainer; - const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.JSContainer; + const flags = SymbolFlags.Module | SymbolFlags.Assignment; + const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment; namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => { if (symbol) { addDeclarationToSymbol(symbol, id, flags); @@ -2527,7 +2527,7 @@ namespace ts { } }); } - if (!namespaceSymbol || !isJavascriptContainer(namespaceSymbol)) { + if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } @@ -2536,14 +2536,14 @@ namespace ts { (namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable())); - const isMethod = isFunctionLikeDeclaration(getAssignedJavascriptInitializer(propertyAccess)!); + const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(propertyAccess)!); const includes = isMethod ? SymbolFlags.Method : SymbolFlags.Property; const excludes = isMethod ? SymbolFlags.MethodExcludes : SymbolFlags.PropertyExcludes; - declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.JSContainer, excludes & ~SymbolFlags.JSContainer); + declareSymbol(symbolTable, namespaceSymbol, propertyAccess, includes | SymbolFlags.Assignment, excludes & ~SymbolFlags.Assignment); } /** - * Javascript containers are: + * Javascript expando values are: * - Functions * - classes * - namespaces @@ -2552,7 +2552,7 @@ namespace ts { * - with empty object literals * - with non-empty object literals if assigned to the prototype property */ - function isJavascriptContainer(symbol: Symbol): boolean { + function isExpandoSymbol(symbol: Symbol): boolean { if (symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.NamespaceModule)) { return true; } @@ -2565,7 +2565,7 @@ namespace ts { init = init && getRightMostAssignedExpression(init); if (init) { const isPrototypeAssignment = isPrototypeAccess(isVariableDeclaration(node) ? node.name : isBinaryExpression(node) ? node.left : node); - return !!getJavascriptInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); + return !!getExpandoInitializer(isBinaryExpression(init) && init.operatorToken.kind === SyntaxKind.BarBarToken ? init.right : init, isPrototypeAssignment); } return false; } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a856df2854a..974c74029eb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -824,7 +824,7 @@ namespace ts { */ function mergeSymbol(target: Symbol, source: Symbol): Symbol { if (!(target.flags & getExcludedSymbolFlags(source.flags)) || - (source.flags | target.flags) & SymbolFlags.JSContainer) { + (source.flags | target.flags) & SymbolFlags.Assignment) { Debug.assert(source !== target); if (!(target.flags & SymbolFlags.Transient)) { target = cloneSymbol(target); @@ -878,12 +878,12 @@ namespace ts { const secondInstanceList = existing.secondFileInstances.get(symbolName) || { instances: [], blockScoped: isEitherBlockScoped }; forEach(source.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; const targetList = sourceSymbolFile === firstFile ? firstInstanceList : secondInstanceList; targetList.instances.push(errorNode); }); forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; const targetList = targetSymbolFile === firstFile ? firstInstanceList : secondInstanceList; targetList.instances.push(errorNode); }); @@ -902,7 +902,7 @@ namespace ts { function addDuplicateDeclarationErrorsForSymbols(target: Symbol, message: DiagnosticMessage, symbolName: string, source: Symbol) { forEach(target.declarations, node => { - const errorNode = (getJavascriptInitializer(node, /*isPrototypeAssignment*/ false) ? getOuterNameOfJsInitializer(node) : getNameOfDeclaration(node)) || node; + const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); }); } @@ -1446,7 +1446,7 @@ namespace ts { } } if (!result) { - if (originalLocation && isInJavaScriptFile(originalLocation) && originalLocation.parent) { + if (originalLocation && isInJSFile(originalLocation) && originalLocation.parent) { if (isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) { return requireSymbol; } @@ -1622,7 +1622,7 @@ namespace ts { } function checkAndReportErrorForUsingTypeAsNamespace(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(errorLocation) ? SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(errorLocation) ? SymbolFlags.Value : 0); if (meaning === namespaceMeaning) { const symbol = resolveSymbol(resolveName(errorLocation, name, SymbolFlags.Type & ~namespaceMeaning, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); const parent = errorLocation.parent; @@ -1788,7 +1788,7 @@ namespace ts { return true; } // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement - if (!isSourceFileJavaScript(file)) { + if (!isSourceFileJS(file)) { return hasExportAssignmentSymbol(moduleSymbol); } // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker @@ -1979,7 +1979,7 @@ namespace ts { */ function isNonLocalAlias(symbol: Symbol | undefined, excludes = SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace): symbol is Symbol { if (!symbol) return false; - return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.JSContainer); + return (symbol.flags & (SymbolFlags.Alias | excludes)) === SymbolFlags.Alias || !!(symbol.flags & SymbolFlags.Alias && symbol.flags & SymbolFlags.Assignment); } function resolveSymbol(symbol: Symbol, dontResolveAlias?: boolean): Symbol; @@ -2081,11 +2081,11 @@ namespace ts { return undefined; } - const namespaceMeaning = SymbolFlags.Namespace | (isInJavaScriptFile(name) ? meaning & SymbolFlags.Value : 0); + const namespaceMeaning = SymbolFlags.Namespace | (isInJSFile(name) ? meaning & SymbolFlags.Value : 0); let symbol: Symbol | undefined; if (name.kind === SyntaxKind.Identifier) { const message = meaning === namespaceMeaning ? Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name).escapedText); - const symbolFromJSPrototype = isInJavaScriptFile(name) ? resolveEntityNameFromJSSpecialAssignment(name, meaning) : undefined; + const symbolFromJSPrototype = isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { return symbolFromJSPrototype; @@ -2101,7 +2101,7 @@ namespace ts { else if (namespace === unknownSymbol) { return namespace; } - if (isInJavaScriptFile(name)) { + if (isInJSFile(name)) { if (namespace.valueDeclaration && isVariableDeclaration(namespace.valueDeclaration) && namespace.valueDeclaration.initializer && @@ -2137,16 +2137,16 @@ namespace ts { * name resolution won't work either. * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too. */ - function resolveEntityNameFromJSSpecialAssignment(name: Identifier, meaning: SymbolFlags) { + function resolveEntityNameFromAssignmentDeclaration(name: Identifier, meaning: SymbolFlags) { if (isJSDocTypeReference(name.parent)) { - const secondaryLocation = getJSSpecialAssignmentLocation(name.parent); + const secondaryLocation = getAssignmentDeclarationLocation(name.parent); if (secondaryLocation) { return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true); } } } - function getJSSpecialAssignmentLocation(node: TypeReferenceNode): Node | undefined { + function getAssignmentDeclarationLocation(node: TypeReferenceNode): Node | undefined { const typeAlias = findAncestor(node, node => !(isJSDocNode(node) || node.flags & NodeFlags.JSDoc) ? "quit" : isJSDocTypeAlias(node)); if (typeAlias) { return; @@ -2154,7 +2154,7 @@ namespace ts { const host = getJSDocHost(node); if (isExpressionStatement(host) && isBinaryExpression(host.expression) && - getSpecialPropertyAssignmentKind(host.expression) === SpecialPropertyAssignmentKind.PrototypeProperty) { + getAssignmentDeclarationKind(host.expression) === AssignmentDeclarationKind.PrototypeProperty) { // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.expression.left); if (symbol) { @@ -2163,7 +2163,7 @@ namespace ts { } if ((isObjectLiteralMethod(host) || isPropertyAssignment(host)) && isBinaryExpression(host.parent.parent) && - getSpecialPropertyAssignmentKind(host.parent.parent) === SpecialPropertyAssignmentKind.Prototype) { + getAssignmentDeclarationKind(host.parent.parent) === AssignmentDeclarationKind.Prototype) { // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration const symbol = getSymbolOfNode(host.parent.parent.left); if (symbol) { @@ -2179,8 +2179,8 @@ namespace ts { function getDeclarationOfJSPrototypeContainer(symbol: Symbol) { const decl = symbol.parent!.valueDeclaration; - const initializer = isAssignmentDeclaration(decl) ? getAssignedJavascriptInitializer(decl) : - hasOnlyExpressionInitializer(decl) ? getDeclaredJavascriptInitializer(decl) : + const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : + hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : undefined; return initializer || decl; } @@ -4732,7 +4732,7 @@ namespace ts { return addOptionality(declaredType, isOptional); } - if ((noImplicitAny || isInJavaScriptFile(declaration)) && + if ((noImplicitAny || isInJSFile(declaration)) && declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !(declaration.flags & NodeFlags.Ambient)) { // If --noImplicitAny is on or the declaration is in a Javascript file, @@ -4764,7 +4764,7 @@ namespace ts { return getReturnTypeOfSignature(getterSignature); } } - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const typeTag = getJSDocType(func); if (typeTag && isFunctionTypeNode(typeTag)) { return getTypeAtPosition(getSignatureFromDeclaration(typeTag), func.parameters.indexOf(declaration)); @@ -4776,10 +4776,10 @@ namespace ts { return addOptionality(type, isOptional); } } - else if (isInJavaScriptFile(declaration)) { - const expandoType = getJSExpandoObjectType(declaration, getSymbolOfNode(declaration), getDeclaredJavascriptInitializer(declaration)); - if (expandoType) { - return expandoType; + else if (isInJSFile(declaration)) { + const containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), getDeclaredExpandoInitializer(declaration)); + if (containerObjectType) { + return containerObjectType; } } @@ -4804,16 +4804,16 @@ namespace ts { return undefined; } - function getWidenedTypeFromJSPropertyAssignments(symbol: Symbol, resolvedSymbol?: Symbol) { - // function/class/{} assignments are fresh declarations, not property assignments, so only add prototype assignments - const specialDeclaration = getAssignedJavascriptInitializer(symbol.valueDeclaration); - if (specialDeclaration) { - const tag = getJSDocTypeTag(specialDeclaration); + function getWidenedTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol?: Symbol) { + // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers + const container = getAssignedExpandoInitializer(symbol.valueDeclaration); + if (container) { + const tag = getJSDocTypeTag(container); if (tag && tag.typeExpression) { return getTypeFromTypeNode(tag.typeExpression); } - const expando = getJSExpandoObjectType(symbol.valueDeclaration, symbol, specialDeclaration); - return expando || getWidenedLiteralType(checkExpressionCached(specialDeclaration)); + const containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container); + return containerObjectType || getWidenedLiteralType(checkExpressionCached(container)); } let definedInConstructor = false; let definedInMethod = false; @@ -4827,8 +4827,8 @@ namespace ts { return errorType; } - const special = isPropertyAccessExpression(expression) ? getSpecialPropertyAccessKind(expression) : getSpecialPropertyAssignmentKind(expression); - if (special === SpecialPropertyAssignmentKind.ThisProperty) { + const kind = isPropertyAccessExpression(expression) ? getAssignmentDeclarationPropertyAccessKind(expression) : getAssignmentDeclarationKind(expression); + if (kind === AssignmentDeclarationKind.ThisProperty) { if (isDeclarationInConstructor(expression)) { definedInConstructor = true; } @@ -4836,9 +4836,9 @@ namespace ts { definedInMethod = true; } } - jsdocType = getJSDocTypeFromSpecialDeclarations(jsdocType, expression, symbol, declaration); + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); if (!jsdocType) { - (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromSpecialDeclarations(symbol, resolvedSymbol, expression, special) : neverType); + (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } let type = jsdocType; @@ -4846,7 +4846,7 @@ namespace ts { let constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types!, symbol.declarations) : undefined; // use only the constructor types unless they were only assigned null | undefined (including widening variants) if (definedInMethod) { - const propType = getTypeOfSpecialPropertyOfBaseType(symbol); + const propType = getTypeOfAssignmentDeclarationPropertyOfBaseType(symbol); if (propType) { (constructorTypes || (constructorTypes = [])).push(propType); definedInConstructor = true; @@ -4865,8 +4865,8 @@ namespace ts { return widened; } - function getJSExpandoObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { - if (!isInJavaScriptFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { + function getJSContainerObjectType(decl: Node, symbol: Symbol, init: Expression | undefined): Type | undefined { + if (!isInJSFile(decl) || !init || !isObjectLiteralExpression(init) || init.properties.length) { return undefined; } const exports = createSymbolTable(); @@ -4886,7 +4886,7 @@ namespace ts { return type; } - function getJSDocTypeFromSpecialDeclarations(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { + function getJSDocTypeFromAssignmentDeclaration(declaredType: Type | undefined, expression: Expression, _symbol: Symbol, declaration: Declaration) { const typeNode = getJSDocType(expression.parent); if (typeNode) { const type = getWidenedType(getTypeFromTypeNode(typeNode)); @@ -4901,10 +4901,10 @@ namespace ts { } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromSpecialDeclarations(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, special: SpecialPropertyAssignmentKind) { + function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, kind: AssignmentDeclarationKind) { const type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right)); if (type.flags & TypeFlags.Object && - special === SpecialPropertyAssignmentKind.ModuleExports && + kind === AssignmentDeclarationKind.ModuleExports && symbol.escapedName === InternalSymbolName.ExportEquals) { const exportedType = resolveStructuredTypeMembers(type as ObjectType); const members = createSymbolTable(); @@ -4962,8 +4962,8 @@ namespace ts { } /** check for definition in base class if any declaration is in a class */ - function getTypeOfSpecialPropertyOfBaseType(specialProperty: Symbol) { - const parentDeclaration = forEach(specialProperty.declarations, d => { + function getTypeOfAssignmentDeclarationPropertyOfBaseType(property: Symbol) { + const parentDeclaration = forEach(property.declarations, d => { const parent = getThisContainer(d, /*includeArrowFunctions*/ false).parent; return isClassLike(parent) && parent; }); @@ -4971,7 +4971,7 @@ namespace ts { const classType = getDeclaredTypeOfSymbol(getSymbolOfNode(parentDeclaration)) as InterfaceType; const baseClassType = classType && getBaseTypes(classType)[0]; if (baseClassType) { - return getTypeOfPropertyOfType(baseClassType, specialProperty.escapedName); + return getTypeOfPropertyOfType(baseClassType, property.escapedName); } } } @@ -5154,9 +5154,9 @@ namespace ts { return errorType; } let type: Type | undefined; - if (isInJavaScriptFile(declaration) && + if (isInJSFile(declaration) && (isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { - type = getWidenedTypeFromJSPropertyAssignments(symbol); + type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) || isPropertyAccessExpression(declaration) @@ -5170,7 +5170,7 @@ namespace ts { return getTypeOfFuncClassEnumModule(symbol); } type = isBinaryExpression(declaration.parent) ? - getWidenedTypeFromJSPropertyAssignments(symbol) : + getWidenedTypeFromAssignmentDeclaration(symbol) : tryGetTypeFromEffectiveTypeNode(declaration) || anyType; } else if (isPropertyAssignment(declaration)) { @@ -5239,7 +5239,7 @@ namespace ts { const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - if (getter && isInJavaScriptFile(getter)) { + if (getter && isInJSFile(getter)) { const jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return jsDocType; @@ -5302,7 +5302,7 @@ namespace ts { let links = getSymbolLinks(symbol); const originalLinks = links; if (!links.type) { - const jsDeclaration = getDeclarationOfJSInitializer(symbol.valueDeclaration); + const jsDeclaration = getDeclarationOfExpando(symbol.valueDeclaration); if (jsDeclaration) { const jsSymbol = getSymbolOfNode(jsDeclaration); if (jsSymbol && (hasEntries(jsSymbol.exports) || hasEntries(jsSymbol.members))) { @@ -5331,7 +5331,7 @@ namespace ts { } else if (declaration.kind === SyntaxKind.BinaryExpression || declaration.kind === SyntaxKind.PropertyAccessExpression && declaration.parent.kind === SyntaxKind.BinaryExpression) { - return getWidenedTypeFromJSPropertyAssignments(symbol); + return getWidenedTypeFromAssignmentDeclaration(symbol); } else if (symbol.flags & SymbolFlags.ValueModule && declaration && isSourceFile(declaration) && declaration.commonJsModuleIndicator) { const resolvedModule = resolveExternalModuleSymbol(symbol); @@ -5340,7 +5340,7 @@ namespace ts { return errorType; } const exportEquals = getMergedSymbol(symbol.exports!.get(InternalSymbolName.ExportEquals)!); - const type = getWidenedTypeFromJSPropertyAssignments(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); + const type = getWidenedTypeFromAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule); if (!popTypeResolution()) { return reportCircularityError(symbol); } @@ -5569,7 +5569,7 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); - const isJavascript = isInJavaScriptFile(location); + const isJavascript = isInJSFile(location); if (isJavascriptConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, SignatureKind.Call); } @@ -5580,7 +5580,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location); const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); - return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJavaScriptFile(location)) : sig); + return sameMap(signatures, sig => some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, isInJSFile(location)) : sig); } /** @@ -6456,7 +6456,7 @@ namespace ts { return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; // TODO: GH#18217 } const baseTypeNode = getBaseTypeNodeOfClass(classType)!; - const isJavaScript = isInJavaScriptFile(baseTypeNode); + const isJavaScript = isInJSFile(baseTypeNode); const typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode); const typeArgCount = length(typeArguments); const result: Signature[] = []; @@ -7459,7 +7459,7 @@ namespace ts { } function isJSDocOptionalParameter(node: ParameterDeclaration) { - return isInJavaScriptFile(node) && ( + return isInJSFile(node) && ( // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType node.type && node.type.kind === SyntaxKind.JSDocOptionalType || getJSDocParameterTags(node).some(({ isBracketed, typeExpression }) => @@ -7578,7 +7578,7 @@ namespace ts { const iife = getImmediatelyInvokedFunctionExpression(declaration); const isJSConstructSignature = isJSDocConstructSignature(declaration); const isUntypedSignatureInJSFile = !iife && - isInJavaScriptFile(declaration) && + isInJSFile(declaration) && isValueSignatureDeclaration(declaration) && !hasJSDocParameterTags(declaration) && !getJSDocType(declaration); @@ -7634,7 +7634,7 @@ namespace ts { getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - const hasRestLikeParameter = hasRestParameter(declaration) || isInJavaScriptFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + const hasRestLikeParameter = hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); @@ -7668,7 +7668,7 @@ namespace ts { } function getSignatureOfTypeTag(node: SignatureDeclaration | JSDocSignature) { - const typeTag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const typeTag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; const signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression)); return signature && getErasedSignature(signature); } @@ -7763,7 +7763,7 @@ namespace ts { else { const type = signature.declaration && getEffectiveReturnTypeNode(signature.declaration); let jsdocPredicate: TypePredicate | undefined; - if (!type && isInJavaScriptFile(signature.declaration)) { + if (!type && isInJSFile(signature.declaration)) { const jsdocSignature = getSignatureOfTypeTag(signature.declaration!); if (jsdocSignature && signature !== jsdocSignature) { jsdocPredicate = getTypePredicateOfSignature(jsdocSignature); @@ -7847,7 +7847,7 @@ namespace ts { return getTypeFromTypeNode(typeNode); } if (declaration.kind === SyntaxKind.GetAccessor && !hasNonBindableDynamicName(declaration)) { - const jsDocType = isInJavaScriptFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); + const jsDocType = isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration); if (jsDocType) { return jsDocType; } @@ -7924,7 +7924,7 @@ namespace ts { return getSignatureInstantiation( signature, map(signature.typeParameters, tp => tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp), - isInJavaScriptFile(signature.declaration)); + isInJSFile(signature.declaration)); } function getBaseSignature(signature: Signature) { @@ -8134,7 +8134,7 @@ namespace ts { if (typeParameters) { const numTypeArguments = length(node.typeArguments); const minTypeArgumentCount = getMinTypeArgumentCount(typeParameters); - const isJs = isInJavaScriptFile(node); + const isJs = isInJSFile(node); const isJsImplicitAny = !noImplicitAny && isJs; if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) { const missingAugmentsTag = isJs && node.parent.kind !== SyntaxKind.JSDocAugmentsTag; @@ -8168,7 +8168,7 @@ namespace ts { const id = getTypeListId(typeArguments); let instantiation = links.instantiations!.get(id); if (!instantiation) { - links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(symbol.valueDeclaration))))); + links.instantiations!.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(symbol.valueDeclaration))))); } return instantiation; } @@ -10163,7 +10163,7 @@ namespace ts { // aren't the right hand side of a generic type alias declaration we optimize by reducing the // set of type parameters to those that are possibly referenced in the literal. let declaration = symbol.declarations[0]; - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { const paramTag = findAncestor(declaration, isJSDocParameterTag); if (paramTag) { const paramSymbol = getParameterSymbolFromJSDoc(paramTag); @@ -10484,7 +10484,7 @@ namespace ts { } function isContextSensitiveFunctionOrObjectLiteralMethod(func: Node): func is FunctionExpression | ArrowFunction | MethodDeclaration { - return (isInJavaScriptFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && + return (isInJSFile(func) && isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) && isContextSensitiveFunctionLikeDeclaration(func); } @@ -15516,7 +15516,7 @@ namespace ts { if (assignmentKind) { if (!(localOrExportSymbol.flags & SymbolFlags.Variable) && - !(isInJavaScriptFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { + !(isInJSFile(node) && localOrExportSymbol.flags & SymbolFlags.ValueModule)) { error(node, Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol)); return errorType; } @@ -15817,7 +15817,7 @@ namespace ts { // Check if it's the RHS of a x.prototype.y = function [name]() { .... } if (container.kind === SyntaxKind.FunctionExpression && container.parent.kind === SyntaxKind.BinaryExpression && - getSpecialPropertyAssignmentKind(container.parent as BinaryExpression) === SpecialPropertyAssignmentKind.PrototypeProperty) { + getAssignmentDeclarationKind(container.parent as BinaryExpression) === AssignmentDeclarationKind.PrototypeProperty) { // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') const className = (((container.parent as BinaryExpression) // x.prototype.y = f .left as PropertyAccessExpression) // x.prototype.y @@ -15852,7 +15852,7 @@ namespace ts { return getFlowTypeOfReference(node, type); } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); @@ -16109,7 +16109,7 @@ namespace ts { } } } - const inJs = isInJavaScriptFile(func); + const inJs = isInJSFile(func); if (noImplicitThis || inJs) { const containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -16332,7 +16332,7 @@ namespace ts { // expression has no contextual type, the right operand is contextually typed by the type of the left operand, // except for the special case of Javascript declarations of the form `namespace.prop = namespace.prop || {}` const type = getContextualType(binaryExpression); - return !type && node === right && !isDefaultedJavascriptInitializer(binaryExpression) ? + return !type && node === right && !isDefaultedExpandoInitializer(binaryExpression) ? getTypeOfExpression(left) : type; case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.CommaToken: @@ -16343,16 +16343,16 @@ namespace ts { } // In an assignment expression, the right operand is contextually typed by the type of the left operand. - // Don't do this for special property assignments unless there is a type tag on the assignment, to avoid circularity from checking the right operand. + // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand. function getIsContextSensitiveAssignmentOrContextType(binaryExpression: BinaryExpression): boolean | Type { - const kind = getSpecialPropertyAssignmentKind(binaryExpression); + const kind = getAssignmentDeclarationKind(binaryExpression); switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: return true; - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration. // See `bindStaticPropertyAssignment` in `binder.ts`. if (!binaryExpression.left.symbol) { @@ -16380,10 +16380,10 @@ namespace ts { return false; } } - return !isInJavaScriptFile(decl); + return !isInJSFile(decl); } - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.ThisProperty: if (!binaryExpression.symbol) return true; if (binaryExpression.symbol.valueDeclaration) { const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration); @@ -16394,7 +16394,7 @@ namespace ts { } } } - if (kind === SpecialPropertyAssignmentKind.ModuleExports) return false; + if (kind === AssignmentDeclarationKind.ModuleExports) return false; const thisAccess = binaryExpression.left as PropertyAccessExpression; if (!isObjectLiteralMethod(getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) { return false; @@ -16631,7 +16631,7 @@ namespace ts { return getContextualTypeForSubstitutionExpression(parent.parent, node); case SyntaxKind.ParenthesizedExpression: { // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast. - const tag = isInJavaScriptFile(parent) ? getJSDocTypeTag(parent) : undefined; + const tag = isInJSFile(parent) ? getJSDocTypeTag(parent) : undefined; return tag ? getTypeFromTypeNode(tag.typeExpression!.type) : getContextualType(parent); } case SyntaxKind.JsxExpression: @@ -16661,7 +16661,7 @@ namespace ts { return anyType; } - const isJs = isInJavaScriptFile(node); + const isJs = isInJSFile(node); return mapType(valueType, t => getJsxSignaturesParameterTypes(t, isJs, node)); } @@ -16740,11 +16740,11 @@ namespace ts { if (managedSym) { const declaredManagedType = getDeclaredTypeOfSymbol(managedSym); if (length((declaredManagedType as GenericType).typeParameters) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], (declaredManagedType as GenericType).typeParameters, 2, isInJSFile(context)); return createTypeReference((declaredManagedType as GenericType), args); } else if (length(declaredManagedType.aliasTypeArguments) >= 2) { - const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJavaScriptFile(context)); + const args = fillMissingTypeArguments([checkExpressionCached(context.tagName), attributesType], declaredManagedType.aliasTypeArguments!, 2, isInJSFile(context)); return getTypeAliasInstantiation(declaredManagedType.aliasSymbol!, args); } } @@ -17077,9 +17077,9 @@ namespace ts { const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); - const isInJSFile = isInJavaScriptFile(node) && !isInJsonFile(node); + const isInJavascript = isInJSFile(node) && !isInJsonFile(node); const enumTag = getJSDocEnumTag(node); - const isJSObjectLiteral = !contextualType && isInJSFile && !enumTag; + const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; let typeFlags: TypeFlags = 0; let patternWithComputedProperties = false; let hasComputedStringProperty = false; @@ -17098,7 +17098,7 @@ namespace ts { let type = memberDecl.kind === SyntaxKind.PropertyAssignment ? checkPropertyAssignment(memberDecl, checkMode) : memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment ? checkExpressionForMutableLocation(memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode); - if (isInJSFile) { + if (isInJavascript) { const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl); if (jsDocType) { checkTypeAssignableTo(type, jsDocType, memberDecl); @@ -17505,7 +17505,7 @@ namespace ts { let hasTypeArgumentError: boolean = !!node.typeArguments; for (const signature of signatures) { if (signature.typeParameters) { - const isJavascript = isInJavaScriptFile(node); + const isJavascript = isInJSFile(node); const typeArgumentInstantiated = getJsxSignatureTypeArgumentInstantiation(signature, node, isJavascript, /*reportErrors*/ false); if (typeArgumentInstantiated) { hasTypeArgumentError = false; @@ -17849,7 +17849,7 @@ namespace ts { checkTypeRelatedTo(elemInstanceType, elementClassType, assignableRelation, openingLikeElement, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } - const isJs = isInJavaScriptFile(openingLikeElement); + const isJs = isInJSFile(openingLikeElement); return getUnionType(instantiatedSignatures!.map(sig => getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true))); } @@ -18107,10 +18107,10 @@ namespace ts { if (symbol.flags & SymbolFlags.Method || getCheckFlags(symbol) & CheckFlags.SyntheticMethod) { return true; } - if (isInJavaScriptFile(symbol.valueDeclaration)) { + if (isInJSFile(symbol.valueDeclaration)) { const parent = symbol.valueDeclaration.parent; return parent && isBinaryExpression(parent) && - getSpecialPropertyAssignmentKind(parent) === SpecialPropertyAssignmentKind.PrototypeProperty; + getAssignmentDeclarationKind(parent) === AssignmentDeclarationKind.PrototypeProperty; } } @@ -18593,7 +18593,7 @@ namespace ts { const prop = getPropertyOfType(type, propertyName); return prop ? checkPropertyAccessibility(node, isSuper, type, prop) // In js files properties of unions are allowed in completion - : isInJavaScriptFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); + : isInJSFile(node) && (type.flags & TypeFlags.Union) !== 0 && (type).types.some(elementType => isValidPropertyAccessWithType(node, isSuper, propertyName, elementType)); } /** @@ -18908,7 +18908,7 @@ namespace ts { if (!contextualMapper) { inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), InferencePriority.ReturnType); } - return getSignatureInstantiation(signature, getInferredTypes(context), isInJavaScriptFile(contextualSignature.declaration)); + return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration)); } function inferJsxTypeArguments(signature: Signature, node: JsxOpeningLikeElement, context: InferenceContext): Type[] { @@ -19029,7 +19029,7 @@ namespace ts { } function checkTypeArguments(signature: Signature, typeArgumentNodes: ReadonlyArray, reportErrors: boolean, headMessage?: DiagnosticMessage): Type[] | undefined { - const isJavascript = isInJavaScriptFile(signature.declaration); + const isJavascript = isInJSFile(signature.declaration); const typeParameters = signature.typeParameters!; const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript); let mapper: TypeMapper | undefined; @@ -19488,10 +19488,10 @@ namespace ts { } } else { - inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); } - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); // If the original signature has a generic rest type, instantiation may produce a // signature with different arity and we need to perform another arity check. if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) { @@ -19513,7 +19513,7 @@ namespace ts { excludeArgument = undefined; if (inferenceContext) { const typeArgumentTypes = inferTypeArguments(node, candidate, args, excludeArgument, inferenceContext); - checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJavaScriptFile(candidate.declaration)); + checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); } if (!checkApplicableSignature(node, args, checkCandidate, relation, excludeArgument, /*reportErrors*/ false)) { candidateForArgumentError = checkCandidate; @@ -19623,7 +19623,7 @@ namespace ts { const typeArgumentNodes: ReadonlyArray | undefined = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined; const instantiated = typeArgumentNodes - ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJavaScriptFile(node))) + ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args); candidates[bestIndex] = instantiated; return instantiated; @@ -19641,7 +19641,7 @@ namespace ts { } function inferSignatureInstantiationForOverloadFailure(node: CallLikeExpression, typeParameters: ReadonlyArray, candidate: Signature, args: ReadonlyArray): Signature { - const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJavaScriptFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); + const inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ isInJSFile(node) ? InferenceFlags.AnyDefault : InferenceFlags.None); const typeArgumentTypes = inferTypeArguments(node, candidate, args, getExcludeArgument(args), inferenceContext); return createSignatureInstantiation(candidate, typeArgumentTypes); } @@ -19741,7 +19741,7 @@ namespace ts { return resolveErrorCall(node); } // If the function is explicitly marked with `@class`, then it must be constructed. - if (callSignatures.some(sig => isInJavaScriptFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { + if (callSignatures.some(sig => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration!))) { error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); return resolveErrorCall(node); } @@ -20107,7 +20107,7 @@ namespace ts { * file. */ function isJavascriptConstructor(node: Declaration | undefined): boolean { - if (node && isInJavaScriptFile(node)) { + if (node && isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (getJSDocClassTag(node)) return true; @@ -20232,7 +20232,7 @@ namespace ts { } // In JavaScript files, calls to any identifier 'require' are treated as external module imports - if (isInJavaScriptFile(node) && isCommonJsRequire(node)) { + if (isInJSFile(node) && isCommonJsRequire(node)) { return resolveExternalModuleTypeByLiteral(node.arguments![0] as StringLiteral); } @@ -20243,8 +20243,8 @@ namespace ts { return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent)); } let jsAssignmentType: Type | undefined; - if (isInJavaScriptFile(node)) { - const decl = getDeclarationOfJSInitializer(node); + if (isInJSFile(node)) { + const decl = getDeclarationOfExpando(node); if (decl) { const jsSymbol = getSymbolOfNode(decl); if (jsSymbol && hasEntries(jsSymbol.exports)) { @@ -21556,7 +21556,7 @@ namespace ts { } function checkBinaryExpression(node: BinaryExpression, checkMode?: CheckMode) { - if (isInJavaScriptFile(node) && getAssignedJavascriptInitializer(node)) { + if (isInJSFile(node) && getAssignedExpandoInitializer(node)) { return checkExpression(node.right, checkMode); } return checkBinaryLikeExpression(node.left, node.operatorToken, node.right, checkMode, node); @@ -21704,9 +21704,9 @@ namespace ts { getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], UnionReduction.Subtype) : leftType; case SyntaxKind.EqualsToken: - const special = isBinaryExpression(left.parent) ? getSpecialPropertyAssignmentKind(left.parent) : SpecialPropertyAssignmentKind.None; - checkSpecialAssignment(special, right); - if (isJSSpecialPropertyAssignment(special)) { + const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None; + checkAssignmentDeclaration(declKind, right); + if (isAssignmentDeclaration(declKind)) { return leftType; } else { @@ -21723,8 +21723,8 @@ namespace ts { return Debug.fail(); } - function checkSpecialAssignment(special: SpecialPropertyAssignmentKind, right: Expression) { - if (special === SpecialPropertyAssignmentKind.ModuleExports) { + function checkAssignmentDeclaration(kind: AssignmentDeclarationKind, right: Expression) { + if (kind === AssignmentDeclarationKind.ModuleExports) { const rightType = checkExpression(right, checkMode); for (const prop of getPropertiesOfObjectType(rightType)) { const propType = getTypeOfSymbol(prop); @@ -21791,17 +21791,17 @@ namespace ts { } } - function isJSSpecialPropertyAssignment(special: SpecialPropertyAssignmentKind) { - switch (special) { - case SpecialPropertyAssignmentKind.ModuleExports: + function isAssignmentDeclaration(kind: AssignmentDeclarationKind) { + switch (kind) { + case AssignmentDeclarationKind.ModuleExports: return true; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.Prototype: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.Prototype: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.ThisProperty: const symbol = getSymbolOfNode(left); - const init = getAssignedJavascriptInitializer(right); + const init = getAssignedExpandoInitializer(right); return init && isObjectLiteralExpression(init) && symbol && hasEntries(symbol.exports); default: @@ -21977,7 +21977,7 @@ namespace ts { const widened = getCombinedNodeFlags(declaration) & NodeFlags.Const || isDeclarationReadonly(declaration) || isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); - if (isInJavaScriptFile(declaration)) { + if (isInJSFile(declaration)) { if (widened.flags & TypeFlags.Nullable) { if (noImplicitAny) { reportImplicitAnyError(declaration, anyType); @@ -22153,7 +22153,7 @@ namespace ts { } function checkParenthesizedExpression(node: ParenthesizedExpression, checkMode?: CheckMode): Type { - const tag = isInJavaScriptFile(node) ? getJSDocTypeTag(node) : undefined; + const tag = isInJSFile(node) ? getJSDocTypeTag(node) : undefined; if (tag) { return checkAssertionWorker(tag, tag.typeExpression!.type, node.expression, checkMode); } @@ -22830,7 +22830,7 @@ namespace ts { function getEffectiveTypeArguments(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): Type[] { return fillMissingTypeArguments(map(node.typeArguments!, getTypeFromTypeNode), typeParameters, - getMinTypeArgumentCount(typeParameters), isInJavaScriptFile(node)); + getMinTypeArgumentCount(typeParameters), isInJSFile(node)); } function checkTypeArgumentConstraints(node: TypeReferenceNode | ExpressionWithTypeArguments, typeParameters: ReadonlyArray): boolean { @@ -22868,7 +22868,7 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJavaScriptFile(node) && !isInJSDoc(node)) { + if (node.kind === SyntaxKind.TypeReference && node.typeName.jsdocDotPos !== undefined && !isInJSFile(node) && !isInJSDoc(node)) { grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } const type = getTypeFromTypeReference(node); @@ -24016,7 +24016,7 @@ namespace ts { } // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const typeTag = getJSDocTypeTag(node); if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) { error(typeTag, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature); @@ -24673,7 +24673,7 @@ namespace ts { // Don't validate for-in initializer as it is already an error const initializer = getEffectiveInitializer(node); if (initializer) { - const isJSObjectLiteralInitializer = isInJavaScriptFile(node) && + const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && hasEntries(symbol.exports); @@ -24690,7 +24690,7 @@ namespace ts { if (type !== errorType && declarationType !== errorType && !isTypeIdenticalTo(type, declarationType) && - !(symbol.flags & SymbolFlags.JSContainer)) { + !(symbol.flags & SymbolFlags.Assignment)) { errorNextVariableOrPropertyDeclarationMustHaveSameType(type, node, declarationType); } if (node.initializer) { @@ -26771,7 +26771,7 @@ namespace ts { const exportEqualsSymbol = moduleSymbol.exports!.get("export=" as __String); if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; - if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJavaScriptFile(declaration)) { + if (!isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) { error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } @@ -26821,7 +26821,7 @@ namespace ts { return; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { forEach((node as JSDocContainer).jsDoc, ({ tags }) => forEach(tags, checkSourceElement)); } @@ -26988,7 +26988,7 @@ namespace ts { } function checkJSDocTypeIsInJsFile(node: Node): void { - if (!isInJavaScriptFile(node)) { + if (!isInJSFile(node)) { grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments); } } @@ -27410,14 +27410,14 @@ namespace ts { } function getSpecialPropertyAssignmentSymbolFromEntityName(entityName: EntityName | PropertyAccessExpression) { - const specialPropertyAssignmentKind = getSpecialPropertyAssignmentKind(entityName.parent.parent as BinaryExpression); + const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent as BinaryExpression); switch (specialPropertyAssignmentKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.PrototypeProperty: return getSymbolOfNode(entityName.parent); - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.Property: return getSymbolOfNode(entityName.parent.parent); } } @@ -27439,7 +27439,7 @@ namespace ts { return getSymbolOfNode(entityName.parent); } - if (isInJavaScriptFile(entityName) && + if (isInJSFile(entityName) && entityName.parent.kind === SyntaxKind.PropertyAccessExpression && entityName.parent === (entityName.parent.parent as BinaryExpression).left) { // Check if this is a special property assignment @@ -27504,7 +27504,7 @@ namespace ts { } if (entityName.parent.kind === SyntaxKind.TypeParameter && entityName.parent.parent.kind === SyntaxKind.JSDocTemplateTag) { - Debug.assert(!isInJavaScriptFile(entityName)); // Otherwise `isDeclarationName` would have been true. + Debug.assert(!isInJSFile(entityName)); // Otherwise `isDeclarationName` would have been true. const typeParameter = getTypeParameterFromJsDoc(entityName.parent as TypeParameterDeclaration & { parent: JSDocTemplateTag }); return typeParameter && typeParameter.symbol; } @@ -27631,7 +27631,7 @@ namespace ts { // 4). type A = import("./f/*gotToDefinitionHere*/oo") if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) || ((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent).moduleSpecifier === node) || - ((isInJavaScriptFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || + ((isInJSFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) || (isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) ) { return resolveExternalModuleName(node, node); @@ -28145,7 +28145,7 @@ namespace ts { hasModifier(parameter, ModifierFlags.ParameterPropertyModifier); } - function isJSContainerFunctionDeclaration(node: Declaration): boolean { + function isExpandoFunctionDeclaration(node: Declaration): boolean { const declaration = getParseTreeNode(node, isFunctionDeclaration); if (!declaration) { return false; @@ -28407,7 +28407,7 @@ namespace ts { isImplementationOfOverload, isRequiredInitializedParameter, isOptionalUninitializedParameterProperty, - isJSContainerFunctionDeclaration, + isExpandoFunctionDeclaration, getPropertiesOfContainerFunction, createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration, @@ -29910,7 +29910,7 @@ namespace ts { } function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { - const jsdocTypeParameters = isInJavaScriptFile(node) && getJSDocTypeParameterDeclarations(node); + const jsdocTypeParameters = isInJSFile(node) && getJSDocTypeParameterDeclarations(node); if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { const { pos, end } = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node; return grammarErrorAtPos(node, pos, end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 55e690f8ae8..2d103b8af8f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -52,7 +52,7 @@ namespace ts { const jsFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options)); const sourceMapFilePath = isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options); // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const declarationFilePath = ((forceDtsPaths || getEmitDeclarations(options)) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined; const declarationMapPath = getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined; return { jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, bundleInfoPath: undefined }; @@ -80,7 +80,7 @@ namespace ts { } if (options.jsx === JsxEmit.Preserve) { - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) { return Extension.Jsx; } @@ -187,12 +187,12 @@ namespace ts { } function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined, declarationMapPath: string | undefined) { - if (!(declarationFilePath && !isInJavaScriptFile(sourceFileOrBundle))) { + if (!(declarationFilePath && !isInJSFile(sourceFileOrBundle))) { return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - const nonJsFiles = filter(sourceFiles, isSourceFileNotJavaScript); + const nonJsFiles = filter(sourceFiles, isSourceFileNotJavascript); const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index bae4dbfa430..aedd1d4c3dc 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -778,7 +778,7 @@ namespace ts { * Throws an error if the module can't be resolved. */ /* @internal */ - export function resolveJavaScriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + export function resolveJavascriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { const { resolvedModule, failedLookupLocations } = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); if (!resolvedModule) { @@ -958,7 +958,7 @@ namespace ts { // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (hasJavaScriptFileExtension(candidate)) { + if (hasJavascriptFileExtension(candidate)) { const extensionless = removeFileExtension(candidate); if (state.traceEnabled) { const extension = candidate.substring(extensionless.length); diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index cb19dcde1e2..6033d95b2a5 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers { function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences { return { relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative, - ending: hasJavaScriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension + ending: hasJavascriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, }; } @@ -148,7 +148,7 @@ namespace ts.moduleSpecifiers { } function usesJsExtensionOnImports({ imports }: SourceFile): boolean { - return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavaScriptOrJsonFileExtension(text) : undefined) || false; + return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavascriptOrJsonFileExtension(text) : undefined) || false; } function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean { @@ -415,13 +415,13 @@ namespace ts.moduleSpecifiers { case Ending.Index: return noExtension; case Ending.JsExtension: - return noExtension + getJavaScriptExtensionForFile(fileName, options); + return noExtension + getJavascriptExtensionForFile(fileName, options); default: return Debug.assertNever(ending); } } - function getJavaScriptExtensionForFile(fileName: string, options: CompilerOptions): Extension { + function getJavascriptExtensionForFile(fileName: string, options: CompilerOptions): Extension { const ext = extensionFromPath(fileName); switch (ext) { case Extension.Ts: diff --git a/src/compiler/program.ts b/src/compiler/program.ts index c24f570819e..61bf38db805 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1438,9 +1438,9 @@ namespace ts { function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): ReadonlyArray { // For JavaScript files, we report semantic errors for using TypeScript-only // constructs from within a JavaScript file as syntactic errors. - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJavascriptSyntacticDiagnosticsForFile(sourceFile); } return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -1538,7 +1538,7 @@ namespace ts { return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { + function getJavascriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { return runWithCancellationToken(() => { const diagnostics: DiagnosticWithLocation[] = []; let parent: Node = sourceFile; @@ -1801,7 +1801,7 @@ namespace ts { return; } - const isJavaScriptFile = isSourceFileJavaScript(file); + const isJavaScriptFile = isSourceFileJS(file); const isExternalModuleFile = isExternalModule(file); // file.imports may not be undefined if there exists dynamic import @@ -2295,7 +2295,7 @@ namespace ts { && i < file.imports.length && !elideImport && !(isJsFile && !options.allowJs) - && (isInJavaScriptFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); + && (isInJSFile(file.imports[i]) || !(file.imports[i].flags & NodeFlags.JSDoc)); if (elideImport) { modulesWithElidedImports.set(file.path, true); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 49e89417ca0..14e7900b0da 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1,11 +1,11 @@ /*@internal*/ namespace ts { export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): DiagnosticWithLocation[] | undefined { - if (file && isSourceFileJavaScript(file)) { + if (file && isSourceFileJS(file)) { return []; // No declaration diagnostics for js for now } const compilerOptions = host.getCompilerOptions(); - const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavascript), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } @@ -157,7 +157,7 @@ namespace ts { function transformRoot(node: SourceFile): SourceFile; function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle; function transformRoot(node: SourceFile | Bundle) { - if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJavaScript(node))) { + if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJS(node))) { return node; } @@ -168,7 +168,7 @@ namespace ts { let hasNoDefaultLib = false; const bundle = createBundle(map(node.sourceFiles, sourceFile => { - if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 + if (sourceFile.isDeclarationFile || isSourceFileJS(sourceFile)) return undefined!; // Omit declaration files from bundle results, too // TODO: GH#18217 hasNoDefaultLib = hasNoDefaultLib || sourceFile.hasNoDefaultLib; currentSourceFile = sourceFile; enclosingDeclaration = sourceFile; @@ -303,7 +303,7 @@ namespace ts { } function collectReferences(sourceFile: SourceFile, ret: Map) { - if (noResolve || isSourceFileJavaScript(sourceFile)) return ret; + if (noResolve || isSourceFileJS(sourceFile)) return ret; forEach(sourceFile.referencedFiles, f => { const elem = tryResolveScriptReference(host, sourceFile, f); if (elem) { @@ -989,7 +989,7 @@ namespace ts { ensureType(input, input.type), /*body*/ undefined )); - if (clean && resolver.isJSContainerFunctionDeclaration(input)) { + if (clean && resolver.isExpandoFunctionDeclaration(input)) { const declarations = mapDefined(resolver.getPropertiesOfContainerFunction(input), p => { if (!isPropertyAccessExpression(p.valueDeclaration)) { return undefined; diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 418185b4c16..3692e9ca057 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -302,7 +302,7 @@ namespace ts { return changeExtension(outputPath, Extension.Dts); } - function getOutputJavaScriptFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOutputJavascriptFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json : @@ -317,7 +317,7 @@ namespace ts { } const outputs: string[] = []; - const js = getOutputJavaScriptFileName(inputFileName, configFile); + const js = getOutputJavascriptFileName(inputFileName, configFile); outputs.push(js); if (configFile.options.sourceMap) { outputs.push(`${js}.map`); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 279fef73d5e..a0d07e00591 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3383,7 +3383,7 @@ namespace ts { isImplementationOfOverload(node: FunctionLike): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; - isJSContainerFunctionDeclaration(node: FunctionDeclaration): boolean; + isExpandoFunctionDeclaration(node: FunctionDeclaration): boolean; getPropertiesOfContainerFunction(node: Declaration): Symbol[]; createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration | PropertyAccessExpression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode | undefined; createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode | undefined; @@ -3435,7 +3435,7 @@ namespace ts { ExportStar = 1 << 23, // Export * declaration Optional = 1 << 24, // Optional property Transient = 1 << 25, // Transient symbol (created during type check) - JSContainer = 1 << 26, // Contains Javascript special declarations + Assignment = 1 << 26, // Assignment treated as declaration (eg `this.prop = 1`) ModuleExports = 1 << 27, // Symbol for CommonJS `module` of `module.exports` /* @internal */ @@ -3444,8 +3444,8 @@ namespace ts { Enum = RegularEnum | ConstEnum, Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | JSContainer, - Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | JSContainer, + Value = Variable | Property | EnumMember | ObjectLiteral | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor | Assignment, + Type = Class | Interface | Enum | EnumMember | TypeLiteral | TypeParameter | TypeAlias | Assignment, Namespace = ValueModule | NamespaceModule | Enum, Module = ValueModule | NamespaceModule, Accessor = GetAccessor | SetAccessor, @@ -3466,7 +3466,7 @@ namespace ts { InterfaceExcludes = Type & ~(Interface | Class), RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums - ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | JSContainer), + ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule | Assignment), NamespaceModuleExcludes = 0, MethodExcludes = Value & ~Method, GetAccessorExcludes = Value & ~SetAccessor, @@ -4219,7 +4219,7 @@ namespace ts { } /* @internal */ - export const enum SpecialPropertyAssignmentKind { + export const enum AssignmentDeclarationKind { None, /// exports.name = expr ExportsProperty, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 18b45d682db..1efbd278aed 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1678,15 +1678,15 @@ namespace ts { return node.kind === SyntaxKind.ImportEqualsDeclaration && (node).moduleReference.kind !== SyntaxKind.ExternalModuleReference; } - export function isSourceFileJavaScript(file: SourceFile): boolean { - return isInJavaScriptFile(file); + export function isSourceFileJS(file: SourceFile): boolean { + return isInJSFile(file); } - export function isSourceFileNotJavaScript(file: SourceFile): boolean { - return !isInJavaScriptFile(file); + export function isSourceFileNotJavascript(file: SourceFile): boolean { + return !isInJSFile(file); } - export function isInJavaScriptFile(node: Node | undefined): boolean { + export function isInJSFile(node: Node | undefined): boolean { return !!node && !!(node.flags & NodeFlags.JavaScriptFile); } @@ -1738,14 +1738,14 @@ namespace ts { return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === CharacterCodes.doubleQuote; } - export function getDeclarationOfJSInitializer(node: Node): Node | undefined { + export function getDeclarationOfExpando(node: Node): Node | undefined { if (!node.parent) { return undefined; } let name: Expression | BindingName | undefined; let decl: Node | undefined; if (isVariableDeclaration(node.parent) && node.parent.initializer === node) { - if (!isInJavaScriptFile(node) && !isVarConst(node.parent)) { + if (!isInJSFile(node) && !isVarConst(node.parent)) { return undefined; } name = node.parent.name; @@ -1770,7 +1770,7 @@ namespace ts { } } - if (!name || !getJavascriptInitializer(node, isPrototypeAccess(name))) { + if (!name || !getExpandoInitializer(node, isPrototypeAccess(name))) { return undefined; } return decl; @@ -1782,7 +1782,7 @@ namespace ts { /** Get the initializer, taking into account defaulted Javascript initializers */ export function getEffectiveInitializer(node: HasExpressionInitializer) { - if (isInJavaScriptFile(node) && node.initializer && + if (isInJSFile(node) && node.initializer && isBinaryExpression(node.initializer) && node.initializer.operatorToken.kind === SyntaxKind.BarBarToken && node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) { return node.initializer.right; @@ -1790,26 +1790,26 @@ namespace ts { return node.initializer; } - /** Get the declaration initializer when it is container-like (See getJavascriptInitializer). */ - export function getDeclaredJavascriptInitializer(node: HasExpressionInitializer) { + /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */ + export function getDeclaredExpandoInitializer(node: HasExpressionInitializer) { const init = getEffectiveInitializer(node); - return init && getJavascriptInitializer(init, isPrototypeAccess(node.name)); + return init && getExpandoInitializer(init, isPrototypeAccess(node.name)); } /** - * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getJavascriptInitializer). + * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - export function getAssignedJavascriptInitializer(node: Node) { + export function getAssignedExpandoInitializer(node: Node) { if (node && node.parent && isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken) { const isPrototypeAssignment = isPrototypeAccess(node.parent.left); - return getJavascriptInitializer(node.parent.right, isPrototypeAssignment) || - getDefaultedJavascriptInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); + return getExpandoInitializer(node.parent.right, isPrototypeAssignment) || + getDefaultedExpandoInitializer(node.parent.left as EntityNameExpression, node.parent.right, isPrototypeAssignment); } } /** - * Recognized Javascript container-like initializers are: + * Recognized expando initializers are: * 1. (function() {})() -- IIFEs * 2. function() { } -- Function expressions * 3. class { } -- Class expressions @@ -1818,7 +1818,7 @@ namespace ts { * * This function returns the provided initializer, or undefined if it is not valid. */ - export function getJavascriptInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { + export function getExpandoInitializer(initializer: Node, isPrototypeAssignment: boolean): Expression | undefined { if (isCallExpression(initializer)) { const e = skipParentheses(initializer.expression); return e.kind === SyntaxKind.FunctionExpression || e.kind === SyntaxKind.ArrowFunction ? initializer : undefined; @@ -1834,29 +1834,29 @@ namespace ts { } /** - * A defaulted Javascript initializer matches the pattern - * `Lhs = Lhs || JavascriptInitializer` - * or `var Lhs = Lhs || JavascriptInitializer` + * A defaulted expando initializer matches the pattern + * `Lhs = Lhs || ExpandoInitializer` + * or `var Lhs = Lhs || ExpandoInitializer` * * The second Lhs is required to be the same as the first except that it may be prefixed with * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker. */ - function getDefaultedJavascriptInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { - const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getJavascriptInitializer(initializer.right, isPrototypeAssignment); + function getDefaultedExpandoInitializer(name: EntityNameExpression, initializer: Expression, isPrototypeAssignment: boolean) { + const e = isBinaryExpression(initializer) && initializer.operatorToken.kind === SyntaxKind.BarBarToken && getExpandoInitializer(initializer.right, isPrototypeAssignment); if (e && isSameEntityName(name, (initializer as BinaryExpression).left as EntityNameExpression)) { return e; } } - export function isDefaultedJavascriptInitializer(node: BinaryExpression) { + export function isDefaultedExpandoInitializer(node: BinaryExpression) { const name = isVariableDeclaration(node.parent) ? node.parent.name : isBinaryExpression(node.parent) && node.parent.operatorToken.kind === SyntaxKind.EqualsToken ? node.parent.left : undefined; - return name && getJavascriptInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); + return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left); } - /** Given a Javascript initializer, return the outer name. That is, the lhs of the assignment or the declaration name. */ - export function getOuterNameOfJsInitializer(node: Declaration): DeclarationName | undefined { + /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */ + export function getNameOfExpando(node: Declaration): DeclarationName | undefined { if (isBinaryExpression(node.parent)) { const parent = (node.parent.operatorToken.kind === SyntaxKind.BarBarToken && isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent; if (parent.operatorToken.kind === SyntaxKind.EqualsToken && isIdentifier(parent.left)) { @@ -1912,36 +1912,36 @@ namespace ts { /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - export function getSpecialPropertyAssignmentKind(expr: BinaryExpression): SpecialPropertyAssignmentKind { - const special = getSpecialPropertyAssignmentKindWorker(expr); - return special === SpecialPropertyAssignmentKind.Property || isInJavaScriptFile(expr) ? special : SpecialPropertyAssignmentKind.None; + export function getAssignmentDeclarationKind(expr: BinaryExpression): AssignmentDeclarationKind { + const special = getAssignmentDeclarationKindWorker(expr); + return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None; } - function getSpecialPropertyAssignmentKindWorker(expr: BinaryExpression): SpecialPropertyAssignmentKind { + function getAssignmentDeclarationKindWorker(expr: BinaryExpression): AssignmentDeclarationKind { if (expr.operatorToken.kind !== SyntaxKind.EqualsToken || !isPropertyAccessExpression(expr.left)) { - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } const lhs = expr.left; if (isEntityNameExpression(lhs.expression) && lhs.name.escapedText === "prototype" && isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) { // F.prototype = { ... } - return SpecialPropertyAssignmentKind.Prototype; + return AssignmentDeclarationKind.Prototype; } - return getSpecialPropertyAccessKind(lhs); + return getAssignmentDeclarationPropertyAccessKind(lhs); } - export function getSpecialPropertyAccessKind(lhs: PropertyAccessExpression): SpecialPropertyAssignmentKind { + export function getAssignmentDeclarationPropertyAccessKind(lhs: PropertyAccessExpression): AssignmentDeclarationKind { if (lhs.expression.kind === SyntaxKind.ThisKeyword) { - return SpecialPropertyAssignmentKind.ThisProperty; + return AssignmentDeclarationKind.ThisProperty; } else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { // module.exports = expr - return SpecialPropertyAssignmentKind.ModuleExports; + return AssignmentDeclarationKind.ModuleExports; } else if (isEntityNameExpression(lhs.expression)) { if (isPrototypeAccess(lhs.expression)) { // F.G....prototype.x = expr - return SpecialPropertyAssignmentKind.PrototypeProperty; + return AssignmentDeclarationKind.PrototypeProperty; } let nextToLast = lhs; @@ -1953,13 +1953,13 @@ namespace ts { if (id.escapedText === "exports" || id.escapedText === "module" && nextToLast.name.escapedText === "exports") { // exports.name = expr OR module.exports.name = expr - return SpecialPropertyAssignmentKind.ExportsProperty; + return AssignmentDeclarationKind.ExportsProperty; } // F.G...x = expr - return SpecialPropertyAssignmentKind.Property; + return AssignmentDeclarationKind.Property; } - return SpecialPropertyAssignmentKind.None; + return AssignmentDeclarationKind.None; } export function getInitializerOfBinaryExpression(expr: BinaryExpression) { @@ -1970,11 +1970,11 @@ namespace ts { } export function isPrototypePropertyAssignment(node: Node): boolean { - return isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.PrototypeProperty; + return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.PrototypeProperty; } export function isSpecialPropertyDeclaration(expr: PropertyAccessExpression): boolean { - return isInJavaScriptFile(expr) && + return isInJSFile(expr) && expr.parent && expr.parent.kind === SyntaxKind.ExpressionStatement && !!getJSDocTypeTag(expr.parent); } @@ -2082,7 +2082,7 @@ namespace ts { function getSourceOfDefaultedAssignment(node: Node): Node | undefined { return isExpressionStatement(node) && isBinaryExpression(node.expression) && - getSpecialPropertyAssignmentKind(node.expression) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(node.expression) !== AssignmentDeclarationKind.None && isBinaryExpression(node.expression.right) && node.expression.right.operatorToken.kind === SyntaxKind.BarBarToken ? node.expression.right.right @@ -2402,7 +2402,7 @@ namespace ts { else { const binExp = parent.parent; return isBinaryExpression(binExp) && - getSpecialPropertyAssignmentKind(binExp) !== SpecialPropertyAssignmentKind.None && + getAssignmentDeclarationKind(binExp) !== AssignmentDeclarationKind.None && (binExp.left.symbol || binExp.symbol) && getNameOfDeclaration(binExp) === name ? binExp @@ -2471,7 +2471,7 @@ namespace ts { node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || - isBinaryExpression(node) && getSpecialPropertyAssignmentKind(node) === SpecialPropertyAssignmentKind.ModuleExports; + isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports; } export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean { @@ -2480,7 +2480,7 @@ namespace ts { } export function getEffectiveBaseTypeNode(node: ClassLikeDeclaration | InterfaceDeclaration) { - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { // Prefer an @augments tag because it may have type parameters. const tag = getJSDocAugmentsTag(node); if (tag) { @@ -3286,7 +3286,7 @@ namespace ts { /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */ export function sourceFileMayBeEmitted(sourceFile: SourceFile, options: CompilerOptions, isSourceFileFromExternalLibrary: (file: SourceFile) => boolean) { - return !(options.noEmitForJsFiles && isSourceFileJavaScript(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); + return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) && !sourceFile.isDeclarationFile && !isSourceFileFromExternalLibrary(sourceFile); } export function getSourceFilePathInNewDir(fileName: string, host: EmitHost, newDirPath: string): string { @@ -3410,7 +3410,7 @@ namespace ts { */ export function getEffectiveTypeAnnotationNode(node: Node): TypeNode | undefined { const type = (node as HasType).type; - if (type || !isInJavaScriptFile(node)) return type; + if (type || !isInJSFile(node)) return type; return isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : getJSDocType(node); } @@ -3425,7 +3425,7 @@ namespace ts { export function getEffectiveReturnTypeNode(node: SignatureDeclaration | JSDocSignature): TypeNode | undefined { return isJSDocSignature(node) ? node.type && node.type.typeExpression && node.type.typeExpression.type : - node.type || (isInJavaScriptFile(node) ? getJSDocReturnType(node) : undefined); + node.type || (isInJSFile(node) ? getJSDocReturnType(node) : undefined); } export function getJSDocTypeParameterDeclarations(node: DeclarationWithTypeParameters): ReadonlyArray { @@ -4986,11 +4986,11 @@ namespace ts { } case SyntaxKind.BinaryExpression: { const expr = declaration as BinaryExpression; - switch (getSpecialPropertyAssignmentKind(expr)) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.PrototypeProperty: + switch (getAssignmentDeclarationKind(expr)) { + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.PrototypeProperty: return (expr.left as PropertyAccessExpression).name; default: return undefined; @@ -5207,7 +5207,7 @@ namespace ts { if (node.typeParameters) { return node.typeParameters; } - if (isInJavaScriptFile(node)) { + if (isInJSFile(node)) { const decls = getJSDocTypeParameterDeclarations(node); if (decls.length) { return decls; @@ -6613,7 +6613,7 @@ namespace ts { /* @internal */ export function isDeclaration(node: Node): node is NamedDeclaration { if (node.kind === SyntaxKind.TypeParameter) { - return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJavaScriptFile(node); + return node.parent.kind !== SyntaxKind.JSDocTemplateTag || isInJSFile(node); } return isDeclarationKind(node.kind); @@ -8010,42 +8010,42 @@ namespace ts { /** * List of supported extensions in order of file resolution precedence. */ - export const supportedTypeScriptExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTypescriptExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; export const supportedJavascriptExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; - export const supportedJavaScriptAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; - const allSupportedExtensions: ReadonlyArray = [...supportedTypeScriptExtensions, ...supportedJavascriptExtensions]; + export const supportedJavascriptAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; + const allSupportedExtensions: ReadonlyArray = [...supportedTypescriptExtensions, ...supportedJavascriptExtensions]; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions; + return needJsExtensions ? allSupportedExtensions : supportedTypescriptExtensions; } const extensions = [ - ...needJsExtensions ? allSupportedExtensions : supportedTypeScriptExtensions, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavaScriptLike(x.scriptKind) ? x.extension : undefined) + ...needJsExtensions ? allSupportedExtensions : supportedTypescriptExtensions, + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavascriptLike(x.scriptKind) ? x.extension : undefined) ]; return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } - function isJavaScriptLike(scriptKind: ScriptKind | undefined): boolean { + function isJavascriptLike(scriptKind: ScriptKind | undefined): boolean { return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX; } - export function hasJavaScriptFileExtension(fileName: string): boolean { + export function hasJavascriptFileExtension(fileName: string): boolean { return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension)); } - export function hasJavaScriptOrJsonFileExtension(fileName: string): boolean { - return supportedJavaScriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); + export function hasJavascriptOrJsonFileExtension(fileName: string): boolean { + return supportedJavascriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); } - export function hasTypeScriptFileExtension(fileName: string): boolean { - return some(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasTypescriptFileExtension(fileName: string): boolean { + return some(supportedTypescriptExtensions, extension => fileExtensionIs(fileName, extension)); } export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index fa9c88d3ffa..abb03babc8d 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -268,7 +268,7 @@ namespace Harness.LanguageService { getHost(): LanguageServiceAdapterHost { return this.host; } getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } getClassifier(): ts.Classifier { return ts.createClassifier(); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavaScriptFileExtension(fileName)); } + getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavascriptFileExtension(fileName)); } } /// Shim adapter diff --git a/src/harness/vpath.ts b/src/harness/vpath.ts index 6211fc9278a..f21ee7fb6bb 100644 --- a/src/harness/vpath.ts +++ b/src/harness/vpath.ts @@ -21,8 +21,8 @@ namespace vpath { export import relative = ts.getRelativePathFromDirectory; export import beneath = ts.containsPath; export import changeExtension = ts.changeAnyExtension; - export import isTypeScript = ts.hasTypeScriptFileExtension; - export import isJavaScript = ts.hasJavaScriptFileExtension; + export import isTypeScript = ts.hasTypescriptFileExtension; + export import isJavaScript = ts.hasJavascriptFileExtension; const invalidRootComponentRegExp = /^(?!(\/|\/\/\w+\/|[a-zA-Z]:\/?|)$)/; const invalidNavigableComponentRegExp = /[:*?"<>|]/; @@ -133,4 +133,4 @@ namespace vpath { export function isTsConfigFile(path: string): boolean { return path.indexOf("tsconfig") !== -1 && path.indexOf("json") !== -1; } -} \ No newline at end of file +} diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index db55ce4993b..3b1868aea84 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -122,7 +122,7 @@ namespace ts.JsTyping { // Only infer typings for .js and .jsx files fileNames = mapDefined(fileNames, fileName => { const path = normalizePath(fileName); - if (hasJavaScriptFileExtension(path)) { + if (hasJavascriptFileExtension(path)) { return path; } }); @@ -218,7 +218,7 @@ namespace ts.JsTyping { */ function getTypingNamesFromSourceFileNames(fileNames: string[]) { const fromFileNames = mapDefined(fileNames, j => { - if (!hasJavaScriptFileExtension(j)) return undefined; + if (!hasJavascriptFileExtension(j)) return undefined; const inferredTypingName = removeFileExtension(getBaseFileName(j.toLowerCase())); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index ddbfd8ac389..b1f88dff3b7 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1447,14 +1447,14 @@ namespace ts.server { for (const f of fileNames) { const fileName = propertyReader.getFileName(f); - if (hasTypeScriptFileExtension(fileName)) { + if (hasTypescriptFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader, hasTypeScriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader, hasTypescriptFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -1464,14 +1464,14 @@ namespace ts.server { return; - function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { + function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTypescriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { const files = getTop5LargestFiles(context); return `Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${files.map(file => `${file.name}:${file.size}`).join(", ")}`; } - function getTop5LargestFiles({ propertyReader, hasTypeScriptFileExtension, host }: { propertyReader: FilePropertyReader, hasTypeScriptFileExtension: (filename: string) => boolean, host: ServerHost }) { + function getTop5LargestFiles({ propertyReader, hasTypescriptFileExtension, host }: { propertyReader: FilePropertyReader, hasTypescriptFileExtension: (filename: string) => boolean, host: ServerHost }) { return fileNames.map(f => propertyReader.getFileName(f)) - .filter(name => hasTypeScriptFileExtension(name)) + .filter(name => hasTypescriptFileExtension(name)) .map(name => ({ name, size: host.getFileSize!(name) })) // TODO: GH#18217 .sort((a, b) => b.size - a.size) .slice(0, 5); diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 085dd6d0eef..5c4eaa9a374 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -167,7 +167,7 @@ namespace ts.server { const fileName = tempFileName || this.fileName; const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text; // Only non typescript files have size limitation - if (!hasTypeScriptFileExtension(this.fileName)) { + if (!hasTypescriptFileExtension(this.fileName)) { const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > maxFileSize) { Debug.assert(!!this.info.containingProjects.length); diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index c2041179888..78e10ce2044 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -138,7 +138,7 @@ namespace ts.codefix { default: { // Don't try to declare members in JavaScript files - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { return; } const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 76cdf471466..e8e24b40a0c 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -61,12 +61,12 @@ namespace ts.codefix { const synthNamesMap: Map = createMap(); const originalTypeMap: Map = createMap(); const allVarNames: SymbolAndIdentifier[] = []; - const isInJSFile = isInJavaScriptFile(functionToConvert); + const isInJavascript = isInJSFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); const constIdentifiers = getConstIdentifiers(synthNamesMap); const returnStatements = getReturnStatementsWithPromiseHandlers(functionToConvertRenamed); - const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile }; + const transformer = { checker, synthNamesMap, allVarNames, setOfExpressionsToReturn, constIdentifiers, originalTypeMap, isInJSFile: isInJavascript }; if (!returnStatements.length) { return; @@ -546,4 +546,4 @@ namespace ts.codefix { return node.original ? node.original : node; } } -} \ No newline at end of file +} diff --git a/src/services/codefixes/disableJsDiagnostics.ts b/src/services/codefixes/disableJsDiagnostics.ts index c81446152dd..4cdd7eb42d2 100644 --- a/src/services/codefixes/disableJsDiagnostics.ts +++ b/src/services/codefixes/disableJsDiagnostics.ts @@ -12,7 +12,7 @@ namespace ts.codefix { getCodeActions(context) { const { sourceFile, program, span, host, formatContext } = context; - if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { + if (!isInJSFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index a23cb621608..dda0903562a 100644 --- a/src/services/codefixes/fixAddMissingMember.ts +++ b/src/services/codefixes/fixAddMissingMember.ts @@ -20,7 +20,7 @@ namespace ts.codefix { const { parentDeclaration, declSourceFile, inJs, makeStatic, token, call } = info; const methodCodeAction = call && getActionForMethodDeclaration(context, declSourceFile, parentDeclaration, token, call, makeStatic, inJs, context.preferences); const addMember = inJs && !isInterfaceDeclaration(parentDeclaration) ? - singleElementArray(getActionsForAddMissingMemberInJavaScriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : + singleElementArray(getActionsForAddMissingMemberInJavascriptFile(context, declSourceFile, parentDeclaration, token.text, makeStatic)) : getActionsForAddMissingMemberInTypeScriptFile(context, declSourceFile, parentDeclaration, token, makeStatic); return concatenate(singleElementArray(methodCodeAction), addMember); }, @@ -131,7 +131,7 @@ namespace ts.codefix { if (classOrInterface) { const makeStatic = ((leftExpressionType as TypeReference).target || leftExpressionType) !== checker.getDeclaredTypeOfSymbol(symbol); const declSourceFile = classOrInterface.getSourceFile(); - const inJs = isSourceFileJavaScript(declSourceFile); + const inJs = isSourceFileJS(declSourceFile); const call = tryCast(parent.parent, isCallExpression); return { kind: InfoKind.ClassOrInterface, token, parentDeclaration: classOrInterface, makeStatic, declSourceFile, inJs, call }; } @@ -142,7 +142,7 @@ namespace ts.codefix { return undefined; } - function getActionsForAddMissingMemberInJavaScriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { + function getActionsForAddMissingMemberInJavascriptFile(context: CodeFixContext, declSourceFile: SourceFile, classDeclaration: ClassLikeDeclaration, tokenName: string, makeStatic: boolean): CodeFixAction | undefined { const changes = textChanges.ChangeTracker.with(context, t => addMissingMemberInJs(t, declSourceFile, classDeclaration, tokenName, makeStatic)); return changes.length === 0 ? undefined : createCodeFixAction(fixName, changes, [makeStatic ? Diagnostics.Initialize_static_property_0 : Diagnostics.Initialize_property_0_in_the_constructor, tokenName], fixId, Diagnostics.Add_all_missing_members); diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 963d1cd64f2..578f55f5c68 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -267,7 +267,7 @@ namespace ts.codefix { function getExistingImportDeclarations({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }: SymbolExportInfo, checker: TypeChecker, sourceFile: SourceFile): ReadonlyArray { // Can't use an es6 import for a type in JS. - return exportedSymbolIsTypeOnly && isSourceFileJavaScript(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { + return exportedSymbolIsTypeOnly && isSourceFileJS(sourceFile) ? emptyArray : mapDefined(sourceFile.imports, moduleSpecifier => { const i = importFromModuleSpecifier(moduleSpecifier); return (i.kind === SyntaxKind.ImportDeclaration || i.kind === SyntaxKind.ImportEqualsDeclaration) && checker.getSymbolAtLocation(moduleSpecifier) === moduleSymbol ? { declaration: i, importKind } : undefined; @@ -282,7 +282,7 @@ namespace ts.codefix { host: LanguageServiceHost, preferences: UserPreferences, ): ReadonlyArray { - const isJs = isSourceFileJavaScript(sourceFile); + const isJs = isSourceFileJS(sourceFile); const choicesForEachExportingModule = flatMap(moduleSymbols, ({ moduleSymbol, importKind, exportedSymbolIsTypeOnly }) => moduleSpecifiers.getModuleSpecifiers(moduleSymbol, program.getCompilerOptions(), sourceFile, host, program.getSourceFiles(), preferences, program.redirectTargetsMap) .map((moduleSpecifier): FixAddNewImport | FixUseImportType => diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 17b3469f0bf..f924208e321 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -26,7 +26,7 @@ namespace ts.codefix { errorCodes, getCodeActions(context) { const { sourceFile, program, span: { start }, errorCode, cancellationToken } = context; - if (isSourceFileJavaScript(sourceFile)) { + if (isSourceFileJS(sourceFile)) { return undefined; // TODO: GH#20113 } diff --git a/src/services/completions.ts b/src/services/completions.ts index 61e424c43ec..ff8c3147824 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -134,7 +134,7 @@ namespace ts.Completions { if (isUncheckedFile(sourceFile, compilerOptions)) { const uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target!, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); - getJavaScriptCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 + getJSCompletionEntries(sourceFile, location!.pos, uniqueNames, compilerOptions.target!, entries); // TODO: GH#18217 } else { if ((!symbols || symbols.length === 0) && keywordFilters === KeywordCompletionFilters.None) { @@ -161,7 +161,7 @@ namespace ts.Completions { } function isUncheckedFile(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean { - return isSourceFileJavaScript(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); + return isSourceFileJS(sourceFile) && !isCheckJsEnabledForFile(sourceFile, compilerOptions); } function isMemberCompletionKind(kind: CompletionKind): boolean { @@ -175,7 +175,7 @@ namespace ts.Completions { } } - function getJavaScriptCompletionEntries( + function getJSCompletionEntries( sourceFile: SourceFile, position: number, uniqueNames: Map, diff --git a/src/services/importTracker.ts b/src/services/importTracker.ts index 77b3c02c80b..86bee92eaec 100644 --- a/src/services/importTracker.ts +++ b/src/services/importTracker.ts @@ -502,11 +502,11 @@ namespace ts.FindAllReferences { function getSpecialPropertyExport(node: BinaryExpression, useLhsSymbol: boolean): ExportedSymbol | undefined { let kind: ExportKind; - switch (getSpecialPropertyAssignmentKind(node)) { - case SpecialPropertyAssignmentKind.ExportsProperty: + switch (getAssignmentDeclarationKind(node)) { + case AssignmentDeclarationKind.ExportsProperty: kind = ExportKind.Named; break; - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ModuleExports: kind = ExportKind.ExportEquals; break; default: diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index d9fa8446b13..641eb643f92 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -312,7 +312,7 @@ namespace ts.JsDoc { const preamble = "/**" + newLine + indentationStr + " * "; const result = preamble + newLine + - parameterDocComments(parameters, hasJavaScriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, hasJavascriptFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); @@ -383,7 +383,7 @@ namespace ts.JsDoc { case SyntaxKind.BinaryExpression: { const be = commentOwner as BinaryExpression; - if (getSpecialPropertyAssignmentKind(be) === SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(be) === AssignmentDeclarationKind.None) { return "quit"; } const parameters = isFunctionLike(be.right) ? be.right.parameters : emptyArray; diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 504311a4a2d..ab7c4327bb5 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -270,17 +270,17 @@ namespace ts.NavigationBar { break; case SyntaxKind.BinaryExpression: { - const special = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const special = getAssignmentDeclarationKind(node as BinaryExpression); switch (special) { - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: - case SpecialPropertyAssignmentKind.PrototypeProperty: - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: + case AssignmentDeclarationKind.PrototypeProperty: + case AssignmentDeclarationKind.Prototype: addNodeWithRecursiveChild(node, (node as BinaryExpression).right); return; - case SpecialPropertyAssignmentKind.ThisProperty: - case SpecialPropertyAssignmentKind.Property: - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.ThisProperty: + case AssignmentDeclarationKind.Property: + case AssignmentDeclarationKind.None: break; default: Debug.assertNever(special); diff --git a/src/services/refactors/extractSymbol.ts b/src/services/refactors/extractSymbol.ts index 93baf2b4209..96b5ba18070 100644 --- a/src/services/refactors/extractSymbol.ts +++ b/src/services/refactors/extractSymbol.ts @@ -719,7 +719,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted function const file = scope.getSourceFile(); const functionNameText = getUniqueName(isClassLike(scope) ? "newMethod" : "newFunction", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const functionName = createIdentifier(functionNameText); @@ -1006,7 +1006,7 @@ namespace ts.refactor.extractSymbol { // Make a unique name for the extracted variable const file = scope.getSourceFile(); const localNameText = getUniqueName(isClassLike(scope) ? "newProperty" : "newLocal", file); - const isJS = isInJavaScriptFile(scope); + const isJS = isInJSFile(scope); const variableType = isJS || !checker.isContextSensitive(node) ? undefined @@ -1424,7 +1424,7 @@ namespace ts.refactor.extractSymbol { if (expressionDiagnostic) { constantErrors.push(expressionDiagnostic); } - if (isClassLike(scope) && isInJavaScriptFile(scope)) { + if (isClassLike(scope) && isInJSFile(scope)) { constantErrors.push(createDiagnosticForNode(scope, Messages.cannotExtractToJSClass)); } if (isArrowFunction(scope) && !isBlock(scope.body)) { diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index e39eb20f8d8..57b25445f5d 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -41,7 +41,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { const fieldInfo = getConvertibleFieldAtPosition(context); if (!fieldInfo) return undefined; - const isJS = isSourceFileJavaScript(file); + const isJS = isSourceFileJS(file); const changeTracker = textChanges.ChangeTracker.fromContext(context); const { isStatic, isReadonly, fieldName, accessorName, originalName, type, container, declaration, renameAccessor } = fieldInfo; diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 9953293e3d1..8b6af714892 100644 --- a/src/services/refactors/moveToNewFile.ts +++ b/src/services/refactors/moveToNewFile.ts @@ -657,7 +657,7 @@ namespace ts.refactor { case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; - return isBinaryExpression(expression) && getSpecialPropertyAssignmentKind(expression) === SpecialPropertyAssignmentKind.ExportsProperty + return isBinaryExpression(expression) && getAssignmentDeclarationKind(expression) === AssignmentDeclarationKind.ExportsProperty ? cb(statement as TopLevelExpressionStatement) : undefined; } diff --git a/src/services/services.ts b/src/services/services.ts index dcc321b00d5..7f2ac2bcc81 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -760,7 +760,7 @@ namespace ts { break; case SyntaxKind.BinaryExpression: - if (getSpecialPropertyAssignmentKind(node as BinaryExpression) !== SpecialPropertyAssignmentKind.None) { + if (getAssignmentDeclarationKind(node as BinaryExpression) !== AssignmentDeclarationKind.None) { addDeclaration(node as BinaryExpression); } // falls through diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index b6174be75e0..29a2b728db2 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -50,7 +50,7 @@ namespace ts.SignatureHelp { if (!candidateInfo) { // We didn't have any sig help items produced by the TS compiler. If this is a JS // file, then see if we can figure out anything better. - return isSourceFileJavaScript(sourceFile) ? createJavaScriptSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; + return isSourceFileJS(sourceFile) ? createJSSignatureHelpItems(argumentInfo, program, cancellationToken) : undefined; } return typeChecker.runWithCancellationToken(cancellationToken, typeChecker => @@ -115,7 +115,7 @@ namespace ts.SignatureHelp { } } - function createJavaScriptSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { + function createJSSignatureHelpItems(argumentInfo: ArgumentListInfo, program: Program, cancellationToken: CancellationToken): SignatureHelpItems | undefined { if (argumentInfo.invocation.kind === InvocationKind.Contextual) return undefined; // See if we can find some symbol with the call expression name that has call signatures. const expression = getExpressionFromInvocation(argumentInfo.invocation); diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 167bcb6bbac..d4aec1b1c6f 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -11,7 +11,7 @@ namespace ts { diags.push(createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } - const isJsFile = isSourceFileJavaScript(sourceFile); + const isJsFile = isSourceFileJS(sourceFile); check(sourceFile); @@ -36,7 +36,7 @@ namespace ts { if (isJsFile) { switch (node.kind) { case SyntaxKind.FunctionExpression: - const decl = getDeclarationOfJSInitializer(node); + const decl = getDeclarationOfExpando(node); if (decl) { const symbol = decl.symbol; if (symbol && (symbol.exports && symbol.exports.size || symbol.members && symbol.members.size)) { @@ -86,8 +86,8 @@ namespace ts { case SyntaxKind.ExpressionStatement: { const { expression } = statement as ExpressionStatement; if (!isBinaryExpression(expression)) return isRequireCall(expression, /*checkArgumentIsStringLiteralLike*/ true); - const kind = getSpecialPropertyAssignmentKind(expression); - return kind === SpecialPropertyAssignmentKind.ExportsProperty || kind === SpecialPropertyAssignmentKind.ModuleExports; + const kind = getAssignmentDeclarationKind(expression); + return kind === AssignmentDeclarationKind.ExportsProperty || kind === AssignmentDeclarationKind.ModuleExports; } default: return false; diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 1c10bc983fd..40a9936b605 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -355,23 +355,23 @@ namespace ts { case SyntaxKind.NamespaceImport: return ScriptElementKind.alias; case SyntaxKind.BinaryExpression: - const kind = getSpecialPropertyAssignmentKind(node as BinaryExpression); + const kind = getAssignmentDeclarationKind(node as BinaryExpression); const { right } = node as BinaryExpression; switch (kind) { - case SpecialPropertyAssignmentKind.None: + case AssignmentDeclarationKind.None: return ScriptElementKind.unknown; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ModuleExports: + case AssignmentDeclarationKind.ExportsProperty: + case AssignmentDeclarationKind.ModuleExports: const rightKind = getNodeKind(right); return rightKind === ScriptElementKind.unknown ? ScriptElementKind.constElement : rightKind; - case SpecialPropertyAssignmentKind.PrototypeProperty: + case AssignmentDeclarationKind.PrototypeProperty: return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.ThisProperty: + case AssignmentDeclarationKind.ThisProperty: return ScriptElementKind.memberVariableElement; // property - case SpecialPropertyAssignmentKind.Property: + case AssignmentDeclarationKind.Property: // static method / property return isFunctionExpression(right) ? ScriptElementKind.memberFunctionElement : ScriptElementKind.memberVariableElement; - case SpecialPropertyAssignmentKind.Prototype: + case AssignmentDeclarationKind.Prototype: return ScriptElementKind.localClassElement; default: { assertType(kind); diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index 7a9e4278c57..e12e60e49ea 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -83,7 +83,7 @@ namespace ts { describe("Node module resolution - relative paths", () => { function testLoadAsFile(containingFileName: string, moduleFileNameNoExt: string, moduleName: string): void { - for (const ext of supportedTypeScriptExtensions) { + for (const ext of supportedTypescriptExtensions) { test(ext, /*hasDirectoryExists*/ false); test(ext, /*hasDirectoryExists*/ true); } @@ -96,7 +96,7 @@ namespace ts { const failedLookupLocations: string[] = []; const dir = getDirectoryPath(containingFileName); - for (const e of supportedTypeScriptExtensions) { + for (const e of supportedTypescriptExtensions) { if (e === ext) { break; } @@ -137,7 +137,7 @@ namespace ts { const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile)); checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); // expect three failed lookup location - attempt to load module as file with all supported extensions - assert.equal(resolution.failedLookupLocations.length, supportedTypeScriptExtensions.length); + assert.equal(resolution.failedLookupLocations.length, supportedTypescriptExtensions.length); } } diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 95b228f6e96..9c05bf0cf16 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -891,7 +891,7 @@ namespace ts.server { sys.require = (initialDir: string, moduleName: string): RequireResult => { try { - return { module: require(resolveJavaScriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(resolveJavascriptModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error }; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 672b93e55da..9465a512a1f 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2059,7 +2059,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 5d093382f54..66ba75bbd93 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2059,7 +2059,7 @@ declare namespace ts { ExportStar = 8388608, Optional = 16777216, Transient = 33554432, - JSContainer = 67108864, + Assignment = 67108864, ModuleExports = 134217728, Enum = 384, Variable = 3, From 2f8a646f8e5bb0331c4b52b4596806894817994a Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 12 Sep 2018 12:21:50 -0700 Subject: [PATCH 100/146] isExpandoFunctionDeclaration only checks values (#27052) Previously it checked types too, which caused a crash because types don't have valueDeclaration set. But expando functions can't export types, only values. --- src/compiler/checker.ts | 2 +- .../reference/declarationEmitOfFuncspace.js | 23 +++++++++++++++++++ .../declarationEmitOfFuncspace.symbols | 16 +++++++++++++ .../declarationEmitOfFuncspace.types | 13 +++++++++++ .../compiler/declarationEmitOfFuncspace.ts | 9 ++++++++ 5 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/declarationEmitOfFuncspace.js create mode 100644 tests/baselines/reference/declarationEmitOfFuncspace.symbols create mode 100644 tests/baselines/reference/declarationEmitOfFuncspace.types create mode 100644 tests/cases/compiler/declarationEmitOfFuncspace.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 974c74029eb..6bd0c0409d4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -28154,7 +28154,7 @@ namespace ts { if (!symbol || !(symbol.flags & SymbolFlags.Function)) { return false; } - return !!forEachEntry(getExportsOfSymbol(symbol), p => isPropertyAccessExpression(p.valueDeclaration)); + return !!forEachEntry(getExportsOfSymbol(symbol), p => p.flags & SymbolFlags.Value && isPropertyAccessExpression(p.valueDeclaration)); } function getPropertiesOfContainerFunction(node: Declaration): Symbol[] { diff --git a/tests/baselines/reference/declarationEmitOfFuncspace.js b/tests/baselines/reference/declarationEmitOfFuncspace.js new file mode 100644 index 00000000000..5a60a51d7e6 --- /dev/null +++ b/tests/baselines/reference/declarationEmitOfFuncspace.js @@ -0,0 +1,23 @@ +//// [expando.ts] +// #27032 +function ExpandoMerge(n: number) { + return n; +} +namespace ExpandoMerge { + export interface I { } +} + + +//// [expando.js] +// #27032 +function ExpandoMerge(n) { + return n; +} + + +//// [expando.d.ts] +declare function ExpandoMerge(n: number): number; +declare namespace ExpandoMerge { + interface I { + } +} diff --git a/tests/baselines/reference/declarationEmitOfFuncspace.symbols b/tests/baselines/reference/declarationEmitOfFuncspace.symbols new file mode 100644 index 00000000000..cd86d57ae68 --- /dev/null +++ b/tests/baselines/reference/declarationEmitOfFuncspace.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/expando.ts === +// #27032 +function ExpandoMerge(n: number) { +>ExpandoMerge : Symbol(ExpandoMerge, Decl(expando.ts, 0, 0), Decl(expando.ts, 3, 1)) +>n : Symbol(n, Decl(expando.ts, 1, 22)) + + return n; +>n : Symbol(n, Decl(expando.ts, 1, 22)) +} +namespace ExpandoMerge { +>ExpandoMerge : Symbol(ExpandoMerge, Decl(expando.ts, 0, 0), Decl(expando.ts, 3, 1)) + + export interface I { } +>I : Symbol(I, Decl(expando.ts, 4, 24)) +} + diff --git a/tests/baselines/reference/declarationEmitOfFuncspace.types b/tests/baselines/reference/declarationEmitOfFuncspace.types new file mode 100644 index 00000000000..030ffa34a58 --- /dev/null +++ b/tests/baselines/reference/declarationEmitOfFuncspace.types @@ -0,0 +1,13 @@ +=== tests/cases/compiler/expando.ts === +// #27032 +function ExpandoMerge(n: number) { +>ExpandoMerge : (n: number) => number +>n : number + + return n; +>n : number +} +namespace ExpandoMerge { + export interface I { } +} + diff --git a/tests/cases/compiler/declarationEmitOfFuncspace.ts b/tests/cases/compiler/declarationEmitOfFuncspace.ts new file mode 100644 index 00000000000..9648178ae81 --- /dev/null +++ b/tests/cases/compiler/declarationEmitOfFuncspace.ts @@ -0,0 +1,9 @@ +// @declaration: true +// @Filename: expando.ts +// #27032 +function ExpandoMerge(n: number) { + return n; +} +namespace ExpandoMerge { + export interface I { } +} From 5553f36c9da286befeeee8250fc8668dc8c4ed21 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 12 Sep 2018 12:30:48 -0700 Subject: [PATCH 101/146] Instead of queueing build for downstream projects right when invalidating project, do it after build for invalidated project is complete --- src/compiler/tsbuild.ts | 49 +++++++++++++---------------- src/testRunner/unittests/tsbuild.ts | 18 ++++++++++- 2 files changed, 38 insertions(+), 29 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 1aaa3e07f1c..415e04adae9 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -783,10 +783,7 @@ namespace ts { diagnostics.removeKey(resolved); } - if (addProjToQueue(resolved, reloadLevel)) { - // TODO: instead of adding the dependent project to queue right away postpone this - queueBuildForDownstreamReferences(resolved); - } + addProjToQueue(resolved, reloadLevel); } /** @@ -797,10 +794,8 @@ namespace ts { if (value === undefined) { projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); invalidatedProjectQueue.push(proj); - return true; } - - if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { + else if (value < (reloadLevel || ConfigFileProgramReloadLevel.None)) { projectPendingBuild.setValue(proj, reloadLevel || ConfigFileProgramReloadLevel.None); } } @@ -823,20 +818,6 @@ namespace ts { return !!projectPendingBuild.getSize(); } - // Mark all downstream projects of this one needing to be built "later" - function queueBuildForDownstreamReferences(root: ResolvedConfigFileName) { - const dependencyGraph = getGlobalDependencyGraph(); - const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(root); - if (!referencingProjects) return; - // Always use build order to queue projects - for (const project of dependencyGraph.buildQueue) { - // Can skip circular references - if (referencingProjects.hasKey(project) && addProjToQueue(project)) { - queueBuildForDownstreamReferences(project); - } - } - } - function scheduleBuildInvalidatedProject() { if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) { return; @@ -910,7 +891,20 @@ namespace ts { return; } - buildSingleProject(resolved); + const buildResult = buildSingleProject(resolved); + // If declaration output changed then only queue in build for downstream projects + if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + const dependencyGraph = getGlobalDependencyGraph(); + const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; + // Always use build order to queue projects + for (const project of dependencyGraph.buildQueue) { + // Can skip circular references + if (referencingProjects.hasKey(project)) { + addProjToQueue(project); + } + } + } } function createDependencyGraph(roots: ResolvedConfigFileName[]): DependencyGraph { @@ -928,7 +922,7 @@ namespace ts { referencingProjectsMap }; - function visit(projPath: ResolvedConfigFileName, inCircularContext = false) { + function visit(projPath: ResolvedConfigFileName, inCircularContext?: boolean) { // Already visited if (permanentMarks.hasKey(projPath)) return; // Circular @@ -1032,14 +1026,13 @@ namespace ts { let anyDtsChanged = false; program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => { let priorChangeTime: Date | undefined; - - if (!anyDtsChanged && isDeclarationFile(fileName) && host.fileExists(fileName)) { - if (host.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + if (!anyDtsChanged && isDeclarationFile(fileName)) { + // Check for unchanged .d.ts files + if (host.fileExists(fileName) && host.readFile(fileName) === content) { priorChangeTime = host.getModifiedTime(fileName); } else { + resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index a9993aabc40..6ddd6d069f7 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -210,10 +210,26 @@ namespace ts { assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + // Does not build tests or core because there is no change in declaration file + tick(); + builder.buildInvalidatedProject(); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); + + // Rebuild this project + tick(); + fs.writeFileSync("/src/logic/index.ts", `${fs.readFileSync("/src/logic/index.ts")} +export class cNew {}`); + builder.invalidateProject("/src/logic"); + builder.buildInvalidatedProject(); + // The file should be updated + assert.equal(fs.statSync("/src/logic/index.js").mtimeMs, time(), "JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should *not* have been rebuilt"); + // Build downstream projects should update 'tests', but not 'core' tick(); builder.buildInvalidatedProject(); - assert.equal(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); + assert.isBelow(fs.statSync("/src/tests/index.js").mtimeMs, time(), "Downstream JS file should have been rebuilt"); assert.isBelow(fs.statSync("/src/core/index.js").mtimeMs, time(), "Upstream JS file should not have been rebuilt"); }); }); From 906fbae37b2310dcb3b5d1bc3b36c763cd957846 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Wed, 12 Sep 2018 14:47:06 -0700 Subject: [PATCH 102/146] Handle promise handler block bodies with no return and other cleanup --- .../codefixes/convertToAsyncFunction.ts | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index d8d6fa05d1f..235f50226eb 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -82,7 +82,7 @@ namespace ts.codefix { } for (const statement of returnStatements) { - forEachChild(statement, function visit(node: Node) { + forEachChild(statement, function visit(node) { if (isCallExpression(node)) { startTransformation(node, statement); } @@ -179,7 +179,7 @@ namespace ts.codefix { // Note - the choice of the last call signature is arbitrary if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { const name = lastCallSignature.parameters[0].name; - const synthName = getNewNameIfConflict(createIdentifier(lastCallSignature.parameters[0].name), allVarNames); + const synthName = getNewNameIfConflict(createIdentifier(name), allVarNames); synthNamesMap.set(symbolIdString, synthName); allVarNames.push({ identifier: synthName.identifier, symbol, originalName: name }); } @@ -404,8 +404,13 @@ namespace ts.codefix { // Arrow functions with block bodies { } will enter this control flow if (isFunctionLikeDeclaration(func) && func.body && isBlock(func.body) && func.body.statements) { let refactoredStmts: Statement[] = []; + let seenReturnStatement = false; for (const statement of func.body.statements) { + if (isReturnStatement(statement)) { + seenReturnStatement = true; + } + if (getReturnStatementsWithPromiseHandlers(statement).length) { refactoredStmts = refactoredStmts.concat(getInnerTransformationBody(transformer, [statement], prevArgName)); } @@ -415,7 +420,7 @@ namespace ts.codefix { } return shouldReturn ? getSynthesizedDeepClones(createNodeArray(refactoredStmts)) : - removeReturns(createNodeArray(refactoredStmts), prevArgName!.identifier, transformer.constIdentifiers); + removeReturns(createNodeArray(refactoredStmts), prevArgName!.identifier, transformer.constIdentifiers, seenReturnStatement); } else { const funcBody = (func).body; @@ -443,12 +448,12 @@ namespace ts.codefix { } function getLastCallSignature(type: Type, checker: TypeChecker): Signature | undefined { - const callSignatures = type && checker.getSignaturesOfType(type, SignatureKind.Call); + const callSignatures = checker.getSignaturesOfType(type, SignatureKind.Call); return callSignatures && callSignatures[callSignatures.length - 1]; } - function removeReturns(stmts: NodeArray, prevArgName: Identifier, constIdentifiers: Identifier[]): NodeArray { + function removeReturns(stmts: NodeArray, prevArgName: Identifier, constIdentifiers: Identifier[], seenReturnStatement: boolean): NodeArray { const ret: Statement[] = []; for (const stmt of stmts) { if (isReturnStatement(stmt)) { @@ -462,6 +467,12 @@ namespace ts.codefix { } } + // if block has no return statement, need to define prevArgName as undefined to prevent undeclared variables + if (!seenReturnStatement) { + ret.push(createVariableStatement(/*modifiers*/ undefined, + (createVariableDeclarationList([createVariableDeclaration(prevArgName, /*type*/ undefined, createIdentifier("undefined"))], getFlagOfIdentifier(prevArgName, constIdentifiers))))); + } + return createNodeArray(ret); } From 95e5f7d55a5a75581093024b5c8419625db2ff9b Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Wed, 12 Sep 2018 14:47:13 -0700 Subject: [PATCH 103/146] Add and update tests --- .../unittests/convertToAsyncFunction.ts | 9 +++++++++ ...vertToAsyncFunction_InnerVarNameConflict.ts | 1 + .../convertToAsyncFunction_bindingPattern.ts | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index d1655824216..f774c58de94 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1198,6 +1198,15 @@ const [#|foo|] = function () { function [#|f|]() { return Promise.resolve().then(x => 1).catch(x => "a").then(x => !!x); } +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` +function [#|f|]():Promise { + return fetch('https://typescriptlang.org').then(res); +} +function res({ status, trailer }){ + console.log(status); +} `); }); diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts index 119d9d408bb..72e4a66fb55 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_InnerVarNameConflict.ts @@ -13,5 +13,6 @@ function /*[#|*/f/*|]*/(): Promise { async function f(): Promise { const resp = await fetch("https://typescriptlang.org"); var blob = resp.blob().then(blob_1 => blob_1.byteOffset).catch(err => 'Error'); + const blob_2 = undefined; return blob_2.toString(); } diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts new file mode 100644 index 00000000000..f7d26faa980 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts @@ -0,0 +1,18 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/():Promise { + return fetch('https://typescriptlang.org').then(res); +} +function res({ status, trailer }){ + console.log(status); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f():Promise { + const __0 = await fetch('https://typescriptlang.org'); + return res(__0); +} +function res({ status, trailer }){ + console.log(status); +} From ef2024a487e2178f8978e7a7cefc4db92becdb0d Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 12 Sep 2018 14:58:08 -0700 Subject: [PATCH 104/146] Handle circular project references --- src/compiler/tsbuild.ts | 20 ++- src/testRunner/unittests/tsbuildWatchMode.ts | 143 +++++++++++-------- 2 files changed, 99 insertions(+), 64 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 415e04adae9..763c62deccf 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -61,6 +61,7 @@ namespace ts { OutOfDateWithUpstream, UpstreamOutOfDate, UpstreamBlocked, + ComputingUpstream, /** * Projects with no outputs (i.e. "solution" files) @@ -76,6 +77,7 @@ namespace ts { | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked + | Status.ComputingUpstream | Status.ContainerOnly; export namespace Status { @@ -145,6 +147,13 @@ namespace ts { upstreamProjectName: string; } + /** + * Computing status of upstream projects referenced + */ + export interface ComputingUpstream { + type: UpToDateStatusType.ComputingUpstream; + } + /** * One or more of the project's outputs is older than the newest output of * an upstream project. @@ -689,11 +698,17 @@ namespace ts { let usesPrepend = false; let upstreamChangedProject: string | undefined; if (project.projectReferences) { + projectStatus.setValue(project.options.configFilePath as ResolvedConfigFileName, { type: UpToDateStatusType.ComputingUpstream }); for (const ref of project.projectReferences) { usesPrepend = usesPrepend || !!(ref.prepend); const resolvedRef = resolveProjectReferencePath(ref); const refStatus = getUpToDateStatus(parseConfigFile(resolvedRef)); + // Its a circular reference ignore the status of this project + if (refStatus.type === UpToDateStatusType.ComputingUpstream) { + continue; + } + // An upstream project is blocked if (refStatus.type === UpToDateStatusType.Unbuildable) { return { @@ -928,9 +943,10 @@ namespace ts { // Circular if (temporaryMarks.hasKey(projPath)) { if (!inCircularContext) { + // TODO:: Do we report this as error? reportStatus(Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")); - return; } + return; } temporaryMarks.setValue(projPath, true); @@ -1263,6 +1279,8 @@ namespace ts { status.reason); case UpToDateStatusType.ContainerOnly: // Don't report status on "solution" projects + case UpToDateStatusType.ComputingUpstream: + // Should never leak from getUptoDateStatusWorker break; default: assertType(status); diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index e2abd2a0d04..17e61140b2d 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -95,7 +95,7 @@ namespace ts.tscWatch { const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); - function createSolutionInWatchMode() { + function createSolutionInWatchMode(allFiles: ReadonlyArray) { const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); verifyWatches(host); @@ -114,7 +114,7 @@ namespace ts.tscWatch { } it("creates solution in watch mode", () => { - createSolutionInWatchMode(); + createSolutionInWatchMode(allFiles); }); describe("validates the changes and watched files", () => { @@ -124,82 +124,99 @@ namespace ts.tscWatch { content: `export const newFileConst = 30;` }; - function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { - const host = createSolutionInWatchMode(); - return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; + function verifyProjectChanges(allFiles: ReadonlyArray) { + function createSolutionInWatchModeToVerifyChanges(additionalFiles?: ReadonlyArray<[SubProject, string]>) { + const host = createSolutionInWatchMode(allFiles); + return { host, verifyChangeWithFile, verifyChangeAfterTimeout, verifyWatches }; - function verifyChangeWithFile(fileName: string, content: string) { - const outputFileStamps = getOutputFileStamps(host, additionalFiles); - host.writeFile(fileName, content); - verifyChangeAfterTimeout(outputFileStamps); + function verifyChangeWithFile(fileName: string, content: string) { + const outputFileStamps = getOutputFileStamps(host, additionalFiles); + host.writeFile(fileName, content); + verifyChangeAfterTimeout(outputFileStamps); + } + + function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedLogic, changedCore, [ + ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function verifyWatches() { + checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); + } } - function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { - host.checkTimeoutQueueLengthAndRun(1); // Builds core - const changedCore = getOutputFileStamps(host, additionalFiles); - verifyChangedFiles(changedCore, outputFileStamps, [ - ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really - ...getOutputFileNames(SubProject.core, "index"), - ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) - ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds logic - const changedLogic = getOutputFileStamps(host, additionalFiles); - verifyChangedFiles(changedLogic, changedCore, [ - ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written - ]); - host.checkTimeoutQueueLengthAndRun(1); // Builds tests - const changedTests = getOutputFileStamps(host, additionalFiles); - verifyChangedFiles(changedTests, changedLogic, [ - ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written - ]); - host.checkTimeoutQueueLength(0); - checkOutputErrorsIncremental(host, emptyArray); - verifyWatches(); - } - - function verifyWatches() { - checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles); - checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); - } - } - - it("change builds changes and reports found errors message", () => { - const { host, verifyChangeWithFile, verifyChangeAfterTimeout } = createSolutionInWatchModeToVerifyChanges(); - verifyChange(`${core[1].content} + it("change builds changes and reports found errors message", () => { + const { host, verifyChangeWithFile, verifyChangeAfterTimeout } = createSolutionInWatchModeToVerifyChanges(); + verifyChange(`${core[1].content} export class someClass { }`); - // Another change requeues and builds it - verifyChange(core[1].content); + // Another change requeues and builds it + verifyChange(core[1].content); - // Two changes together report only single time message: File change detected. Starting incremental compilation... - const outputFileStamps = getOutputFileStamps(host); - const change1 = `${core[1].content} + // Two changes together report only single time message: File change detected. Starting incremental compilation... + const outputFileStamps = getOutputFileStamps(host); + const change1 = `${core[1].content} export class someClass { }`; - host.writeFile(core[1].path, change1); - host.writeFile(core[1].path, `${change1} + host.writeFile(core[1].path, change1); + host.writeFile(core[1].path, `${change1} export class someClass2 { }`); - verifyChangeAfterTimeout(outputFileStamps); + verifyChangeAfterTimeout(outputFileStamps); - function verifyChange(coreContent: string) { - verifyChangeWithFile(core[1].path, coreContent); - } - }); + function verifyChange(coreContent: string) { + verifyChangeWithFile(core[1].path, coreContent); + } + }); - it("builds when new file is added, and its subsequent updates", () => { - const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; - const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); - verifyChange(newFile.content); + it("builds when new file is added, and its subsequent updates", () => { + const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; + const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); + verifyChange(newFile.content); - // Another change requeues and builds it - verifyChange(`${newFile.content} + // Another change requeues and builds it + verifyChange(`${newFile.content} export class someClass2 { }`); - function verifyChange(newFileContent: string) { - verifyChangeWithFile(newFile.path, newFileContent); - } + function verifyChange(newFileContent: string) { + verifyChangeWithFile(newFile.path, newFileContent); + } + }); + } + + describe("with simple project reference graph", () => { + verifyProjectChanges(allFiles); }); + describe("with circular project reference", () => { + const [coreTsconfig, ...otherCoreFiles] = core; + const circularCoreConfig: File = { + path: coreTsconfig.path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true }, + references: [{ path: "../tests", circular: true }] + }) + }; + verifyProjectChanges([libFile, circularCoreConfig, ...otherCoreFiles, ...logic, ...tests]); + }); }); it("watches config files that are not present", () => { From 0319f103f231cc69a667fc7ec20b298ffd268872 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 12 Sep 2018 15:05:20 -0700 Subject: [PATCH 105/146] Test case to verify the non local change doesnt build referencing projects --- src/testRunner/unittests/tsbuildWatchMode.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 17e61140b2d..12c82becef3 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -187,6 +187,22 @@ export class someClass2 { }`); } }); + it("non local change does not start build of referencing projects", () => { + const host = createSolutionInWatchMode(allFiles); + const outputFileStamps = getOutputFileStamps(host); + host.writeFile(core[1].path, `${core[1].content} +function foo() { }`); + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + it("builds when new file is added, and its subsequent updates", () => { const additinalFiles: ReadonlyArray<[SubProject, string]> = [[SubProject.core, newFileWithoutExtension]]; const { verifyChangeWithFile } = createSolutionInWatchModeToVerifyChanges(additinalFiles); From 5696384a9fd23d5fcbc93e8bd80eb791f0962ab9 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 12 Sep 2018 15:38:23 -0700 Subject: [PATCH 106/146] Handle prepend output to be emitted in downstream project even if declaration file doesnt change --- src/compiler/tsbuild.ts | 28 ++++---- src/testRunner/unittests/tsbuildWatchMode.ts | 75 ++++++++++++++++++++ 2 files changed, 89 insertions(+), 14 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 763c62deccf..d7eb648bca2 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -13,7 +13,8 @@ namespace ts { interface DependencyGraph { buildQueue: ResolvedConfigFileName[]; - referencingProjectsMap: ConfigFileMap>; + /** value in config File map is true if project is referenced using prepend */ + referencingProjectsMap: ConfigFileMap>; } export interface BuildOptions { @@ -907,17 +908,16 @@ namespace ts { } const buildResult = buildSingleProject(resolved); - // If declaration output changed then only queue in build for downstream projects - if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { - const dependencyGraph = getGlobalDependencyGraph(); - const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); - if (!referencingProjects) return; - // Always use build order to queue projects - for (const project of dependencyGraph.buildQueue) { - // Can skip circular references - if (referencingProjects.hasKey(project)) { - addProjToQueue(project); - } + const dependencyGraph = getGlobalDependencyGraph(); + const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; + // Always use build order to queue projects + for (const project of dependencyGraph.buildQueue) { + const prepend = referencingProjects.getValue(project); + // If the project is referenced with prepend, always build downstream projectm, + // otherwise queue it only if declaration output changed + if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + addProjToQueue(project); } } } @@ -927,7 +927,7 @@ namespace ts { const permanentMarks = createFileMap(toPath); const circularityReportStack: string[] = []; const buildOrder: ResolvedConfigFileName[] = []; - const referencingProjectsMap = createFileMap>(toPath); + const referencingProjectsMap = createFileMap>(toPath); for (const root of roots) { visit(root); } @@ -958,7 +958,7 @@ namespace ts { visit(resolvedRefPath, inCircularContext || ref.circular); // Get projects referencing resolvedRefPath and add projPath to it const referencingProjects = getOrCreateValueFromConfigFileMap(referencingProjectsMap, resolvedRefPath, () => createFileMap(toPath)); - referencingProjects.setValue(projPath, true); + referencingProjects.setValue(projPath, !!ref.prepend); } } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 12c82becef3..697d14f72ba 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -276,6 +276,81 @@ export class someClass2 { }`); verifyWatches(host); }); + it("when referenced using prepend, builds referencing project even for non local change", () => { + const coreTsConfig: File = { + path: core[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" } + }) + }; + const coreIndex: File = { + path: core[1].path, + content: `function foo() { return 10; }` + }; + const logicTsConfig: File = { + path: logic[0].path, + content: JSON.stringify({ + compilerOptions: { composite: true, declaration: true, outFile: "index.js" }, + references: [{ path: "../core", prepend: true }] + }) + }; + const logicIndex: File = { + path: logic[1].path, + content: `function bar() { return foo() + 1 };` + }; + + const projectFiles = [coreTsConfig, coreIndex, logicTsConfig, logicIndex]; + const host = createWatchedSystem([libFile, ...projectFiles], { currentDirectory: projectsLocation }); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.logic}`]); + verifyWatches(); + checkOutputErrorsInitial(host, emptyArray); + const outputFileStamps = getOutputFileStamps(); + for (const stamp of outputFileStamps) { + assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); + } + + // Make non local change + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 10; }`); + + // Make local change to function bar + verifyChangeInCore(`${coreIndex.content} +function myFunc() { return 100; }`); + + function verifyChangeInCore(content: string) { + const outputFileStamps = getOutputFileStamps(); + host.writeFile(coreIndex.path, content); + + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "index") + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(); + verifyChangedFiles(changedLogic, changedCore, [ + ...getOutputFileNames(SubProject.logic, "index") + ]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function getOutputFileStamps(): OutputFileStamp[] { + const result = [ + ...getOutputStamps(host, SubProject.core, "index"), + ...getOutputStamps(host, SubProject.logic, "index"), + ]; + return result; + } + + function verifyWatches() { + checkWatchedFiles(host, projectFiles.map(f => f.path)); + checkWatchedDirectories(host, emptyArray, /*recursive*/ false); + checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true); + } + }); + // TODO: write tests reporting errors but that will have more involved work since file }); } From 614423b2870f037f8046ac8d5b54b392c1fb7ee8 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 12 Sep 2018 16:21:17 -0700 Subject: [PATCH 107/146] Fix this-type in prototype-assigned object literals (#26925) * Fix this-type in prototype-assigned object literals Some cases were missing from tryGetThisTypeAt. Fixes #26831 * Lookup this in JS only for @constructor+prototype assignments --- src/compiler/checker.ts | 51 ++++-- .../reference/jsdocTemplateTag5.errors.txt | 77 --------- .../reference/jsdocTemplateTag5.symbols | 9 +- .../reference/jsdocTemplateTag5.types | 24 +-- .../typeFromPrototypeAssignment.errors.txt | 45 ++++++ .../typeFromPrototypeAssignment.symbols | 122 ++++++++++++++ .../typeFromPrototypeAssignment.types | 149 ++++++++++++++++++ .../salsa/typeFromPrototypeAssignment.ts | 44 ++++++ 8 files changed, 416 insertions(+), 105 deletions(-) delete mode 100644 tests/baselines/reference/jsdocTemplateTag5.errors.txt create mode 100644 tests/baselines/reference/typeFromPrototypeAssignment.errors.txt create mode 100644 tests/baselines/reference/typeFromPrototypeAssignment.symbols create mode 100644 tests/baselines/reference/typeFromPrototypeAssignment.types create mode 100644 tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6bd0c0409d4..e6a794e866a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -15809,30 +15809,27 @@ namespace ts { } function tryGetThisTypeAt(node: Node, container = getThisContainer(node, /*includeArrowFunctions*/ false)): Type | undefined { + const isInJS = isInJSFile(node); if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. - // If this is a function in a JS file, it might be a class method. - // Check if it's the RHS of a x.prototype.y = function [name]() { .... } - if (container.kind === SyntaxKind.FunctionExpression && - container.parent.kind === SyntaxKind.BinaryExpression && - getAssignmentDeclarationKind(container.parent as BinaryExpression) === AssignmentDeclarationKind.PrototypeProperty) { - // Get the 'x' of 'x.prototype.y = f' (here, 'f' is 'container') - const className = (((container.parent as BinaryExpression) // x.prototype.y = f - .left as PropertyAccessExpression) // x.prototype.y - .expression as PropertyAccessExpression) // x.prototype - .expression; // x + const className = getClassNameFromPrototypeMethod(container); + if (isInJS && className) { const classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { - return getFlowTypeOfReference(node, getInferredClassType(classSymbol)); + const classType = getJavascriptClassType(classSymbol); + if (classType) { + return getFlowTypeOfReference(node, classType); + } } } // Check if it's a constructor definition, can be either a variable decl or function decl // i.e. // * /** @constructor */ function [name]() { ... } // * /** @constructor */ var x = function() { ... } - else if ((container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && + else if (isInJS && + (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && getJSDocClassTag(container)) { const classType = getJavascriptClassType(container.symbol); if (classType) { @@ -15852,7 +15849,7 @@ namespace ts { return getFlowTypeOfReference(node, type); } - if (isInJSFile(node)) { + if (isInJS) { const type = getTypeForThisExpressionFromJSDoc(container); if (type && type !== errorType) { return getFlowTypeOfReference(node, type); @@ -15860,6 +15857,34 @@ namespace ts { } } + function getClassNameFromPrototypeMethod(container: Node) { + // Check if it's the RHS of a x.prototype.y = function [name]() { .... } + if (container.kind === SyntaxKind.FunctionExpression && + isBinaryExpression(container.parent) && + getAssignmentDeclarationKind(container.parent) === AssignmentDeclarationKind.PrototypeProperty) { + // Get the 'x' of 'x.prototype.y = container' + return ((container.parent // x.prototype.y = container + .left as PropertyAccessExpression) // x.prototype.y + .expression as PropertyAccessExpression) // x.prototype + .expression; // x + } + // x.prototype = { method() { } } + else if (container.kind === SyntaxKind.MethodDeclaration && + container.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.left as PropertyAccessExpression).expression; + } + // x.prototype = { method: function() { } } + else if (container.kind === SyntaxKind.FunctionExpression && + container.parent.kind === SyntaxKind.PropertyAssignment && + container.parent.parent.kind === SyntaxKind.ObjectLiteralExpression && + isBinaryExpression(container.parent.parent.parent) && + getAssignmentDeclarationKind(container.parent.parent.parent) === AssignmentDeclarationKind.Prototype) { + return (container.parent.parent.parent.left as PropertyAccessExpression).expression; + } + } + function getTypeForThisExpressionFromJSDoc(node: Node) { const jsdocType = getJSDocType(node); if (jsdocType && jsdocType.kind === SyntaxKind.JSDocFunctionType) { diff --git a/tests/baselines/reference/jsdocTemplateTag5.errors.txt b/tests/baselines/reference/jsdocTemplateTag5.errors.txt deleted file mode 100644 index e24cd0926b6..00000000000 --- a/tests/baselines/reference/jsdocTemplateTag5.errors.txt +++ /dev/null @@ -1,77 +0,0 @@ -tests/cases/conformance/jsdoc/a.js(18,21): error TS2339: Property '_map' does not exist on type '{ get(key: K): V; }'. -tests/cases/conformance/jsdoc/a.js(39,21): error TS2339: Property '_map' does not exist on type '{ get: (key: K) => V; }'. -tests/cases/conformance/jsdoc/a.js(61,21): error TS2339: Property '_map' does not exist on type '{ get(key: K): V; }'. - - -==== tests/cases/conformance/jsdoc/a.js (3 errors) ==== - /** - * Should work for function declarations - * @constructor - * @template {string} K - * @template V - */ - function Multimap() { - /** @type {Object} TODO: Remove the prototype from the fresh object */ - this._map = {}; - }; - - Multimap.prototype = { - /** - * @param {K} key the key ok - * @returns {V} the value ok - */ - get(key) { - return this._map[key + '']; - ~~~~ -!!! error TS2339: Property '_map' does not exist on type '{ get(key: K): V; }'. - } - } - - /** - * Should work for initialisers too - * @constructor - * @template {string} K - * @template V - */ - var Multimap2 = function() { - /** @type {Object} TODO: Remove the prototype from the fresh object */ - this._map = {}; - }; - - Multimap2.prototype = { - /** - * @param {K} key the key ok - * @returns {V} the value ok - */ - get: function(key) { - return this._map[key + '']; - ~~~~ -!!! error TS2339: Property '_map' does not exist on type '{ get: (key: K) => V; }'. - } - } - - var Ns = {}; - /** - * Should work for expando-namespaced initialisers too - * @constructor - * @template {string} K - * @template V - */ - Ns.Multimap3 = function() { - /** @type {Object} TODO: Remove the prototype from the fresh object */ - this._map = {}; - }; - - Ns.Multimap3.prototype = { - /** - * @param {K} key the key ok - * @returns {V} the value ok - */ - get(key) { - return this._map[key + '']; - ~~~~ -!!! error TS2339: Property '_map' does not exist on type '{ get(key: K): V; }'. - } - } - - \ No newline at end of file diff --git a/tests/baselines/reference/jsdocTemplateTag5.symbols b/tests/baselines/reference/jsdocTemplateTag5.symbols index 249e92ab257..aa1b023f339 100644 --- a/tests/baselines/reference/jsdocTemplateTag5.symbols +++ b/tests/baselines/reference/jsdocTemplateTag5.symbols @@ -29,7 +29,8 @@ Multimap.prototype = { >key : Symbol(key, Decl(a.js, 16, 8)) return this._map[key + '']; ->this : Symbol(__object, Decl(a.js, 11, 20)) +>this._map : Symbol(Multimap._map, Decl(a.js, 6, 21)) +>_map : Symbol(Multimap._map, Decl(a.js, 6, 21)) >key : Symbol(key, Decl(a.js, 16, 8)) } } @@ -64,7 +65,8 @@ Multimap2.prototype = { >key : Symbol(key, Decl(a.js, 37, 18)) return this._map[key + '']; ->this : Symbol(__object, Decl(a.js, 32, 21)) +>this._map : Symbol(Multimap2._map, Decl(a.js, 27, 28)) +>_map : Symbol(Multimap2._map, Decl(a.js, 27, 28)) >key : Symbol(key, Decl(a.js, 37, 18)) } } @@ -106,7 +108,8 @@ Ns.Multimap3.prototype = { >key : Symbol(key, Decl(a.js, 59, 8)) return this._map[key + '']; ->this : Symbol(__object, Decl(a.js, 54, 24)) +>this._map : Symbol(Multimap3._map, Decl(a.js, 49, 27)) +>_map : Symbol(Multimap3._map, Decl(a.js, 49, 27)) >key : Symbol(key, Decl(a.js, 59, 8)) } } diff --git a/tests/baselines/reference/jsdocTemplateTag5.types b/tests/baselines/reference/jsdocTemplateTag5.types index c5b8752d2b6..1195b372e18 100644 --- a/tests/baselines/reference/jsdocTemplateTag5.types +++ b/tests/baselines/reference/jsdocTemplateTag5.types @@ -34,10 +34,10 @@ Multimap.prototype = { >key : K return this._map[key + '']; ->this._map[key + ''] : any ->this._map : any ->this : { get(key: K): V; } ->_map : any +>this._map[key + ''] : V +>this._map : { [x: string]: V; } +>this : Multimap & { get(key: K): V; } +>_map : { [x: string]: V; } >key + '' : string >key : K >'' : "" @@ -81,10 +81,10 @@ Multimap2.prototype = { >key : K return this._map[key + '']; ->this._map[key + ''] : any ->this._map : any ->this : { get: (key: K) => V; } ->_map : any +>this._map[key + ''] : V +>this._map : { [x: string]: V; } +>this : Multimap2 & { get: (key: K) => V; } +>_map : { [x: string]: V; } >key + '' : string >key : K >'' : "" @@ -136,10 +136,10 @@ Ns.Multimap3.prototype = { >key : K return this._map[key + '']; ->this._map[key + ''] : any ->this._map : any ->this : { get(key: K): V; } ->_map : any +>this._map[key + ''] : V +>this._map : { [x: string]: V; } +>this : Multimap3 & { get(key: K): V; } +>_map : { [x: string]: V; } >key + '' : string >key : K >'' : "" diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt b/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt new file mode 100644 index 00000000000..edd3435c445 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.errors.txt @@ -0,0 +1,45 @@ +tests/cases/conformance/salsa/a.js(27,20): error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + + +==== tests/cases/conformance/salsa/a.js (1 errors) ==== + // all references to _map, set, get, addon should be ok + + /** @constructor */ + var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon + }; + + Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } + } + + Multimap.prototype.addon = function () { + ~~~~~ +!!! error TS2339: Property 'addon' does not exist on type '{ set: () => void; get(): void; }'. + this._map + this.set + this.get + this.addon + } + + var mm = new Multimap(); + mm._map + mm.set + mm.get + mm.addon + \ No newline at end of file diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.symbols b/tests/baselines/reference/typeFromPrototypeAssignment.symbols new file mode 100644 index 00000000000..d51382a639f --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.symbols @@ -0,0 +1,122 @@ +=== tests/cases/conformance/salsa/a.js === +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) + + this._map = {}; +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + +}; + +Multimap.prototype = { +>Multimap.prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) + + set: function() { +>set : Symbol(set, Decl(a.js, 11, 22)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + + }, + get() { +>get : Symbol(get, Decl(a.js, 17, 6)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + } +} + +Multimap.prototype.addon = function () { +>Multimap.prototype : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) +>prototype : Symbol(Multimap.prototype, Decl(a.js, 9, 2)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + + this._map +>this._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + + this.set +>this.set : Symbol(set, Decl(a.js, 11, 22)) +>set : Symbol(set, Decl(a.js, 11, 22)) + + this.get +>this.get : Symbol(get, Decl(a.js, 17, 6)) +>get : Symbol(get, Decl(a.js, 17, 6)) + + this.addon +>this.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +} + +var mm = new Multimap(); +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>Multimap : Symbol(Multimap, Decl(a.js, 3, 3), Decl(a.js, 9, 2)) + +mm._map +>mm._map : Symbol(Multimap._map, Decl(a.js, 3, 27)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>_map : Symbol(Multimap._map, Decl(a.js, 3, 27)) + +mm.set +>mm.set : Symbol(set, Decl(a.js, 11, 22)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>set : Symbol(set, Decl(a.js, 11, 22)) + +mm.get +>mm.get : Symbol(get, Decl(a.js, 17, 6)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>get : Symbol(get, Decl(a.js, 17, 6)) + +mm.addon +>mm.addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) +>mm : Symbol(mm, Decl(a.js, 33, 3)) +>addon : Symbol(Multimap.addon, Decl(a.js, 24, 1)) + diff --git a/tests/baselines/reference/typeFromPrototypeAssignment.types b/tests/baselines/reference/typeFromPrototypeAssignment.types new file mode 100644 index 00000000000..87e4be5e0b9 --- /dev/null +++ b/tests/baselines/reference/typeFromPrototypeAssignment.types @@ -0,0 +1,149 @@ +=== tests/cases/conformance/salsa/a.js === +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { +>Multimap : typeof Multimap +>function() { this._map = {}; this._map this.set this.get this.addon} : typeof Multimap + + this._map = {}; +>this._map = {} : {} +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} +>{} : {} + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + +}; + +Multimap.prototype = { +>Multimap.prototype = { set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon }} : { set: () => void; get(): void; } +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>{ set: function() { this._map this.set this.get this.addon }, get() { this._map this.set this.get this.addon }} : { set: () => void; get(): void; } + + set: function() { +>set : () => void +>function() { this._map this.set this.get this.addon } : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + + }, + get() { +>get : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void + } +} + +Multimap.prototype.addon = function () { +>Multimap.prototype.addon = function () { this._map this.set this.get this.addon} : () => void +>Multimap.prototype.addon : any +>Multimap.prototype : { set: () => void; get(): void; } +>Multimap : typeof Multimap +>prototype : { set: () => void; get(): void; } +>addon : any +>function () { this._map this.set this.get this.addon} : () => void + + this._map +>this._map : {} +>this : Multimap & { set: () => void; get(): void; } +>_map : {} + + this.set +>this.set : () => void +>this : Multimap & { set: () => void; get(): void; } +>set : () => void + + this.get +>this.get : () => void +>this : Multimap & { set: () => void; get(): void; } +>get : () => void + + this.addon +>this.addon : () => void +>this : Multimap & { set: () => void; get(): void; } +>addon : () => void +} + +var mm = new Multimap(); +>mm : Multimap & { set: () => void; get(): void; } +>new Multimap() : Multimap & { set: () => void; get(): void; } +>Multimap : typeof Multimap + +mm._map +>mm._map : {} +>mm : Multimap & { set: () => void; get(): void; } +>_map : {} + +mm.set +>mm.set : () => void +>mm : Multimap & { set: () => void; get(): void; } +>set : () => void + +mm.get +>mm.get : () => void +>mm : Multimap & { set: () => void; get(): void; } +>get : () => void + +mm.addon +>mm.addon : () => void +>mm : Multimap & { set: () => void; get(): void; } +>addon : () => void + diff --git a/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts b/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts new file mode 100644 index 00000000000..373ccab0394 --- /dev/null +++ b/tests/cases/conformance/salsa/typeFromPrototypeAssignment.ts @@ -0,0 +1,44 @@ +// @noEmit: true +// @allowJs: true +// @checkJs: true +// @Filename: a.js +// @strict: true + +// all references to _map, set, get, addon should be ok + +/** @constructor */ +var Multimap = function() { + this._map = {}; + this._map + this.set + this.get + this.addon +}; + +Multimap.prototype = { + set: function() { + this._map + this.set + this.get + this.addon + }, + get() { + this._map + this.set + this.get + this.addon + } +} + +Multimap.prototype.addon = function () { + this._map + this.set + this.get + this.addon +} + +var mm = new Multimap(); +mm._map +mm.set +mm.get +mm.addon From b8f33f6a35e6659912f39055c4844e786d581c86 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 12 Sep 2018 16:09:22 -0700 Subject: [PATCH 108/146] Report all project errors on incremental compile --- src/compiler/tsbuild.ts | 65 ++++++++++---------- src/testRunner/unittests/tsbuildWatchMode.ts | 27 ++++++++ src/testRunner/unittests/tscWatchMode.ts | 18 +++--- 3 files changed, 72 insertions(+), 38 deletions(-) diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index d7eb648bca2..2c064bea137 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -394,9 +394,9 @@ namespace ts { let globalDependencyGraph: DependencyGraph | undefined; // Watch state - // TODO(shkamat): this should be really be diagnostics but thats for later time - const diagnostics = createFileMap(toPath); + const diagnostics = createFileMap>(toPath); const projectPendingBuild = createFileMap(toPath); + const projectErrorsReported = createFileMap(toPath); const invalidatedProjectQueue = [] as ResolvedConfigFileName[]; let nextProjectToBuild = 0; let timerToBuildInvalidatedProject: any; @@ -438,6 +438,7 @@ namespace ts { diagnostics.clear(); projectPendingBuild.clear(); + projectErrorsReported.clear(); invalidatedProjectQueue.length = 0; nextProjectToBuild = 0; if (timerToBuildInvalidatedProject) { @@ -472,18 +473,6 @@ namespace ts { host.reportSolutionBuilderStatus(createCompilerDiagnostic(message, ...args)); } - function storeErrors(proj: ResolvedConfigFileName, diagnostics: ReadonlyArray) { - if (options.watch) { - storeErrorSummary(proj, diagnostics.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); - } - } - - function storeErrorSummary(proj: ResolvedConfigFileName, errorCount: number) { - if (options.watch) { - diagnostics.setValue(proj, errorCount); - } - } - function reportWatchStatus(message: DiagnosticMessage, ...args: (string | number | undefined)[]) { if (hostWithWatch.onWatchStatusChange) { hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: options.preserveWatchOutput }); @@ -509,7 +498,7 @@ namespace ts { } function watchConfigFile(resolved: ResolvedConfigFileName) { - if (!allWatchedConfigFiles.hasKey(resolved)) { + if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, () => { invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); })); @@ -517,6 +506,7 @@ namespace ts { } function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; updateWatchingWildcardDirectories( getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), @@ -540,6 +530,7 @@ namespace ts { } function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; mutateMap( getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), arrayToMap(parsed.fileNames, toPath), @@ -848,6 +839,7 @@ namespace ts { timerToBuildInvalidatedProject = undefined; if (reportFileChangeDetected) { reportFileChangeDetected = false; + projectErrorsReported.clear(); reportWatchStatus(Diagnostics.File_change_detected_Starting_incremental_compilation); } const buildProject = getNextInvalidatedProject(); @@ -866,15 +858,19 @@ namespace ts { function reportErrorSummary() { if (options.watch) { + // Report errors from the other projects + getGlobalDependencyGraph().buildQueue.forEach(project => { + if (!projectErrorsReported.hasKey(project)) { + reportErrors(diagnostics.getValue(project) || emptyArray); + } + }); let totalErrors = 0; - diagnostics.forEach(singleProjectErrors => totalErrors += singleProjectErrors); + diagnostics.forEach(singleProjectErrors => totalErrors += singleProjectErrors.filter(diagnostic => diagnostic.category === DiagnosticCategory.Error).length); reportWatchStatus(totalErrors === 1 ? Diagnostics.Found_1_error_Watching_for_file_changes : Diagnostics.Found_0_errors_Watching_for_file_changes, totalErrors); } } function buildSingleInvalidatedProject(resolved: ResolvedConfigFileName, reloadLevel: ConfigFileProgramReloadLevel) { - // TODO:: handle this in better way later - const proj = parseConfigFile(resolved); if (!proj) { reportParseConfigFileDiagnostic(resolved); @@ -968,10 +964,6 @@ namespace ts { } } - function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) { - host.reportDiagnostic(configFileCache.getValue(proj) as Diagnostic); - storeErrorSummary(proj, 1); - } function buildSingleProject(proj: ResolvedConfigFileName): BuildResultFlags { if (options.dry) { @@ -1013,7 +1005,7 @@ namespace ts { ...program.getSyntacticDiagnostics()]; if (syntaxDiagnostics.length) { resultFlags |= BuildResultFlags.SyntaxErrors; - reportErrors(proj, syntaxDiagnostics); + reportAndStoreErrors(proj, syntaxDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); return resultFlags; } @@ -1023,7 +1015,7 @@ namespace ts { const declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { resultFlags |= BuildResultFlags.DeclarationEmitErrors; - reportErrors(proj, declDiagnostics); + reportAndStoreErrors(proj, declDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); return resultFlags; } @@ -1033,7 +1025,7 @@ namespace ts { const semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { resultFlags |= BuildResultFlags.TypeErrors; - reportErrors(proj, semanticDiagnostics); + reportAndStoreErrors(proj, semanticDiagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); return resultFlags; } @@ -1154,7 +1146,7 @@ namespace ts { const projName = proj.options.configFilePath!; if (status.type === UpToDateStatusType.UpToDate && !options.force) { - reportErrors(next, errors); + reportAndStoreErrors(next, errors); // Up to date, skip if (defaultOptions.dry) { // In a dry build, inform the user of this fact @@ -1164,20 +1156,20 @@ namespace ts { } if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { - reportErrors(next, errors); + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - reportErrors(next, errors); + reportAndStoreErrors(next, errors); if (options.verbose) reportStatus(Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, projName, status.upstreamProjectName); continue; } if (status.type === UpToDateStatusType.ContainerOnly) { - reportErrors(next, errors); + reportAndStoreErrors(next, errors); // Do nothing continue; } @@ -1189,9 +1181,20 @@ namespace ts { return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } - function reportErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { + function reportParseConfigFileDiagnostic(proj: ResolvedConfigFileName) { + reportAndStoreErrors(proj, [configFileCache.getValue(proj) as Diagnostic]); + } + + function reportAndStoreErrors(proj: ResolvedConfigFileName, errors: ReadonlyArray) { + reportErrors(errors); + if (options.watch) { + projectErrorsReported.setValue(proj, true); + diagnostics.setValue(proj, errors); + } + } + + function reportErrors(errors: ReadonlyArray) { errors.forEach(err => host.reportDiagnostic(err)); - storeErrors(proj, errors); } /** diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index 697d14f72ba..d9dcda94bff 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -351,6 +351,33 @@ function myFunc() { return 100; }`); } }); + it("reports errors in all projects on incremental compile", () => { + const host = createSolutionInWatchMode(allFiles); + const outputFileStamps = getOutputFileStamps(host); + + host.writeFile(logic[1].path, `${logic[1].content} +let y: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, outputFileStamps, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ]); + + host.writeFile(core[1].path, `${core[1].content} +let x: string = 10;`); + + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, changedLogic, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/core/index.ts(5,5): error TS2322: Type '10' is not assignable to type 'string'.\n`, + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ]); + }); // TODO: write tests reporting errors but that will have more involved work since file }); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index da1c4fd0d70..b750e4c556c 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -77,7 +77,7 @@ namespace ts.tscWatch { logsBeforeWatchDiagnostic: string[] | undefined, preErrorsWatchDiagnostic: Diagnostic, logsBeforeErrors: string[] | undefined, - errors: ReadonlyArray, + errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean | undefined, ...postErrorsWatchDiagnostics: Diagnostic[] ) { @@ -96,8 +96,12 @@ namespace ts.tscWatch { assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); host.clearOutput(); - function assertDiagnostic(diagnostic: Diagnostic) { - const expected = formatDiagnostic(diagnostic, host); + function isDiagnostic(diagnostic: Diagnostic | string): diagnostic is Diagnostic { + return !!(diagnostic as Diagnostic).messageText; + } + + function assertDiagnostic(diagnostic: Diagnostic | string) { + const expected = isDiagnostic(diagnostic) ? formatDiagnostic(diagnostic, host) : diagnostic; assert.equal(outputs[index], expected, getOutputAtFailedMessage("Diagnostic", expected)); index++; } @@ -130,13 +134,13 @@ namespace ts.tscWatch { } } - function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray) { + function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray | ReadonlyArray) { return errors.length === 1 ? createCompilerDiagnostic(Diagnostics.Found_1_error_Watching_for_file_changes) : createCompilerDiagnostic(Diagnostics.Found_0_errors_Watching_for_file_changes, errors.length); } - export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { checkOutputErrors( host, /*logsBeforeWatchDiagnostic*/ undefined, @@ -147,7 +151,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -158,7 +162,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, From d3463ce3560641ce8b164f50401e00e7d99e36d8 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 12 Sep 2018 17:16:34 -0700 Subject: [PATCH 109/146] Avoid circularly resolving names when looking up type members using resolveName (#26924) * Avoid circularly resolving names when looking up type members using resolveName * Add comment --- src/compiler/checker.ts | 5 ++++- ...ationTypecheckNoUseBeforeReferenceCheck.symbols | 14 ++++++++++++++ ...arationTypecheckNoUseBeforeReferenceCheck.types | 14 ++++++++++++++ ...eclarationTypecheckNoUseBeforeReferenceCheck.ts | 5 +++++ 4 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.symbols create mode 100644 tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.types create mode 100644 tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index e6a794e866a..6f541461b09 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1312,7 +1312,10 @@ namespace ts { case SyntaxKind.ClassDeclaration: case SyntaxKind.ClassExpression: case SyntaxKind.InterfaceDeclaration: - if (result = lookup(getMembersOfSymbol(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration)), name, meaning & SymbolFlags.Type)) { + // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals + // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would + // trigger resolving late-bound names, which we may already be in the process of doing while we're here! + if (result = lookup(getSymbolOfNode(location as ClassLikeDeclaration | InterfaceDeclaration).members || emptySymbols, name, meaning & SymbolFlags.Type)) { if (!isTypeParameterSymbolDeclaredInContainer(result, location)) { // ignore type parameters not declared in this container result = undefined; diff --git a/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.symbols b/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.symbols new file mode 100644 index 00000000000..95b3bd297c9 --- /dev/null +++ b/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.symbols @@ -0,0 +1,14 @@ +=== tests/cases/compiler/index.d.ts === +export class C extends Object { +>C : Symbol(C, Decl(index.d.ts, 0, 0)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + static readonly p: unique symbol; +>p : Symbol(C.p, Decl(index.d.ts, 0, 31)) + + [C.p](): void; +>[C.p] : Symbol(C[C.p], Decl(index.d.ts, 1, 37)) +>C.p : Symbol(C.p, Decl(index.d.ts, 0, 31)) +>C : Symbol(C, Decl(index.d.ts, 0, 0)) +>p : Symbol(C.p, Decl(index.d.ts, 0, 31)) +} diff --git a/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.types b/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.types new file mode 100644 index 00000000000..86f294591dc --- /dev/null +++ b/tests/baselines/reference/declarationTypecheckNoUseBeforeReferenceCheck.types @@ -0,0 +1,14 @@ +=== tests/cases/compiler/index.d.ts === +export class C extends Object { +>C : C +>Object : Object + + static readonly p: unique symbol; +>p : unique symbol + + [C.p](): void; +>[C.p] : () => void +>C.p : unique symbol +>C : typeof C +>p : unique symbol +} diff --git a/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts b/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts new file mode 100644 index 00000000000..21c1db5f59c --- /dev/null +++ b/tests/cases/compiler/declarationTypecheckNoUseBeforeReferenceCheck.ts @@ -0,0 +1,5 @@ +// @filename: index.d.ts +export class C extends Object { + static readonly p: unique symbol; + [C.p](): void; +} \ No newline at end of file From 2b888c30f9a86c33d95cc9796baec1b3a3e29091 Mon Sep 17 00:00:00 2001 From: Andy Date: Wed, 12 Sep 2018 17:44:06 -0700 Subject: [PATCH 110/146] Consistently pass indent to 'parseTagComments' (#27055) * Consistently pass indent to 'parseTagComments' * Update baselines --- src/compiler/parser.ts | 29 +++++++++---------- ...ts.parsesCorrectly.Nested @param tags.json | 2 +- ...sCorrectly.typedefTagWithChildrenTags.json | 4 +-- tests/cases/fourslash/quickInfoPropertyTag.ts | 3 +- 4 files changed, 17 insertions(+), 21 deletions(-) diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 1d65e31b490..415a62e5627 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6724,7 +6724,7 @@ namespace ts { } } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number | undefined): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -6739,9 +6739,8 @@ namespace ts { const result = target === PropertyLikeParse.Property ? createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) : createNode(SyntaxKind.JSDocParameterTag, atToken.pos); - let comment: string | undefined; - if (indent !== undefined) comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); - const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target); + const comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + const nestedTypeLiteral = target !== PropertyLikeParse.CallbackParameter && parseNestedTypeLiteral(typeExpression, name, target, indent); if (nestedTypeLiteral) { typeExpression = nestedTypeLiteral; isNameFirst = true; @@ -6756,14 +6755,14 @@ namespace ts { return finishNode(result); } - function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse) { + function parseNestedTypeLiteral(typeExpression: JSDocTypeExpression | undefined, name: EntityName, target: PropertyLikeParse, indent: number) { if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) { const typeLiteralExpression = createNode(SyntaxKind.JSDocTypeExpression, scanner.getTokenPos()); let child: JSDocPropertyLikeTag | JSDocTypeTag | false; let jsdocTypeLiteral: JSDocTypeLiteral; const start = scanner.getStartPos(); let children: JSDocPropertyLikeTag[] | undefined; - while (child = tryParse(() => parseChildParameterOrPropertyTag(target, name))) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(target, indent, name))) { if (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) { children = append(children, child); } @@ -6879,7 +6878,7 @@ namespace ts { let jsdocTypeLiteral: JSDocTypeLiteral | undefined; let childTypeTag: JSDocTypeTag | undefined; const start = atToken.pos; - while (child = tryParse(() => parseChildPropertyTag())) { + while (child = tryParse(() => parseChildPropertyTag(indent))) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); } @@ -6945,7 +6944,7 @@ namespace ts { const start = scanner.getStartPos(); const jsdocSignature = createNode(SyntaxKind.JSDocSignature, start) as JSDocSignature; jsdocSignature.parameters = []; - while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter) as JSDocParameterTag)) { + while (child = tryParse(() => parseChildParameterOrPropertyTag(PropertyLikeParse.CallbackParameter, indent) as JSDocParameterTag)) { jsdocSignature.parameters = append(jsdocSignature.parameters as MutableNodeArray, child); } const returnTag = tryParse(() => { @@ -6988,18 +6987,18 @@ namespace ts { return a.escapedText === b.escapedText; } - function parseChildPropertyTag() { - return parseChildParameterOrPropertyTag(PropertyLikeParse.Property) as JSDocTypeTag | JSDocPropertyTag | false; + function parseChildPropertyTag(indent: number) { + return parseChildParameterOrPropertyTag(PropertyLikeParse.Property, indent) as JSDocTypeTag | JSDocPropertyTag | false; } - function parseChildParameterOrPropertyTag(target: PropertyLikeParse, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function parseChildParameterOrPropertyTag(target: PropertyLikeParse, indent: number, name?: EntityName): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { let canParseTag = true; let seenAsterisk = false; while (true) { switch (nextJSDocToken()) { case SyntaxKind.AtToken: if (canParseTag) { - const child = tryParseChildTag(target); + const child = tryParseChildTag(target, indent); if (child && (child.kind === SyntaxKind.JSDocParameterTag || child.kind === SyntaxKind.JSDocPropertyTag) && target !== PropertyLikeParse.CallbackParameter && name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) { @@ -7028,7 +7027,7 @@ namespace ts { } } - function tryParseChildTag(target: PropertyLikeParse): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { + function tryParseChildTag(target: PropertyLikeParse, indent: number): JSDocTypeTag | JSDocPropertyTag | JSDocParameterTag | false { Debug.assert(token() === SyntaxKind.AtToken); const atToken = createNode(SyntaxKind.AtToken); atToken.end = scanner.getTextPos(); @@ -7055,9 +7054,7 @@ namespace ts { if (!(target & t)) { return false; } - const tag = parseParameterOrPropertyTag(atToken, tagName, target, /*indent*/ undefined); - tag.comment = parseTagComments(tag.end - tag.pos); - return tag; + return parseParameterOrPropertyTag(atToken, tagName, target, indent); } function parseTemplateTag(atToken: AtToken, tagName: Identifier): JSDocTemplateTag { diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json index 73d3f598059..f75d1e5fc6b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json @@ -30,7 +30,7 @@ { "kind": "JSDocParameterTag", "pos": 34, - "end": 54, + "end": 64, "atToken": { "kind": "AtToken", "pos": 34, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 6d2fb4ada2f..7b3050cffa2 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -38,7 +38,7 @@ { "kind": "JSDocPropertyTag", "pos": 47, - "end": 72, + "end": 74, "atToken": { "kind": "AtToken", "pos": 47, @@ -72,7 +72,7 @@ { "kind": "JSDocPropertyTag", "pos": 74, - "end": 97, + "end": 100, "atToken": { "kind": "AtToken", "pos": 74, diff --git a/tests/cases/fourslash/quickInfoPropertyTag.ts b/tests/cases/fourslash/quickInfoPropertyTag.ts index b413a7610e1..e702436ed42 100644 --- a/tests/cases/fourslash/quickInfoPropertyTag.ts +++ b/tests/cases/fourslash/quickInfoPropertyTag.ts @@ -12,5 +12,4 @@ /////** @type {I} */ ////const obj = { /**/x: 10 }; -// TODO: GH#21123 There shouldn't be a " " before "More doc" -verify.quickInfoAt("", "(property) x: number", "Doc\n More doc"); +verify.quickInfoAt("", "(property) x: number", "Doc\nMore doc"); From ea7ff15307757400a57ca524caa28b1a95cd309f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Sep 2018 17:51:57 -0700 Subject: [PATCH 111/146] makeFileLevelOptmiisticUniqueName -> makeFileLevelOptimisticUniqueName --- src/compiler/emitter.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 2d103b8af8f..bce36bca73c 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1015,7 +1015,7 @@ namespace ts { writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -3588,7 +3588,7 @@ namespace ts { } } - function makeFileLevelOptmiisticUniqueName(name: string) { + function makeFileLevelOptimisticUniqueName(name: string) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } From cc7bfc03496716374b9d28d0ff73c9ad5d942dd0 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 13 Sep 2018 08:47:50 -0700 Subject: [PATCH 112/146] Support testing jsdoc tags of completions (#26962) --- src/harness/fourslash.ts | 27 ++- src/services/jsDoc.ts | 4 +- src/services/symbolDisplay.ts | 2 +- .../unittests/tsserverProjectSystem.ts | 6 +- tests/baselines/reference/jsDocTypedef1.js | 3 +- ...splayPartsArrowFunctionExpression.baseline | 24 +-- .../quickInfoDisplayPartsClass.baseline | 15 +- ...ickInfoDisplayPartsClassAccessors.baseline | 96 +++------ ...kInfoDisplayPartsClassConstructor.baseline | 78 +++---- .../quickInfoDisplayPartsClassMethod.baseline | 48 ++--- ...uickInfoDisplayPartsClassProperty.baseline | 48 ++--- .../quickInfoDisplayPartsConst.baseline | 48 ++--- .../quickInfoDisplayPartsEnum1.baseline | 90 +++----- .../quickInfoDisplayPartsEnum2.baseline | 90 +++----- .../quickInfoDisplayPartsEnum3.baseline | 90 +++----- ...layPartsExternalModuleAlias_file0.baseline | 18 +- ...ckInfoDisplayPartsExternalModules.baseline | 51 ++--- .../quickInfoDisplayPartsFunction.baseline | 42 ++-- ...nfoDisplayPartsFunctionExpression.baseline | 18 +- .../quickInfoDisplayPartsInterface.baseline | 9 +- ...kInfoDisplayPartsInterfaceMembers.baseline | 27 +-- ...foDisplayPartsInternalModuleAlias.baseline | 24 +-- .../quickInfoDisplayPartsLet.baseline | 48 ++--- ...nfoDisplayPartsLiteralLikeNames01.baseline | 30 +-- ...uickInfoDisplayPartsLocalFunction.baseline | 48 ++--- .../quickInfoDisplayPartsModules.baseline | 51 ++--- .../quickInfoDisplayPartsParameters.baseline | 27 +-- .../quickInfoDisplayPartsTypeAlias.baseline | 18 +- ...oDisplayPartsTypeParameterInClass.baseline | 123 ++++------- ...splayPartsTypeParameterInFunction.baseline | 36 ++-- ...arameterInFunctionLikeInTypeAlias.baseline | 9 +- ...playPartsTypeParameterInInterface.baseline | 195 ++++++------------ ...playPartsTypeParameterInTypeAlias.baseline | 18 +- .../quickInfoDisplayPartsVar.baseline | 42 ++-- ...quickInfoDisplayPartsVar.shims-pp.baseline | 42 ++-- .../quickInfoDisplayPartsVar.shims.baseline | 42 ++-- ...oDisplayPartsVarWithStringTypes01.baseline | 9 +- .../cases/fourslash/commentsCommentParsing.ts | 14 +- tests/cases/fourslash/fourslash.ts | 9 +- .../fourslash/jsDocFunctionSignatures9.ts | 2 +- .../completionEntryDetailAcrossFiles02.ts | 4 +- 41 files changed, 562 insertions(+), 1063 deletions(-) diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 1abb7d4c1cc..a1f3517b6e6 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -908,8 +908,8 @@ namespace FourSlash { } private verifyCompletionEntry(actual: ts.CompletionEntry, expected: FourSlashInterface.ExpectedCompletionEntry) { - const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, source, sourceDisplay } = typeof expected === "string" - ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, source: undefined, sourceDisplay: undefined } + const { insertText, replacementSpan, hasAction, isRecommended, kind, text, documentation, tags, source, sourceDisplay } = typeof expected === "string" + ? { insertText: undefined, replacementSpan: undefined, hasAction: undefined, isRecommended: undefined, kind: undefined, text: undefined, documentation: undefined, tags: undefined, source: undefined, sourceDisplay: undefined } : expected; if (actual.insertText !== insertText) { @@ -929,7 +929,7 @@ namespace FourSlash { assert.equal(actual.isRecommended, isRecommended); assert.equal(actual.source, source); - if (text) { + if (text !== undefined) { const actualDetails = this.getCompletionEntryDetails(actual.name, actual.source)!; assert.equal(ts.displayPartsToString(actualDetails.displayParts), text); assert.equal(ts.displayPartsToString(actualDetails.documentation), documentation || ""); @@ -937,9 +937,10 @@ namespace FourSlash { // assert.equal(actualDetails.kind, actual.kind); assert.equal(actualDetails.kindModifiers, actual.kindModifiers); assert.equal(actualDetails.source && ts.displayPartsToString(actualDetails.source), sourceDisplay); + assert.deepEqual(actualDetails.tags, tags); } else { - assert(documentation === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); + assert(documentation === undefined && tags === undefined && sourceDisplay === undefined, "If specifying completion details, should specify 'text'"); } } @@ -1363,7 +1364,7 @@ Actual: ${stringify(fullActual)}`); public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], - tags: ts.JSDocTagInfo[] + tags: ts.JSDocTagInfo[] | undefined ) { const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition)!; @@ -1372,11 +1373,16 @@ Actual: ${stringify(fullActual)}`); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.displayParts), TestState.getDisplayPartsJson(displayParts), this.messageAtLastKnownMarker("QuickInfo displayParts")); assert.equal(TestState.getDisplayPartsJson(actualQuickInfo.documentation), TestState.getDisplayPartsJson(documentation), this.messageAtLastKnownMarker("QuickInfo documentation")); - assert.equal(actualQuickInfo.tags!.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); - ts.zipWith(tags, actualQuickInfo.tags!, (expectedTag, actualTag) => { - assert.equal(expectedTag.name, actualTag.name); - assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); - }); + if (!actualQuickInfo.tags || !tags) { + assert.equal(actualQuickInfo.tags, tags, this.messageAtLastKnownMarker("QuickInfo tags")); + } + else { + assert.equal(actualQuickInfo.tags.length, tags.length, this.messageAtLastKnownMarker("QuickInfo tags")); + ts.zipWith(tags, actualQuickInfo.tags, (expectedTag, actualTag) => { + assert.equal(expectedTag.name, actualTag.name); + assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name)); + }); + } } public verifyRangesAreRenameLocations(options?: Range[] | { findInStrings?: boolean, findInComments?: boolean, ranges?: Range[] }) { @@ -4802,6 +4808,7 @@ namespace FourSlashInterface { readonly text: string; readonly documentation: string; readonly sourceDisplay?: string; + readonly tags?: ReadonlyArray; }; export interface CompletionsAtOptions extends Partial { triggerCharacter?: ts.CompletionsTriggerCharacter; diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 641eb643f92..442df61e073 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -208,7 +208,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -242,7 +242,7 @@ namespace ts.JsDoc { kindModifiers: "", displayParts: [textPart(name)], documentation: emptyArray, - tags: emptyArray, + tags: undefined, codeActions: undefined, }; } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index cc59aa3c0ce..e0728f98a29 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -534,7 +534,7 @@ namespace ts.SymbolDisplay { tags = tagsFromAlias; } - return { displayParts, documentation, symbolKind, tags: tags! }; + return { displayParts, documentation, symbolKind, tags: tags!.length === 0 ? undefined : tags }; function getPrinter() { if (!printer) { diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 7114759b097..988ccbc3bfe 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -3204,7 +3204,7 @@ namespace ts.projectSystem { { text: "number", kind: "keyword" } ], documentation: [], - tags: [] + tags: undefined, }); }); @@ -9501,7 +9501,7 @@ export function Test2() { kindModifiers: ScriptElementKindModifier.exportedModifier, name: "foo", source: [{ text: "./a", kind: "text" }], - tags: emptyArray, + tags: undefined, }; assert.deepEqual | undefined>(detailsResponse, [ { @@ -9583,7 +9583,7 @@ declare class TestLib { constructor() { var l = new TestLib(); - + } public test2() { diff --git a/tests/baselines/reference/jsDocTypedef1.js b/tests/baselines/reference/jsDocTypedef1.js index bc00dcafb5d..4745ca9d226 100644 --- a/tests/baselines/reference/jsDocTypedef1.js +++ b/tests/baselines/reference/jsDocTypedef1.js @@ -100,8 +100,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsArrowFunctionExpression.baseline b/tests/baselines/reference/quickInfoDisplayPartsArrowFunctionExpression.baseline index f4484663b97..7ee4e5b25cd 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsArrowFunctionExpression.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsArrowFunctionExpression.baseline @@ -73,8 +73,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -123,8 +122,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -225,8 +223,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -275,8 +272,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -325,8 +321,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -403,8 +398,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -453,8 +447,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -515,8 +508,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsClass.baseline b/tests/baselines/reference/quickInfoDisplayPartsClass.baseline index 68e3b16c7a6..0b048b737a6 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsClass.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsClass.baseline @@ -25,8 +25,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -67,8 +66,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -117,8 +115,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -167,8 +164,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -197,8 +193,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsClassAccessors.baseline b/tests/baselines/reference/quickInfoDisplayPartsClassAccessors.baseline index 97f167fdd80..b0c27fd9d28 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsClassAccessors.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsClassAccessors.baseline @@ -53,8 +53,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -111,8 +110,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -169,8 +167,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -227,8 +224,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -285,8 +281,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -343,8 +338,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -401,8 +395,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -459,8 +452,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -517,8 +509,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -575,8 +566,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -633,8 +623,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -691,8 +680,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -749,8 +737,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -807,8 +794,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -865,8 +851,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -923,8 +908,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -981,8 +965,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1039,8 +1022,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1097,8 +1079,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1155,8 +1136,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1213,8 +1193,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1271,8 +1250,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1329,8 +1307,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1387,8 +1364,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1429,8 +1405,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1487,8 +1462,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1517,8 +1491,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1575,8 +1548,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1617,8 +1589,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1675,8 +1646,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1705,8 +1675,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1763,8 +1732,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsClassConstructor.baseline b/tests/baselines/reference/quickInfoDisplayPartsClassConstructor.baseline index f6217460180..76ca00a4048 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsClassConstructor.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsClassConstructor.baseline @@ -45,8 +45,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -87,8 +86,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -137,8 +135,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -187,8 +184,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -217,8 +213,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -311,8 +306,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -405,8 +399,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -499,8 +492,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -541,8 +533,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -635,8 +626,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -677,8 +667,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -771,8 +760,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -821,8 +809,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -851,8 +838,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -945,8 +931,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1039,8 +1024,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1133,8 +1117,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1227,8 +1210,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1269,8 +1251,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1363,8 +1344,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1405,8 +1385,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1499,8 +1478,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1541,8 +1519,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1635,8 +1612,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1685,8 +1661,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1715,8 +1690,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsClassMethod.baseline b/tests/baselines/reference/quickInfoDisplayPartsClassMethod.baseline index e17708f1bc6..d6f3f187d02 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsClassMethod.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsClassMethod.baseline @@ -61,8 +61,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -127,8 +126,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -193,8 +191,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -259,8 +256,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -325,8 +321,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -391,8 +386,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -457,8 +451,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -523,8 +516,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -589,8 +581,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -655,8 +646,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -721,8 +711,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -787,8 +776,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -829,8 +817,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -895,8 +882,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -925,8 +911,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -991,8 +976,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsClassProperty.baseline b/tests/baselines/reference/quickInfoDisplayPartsClassProperty.baseline index 57a41e6beb4..b49fb80c38a 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsClassProperty.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsClassProperty.baseline @@ -53,8 +53,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -111,8 +110,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -169,8 +167,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -227,8 +224,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -285,8 +281,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -343,8 +338,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -401,8 +395,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -459,8 +452,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -517,8 +509,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -575,8 +566,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -633,8 +623,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -691,8 +680,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -733,8 +721,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -791,8 +778,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -821,8 +807,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -879,8 +864,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsConst.baseline b/tests/baselines/reference/quickInfoDisplayPartsConst.baseline index f73ef50dc0c..7493d001bd3 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsConst.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsConst.baseline @@ -37,8 +37,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -79,8 +78,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -121,8 +119,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -163,8 +160,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -205,8 +201,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -255,8 +250,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -297,8 +291,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -359,8 +352,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -421,8 +413,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -483,8 +474,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -545,8 +535,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -691,8 +680,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -837,8 +825,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -983,8 +970,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1089,8 +1075,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1195,8 +1180,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsEnum1.baseline b/tests/baselines/reference/quickInfoDisplayPartsEnum1.baseline index cf3ddc3025c..6dc27a4a5b3 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsEnum1.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsEnum1.baseline @@ -25,8 +25,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -87,8 +86,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -149,8 +147,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -211,8 +208,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -253,8 +249,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -283,8 +278,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -325,8 +319,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -355,8 +348,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -417,8 +409,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -459,8 +450,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -489,8 +479,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -551,8 +540,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -593,8 +581,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -623,8 +610,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -685,8 +671,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -723,8 +708,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -785,8 +769,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -847,8 +830,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -909,8 +891,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -951,8 +932,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -989,8 +969,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1031,8 +1010,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1069,8 +1047,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1131,8 +1108,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1173,8 +1149,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1211,8 +1186,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1273,8 +1247,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1315,8 +1288,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1353,8 +1325,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1415,8 +1386,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsEnum2.baseline b/tests/baselines/reference/quickInfoDisplayPartsEnum2.baseline index 0bb72e51078..43d0683faef 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsEnum2.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsEnum2.baseline @@ -25,8 +25,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -91,8 +90,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -157,8 +155,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -223,8 +220,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -265,8 +261,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -295,8 +290,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -337,8 +331,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -367,8 +360,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -433,8 +425,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -475,8 +466,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -505,8 +495,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -571,8 +560,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -613,8 +601,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -643,8 +630,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -709,8 +695,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -747,8 +732,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -813,8 +797,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -879,8 +862,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -945,8 +927,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -987,8 +968,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1025,8 +1005,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1067,8 +1046,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1105,8 +1083,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1171,8 +1148,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1213,8 +1189,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1251,8 +1226,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1317,8 +1291,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1359,8 +1332,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1397,8 +1369,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1463,8 +1434,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsEnum3.baseline b/tests/baselines/reference/quickInfoDisplayPartsEnum3.baseline index 1366a49ec7b..b9f6483f63a 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsEnum3.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsEnum3.baseline @@ -25,8 +25,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -91,8 +90,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -157,8 +155,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -223,8 +220,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -265,8 +261,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -295,8 +290,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -337,8 +331,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -367,8 +360,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -433,8 +425,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -475,8 +466,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -505,8 +495,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -571,8 +560,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -613,8 +601,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -643,8 +630,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -709,8 +695,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -747,8 +732,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -813,8 +797,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -879,8 +862,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -945,8 +927,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -987,8 +968,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1025,8 +1005,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1067,8 +1046,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1105,8 +1083,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1171,8 +1148,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1213,8 +1189,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1251,8 +1226,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1317,8 +1291,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1359,8 +1332,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1397,8 +1369,7 @@ "kind": "enumName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1463,8 +1434,7 @@ "kind": "numericLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsExternalModuleAlias_file0.baseline b/tests/baselines/reference/quickInfoDisplayPartsExternalModuleAlias_file0.baseline index 182ae0a4040..78667e7c6e6 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsExternalModuleAlias_file0.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsExternalModuleAlias_file0.baseline @@ -53,8 +53,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -83,8 +82,7 @@ "kind": "aliasName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -141,8 +139,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -199,8 +196,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -229,8 +225,7 @@ "kind": "aliasName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -287,8 +282,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsExternalModules.baseline b/tests/baselines/reference/quickInfoDisplayPartsExternalModules.baseline index dc422bbac33..fa548470a76 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsExternalModules.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsExternalModules.baseline @@ -25,8 +25,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -67,8 +66,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -117,8 +115,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -167,8 +164,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -197,8 +193,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -247,8 +242,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -277,8 +271,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -307,8 +300,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -345,8 +337,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -387,8 +378,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -445,8 +435,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -503,8 +492,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -533,8 +521,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -571,8 +558,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -629,8 +615,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -659,8 +644,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -697,8 +681,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsFunction.baseline b/tests/baselines/reference/quickInfoDisplayPartsFunction.baseline index 2e3cacb9801..6ac80589629 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsFunction.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsFunction.baseline @@ -153,8 +153,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -247,8 +246,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -341,8 +339,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -435,8 +432,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -529,8 +525,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -623,8 +618,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -717,8 +711,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -811,8 +804,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -969,8 +961,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1063,8 +1054,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1157,8 +1147,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1251,8 +1240,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1345,8 +1333,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1439,8 +1426,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsFunctionExpression.baseline b/tests/baselines/reference/quickInfoDisplayPartsFunctionExpression.baseline index 2e67ba6c4aa..ec943e3ac7c 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsFunctionExpression.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsFunctionExpression.baseline @@ -57,8 +57,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -115,8 +114,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -173,8 +171,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -235,8 +232,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -293,8 +289,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -351,8 +346,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsInterface.baseline b/tests/baselines/reference/quickInfoDisplayPartsInterface.baseline index 51383489237..43b9faa9540 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsInterface.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsInterface.baseline @@ -25,8 +25,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -67,8 +66,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -97,8 +95,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsInterfaceMembers.baseline b/tests/baselines/reference/quickInfoDisplayPartsInterfaceMembers.baseline index fa1e5977dd5..4a82bd41d30 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsInterfaceMembers.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsInterfaceMembers.baseline @@ -53,8 +53,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -119,8 +118,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -161,8 +159,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -219,8 +216,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -261,8 +257,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -327,8 +322,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -397,8 +391,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -439,8 +432,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -517,8 +509,7 @@ "kind": "interfaceName" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsInternalModuleAlias.baseline b/tests/baselines/reference/quickInfoDisplayPartsInternalModuleAlias.baseline index c476abad356..0d4660e51d5 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsInternalModuleAlias.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsInternalModuleAlias.baseline @@ -73,8 +73,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -151,8 +150,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -237,8 +235,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -323,8 +320,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -417,8 +413,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -511,8 +506,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -613,8 +607,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -715,8 +708,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsLet.baseline b/tests/baselines/reference/quickInfoDisplayPartsLet.baseline index d8f339f8451..2153c0b132b 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsLet.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsLet.baseline @@ -37,8 +37,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -79,8 +78,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -121,8 +119,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -163,8 +160,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -205,8 +201,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -255,8 +250,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -297,8 +291,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -359,8 +352,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -421,8 +413,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -483,8 +474,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -545,8 +535,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -691,8 +680,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -837,8 +825,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -983,8 +970,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1089,8 +1075,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1195,8 +1180,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsLiteralLikeNames01.baseline b/tests/baselines/reference/quickInfoDisplayPartsLiteralLikeNames01.baseline index 1d2d8216808..47e5239c605 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsLiteralLikeNames01.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsLiteralLikeNames01.baseline @@ -65,8 +65,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -131,8 +130,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -197,8 +195,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -267,8 +264,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -337,8 +333,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -407,8 +402,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -473,8 +467,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -539,8 +532,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -605,8 +597,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -675,8 +666,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsLocalFunction.baseline b/tests/baselines/reference/quickInfoDisplayPartsLocalFunction.baseline index 1b7d050c3b3..65c3dc88390 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsLocalFunction.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsLocalFunction.baseline @@ -45,8 +45,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -211,8 +210,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -313,8 +311,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -415,8 +412,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -517,8 +513,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -619,8 +614,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -721,8 +715,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -823,8 +816,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -925,8 +917,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1091,8 +1082,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1193,8 +1183,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1295,8 +1284,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1397,8 +1385,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1499,8 +1486,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1601,8 +1587,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1651,8 +1636,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsModules.baseline b/tests/baselines/reference/quickInfoDisplayPartsModules.baseline index 66c04216af6..e2f04ea75e8 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsModules.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsModules.baseline @@ -25,8 +25,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -67,8 +66,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -117,8 +115,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -167,8 +164,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -197,8 +193,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -247,8 +242,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -277,8 +271,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -307,8 +300,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -345,8 +337,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -387,8 +378,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -445,8 +435,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -503,8 +492,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -533,8 +521,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -571,8 +558,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -629,8 +615,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -659,8 +644,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -697,8 +681,7 @@ "kind": "moduleName" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsParameters.baseline b/tests/baselines/reference/quickInfoDisplayPartsParameters.baseline index c0451e35dbb..45f6128c2b1 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsParameters.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsParameters.baseline @@ -153,8 +153,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -203,8 +202,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -253,8 +251,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -303,8 +300,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -361,8 +357,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -411,8 +406,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -461,8 +455,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -511,8 +504,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -569,8 +561,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeAlias.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeAlias.baseline index 367acd4dbc4..49a97ac6773 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeAlias.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeAlias.baseline @@ -25,8 +25,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -71,8 +70,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -101,8 +99,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -143,8 +140,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -189,8 +185,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -239,8 +234,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInClass.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInClass.baseline index db995905483..48bd280a1b5 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInClass.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInClass.baseline @@ -37,8 +37,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -103,8 +102,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -193,8 +191,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -243,8 +240,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -309,8 +305,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -439,8 +434,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -585,8 +579,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -635,8 +628,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -781,8 +773,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -831,8 +822,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -897,8 +887,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -947,8 +936,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1001,8 +989,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1091,8 +1078,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1141,8 +1127,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1183,8 +1168,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1237,8 +1221,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1367,8 +1350,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1437,8 +1419,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1531,8 +1512,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1573,8 +1553,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1691,8 +1670,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1769,8 +1747,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1863,8 +1840,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2049,8 +2025,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2251,8 +2226,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2293,8 +2267,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2371,8 +2344,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2573,8 +2545,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2651,8 +2622,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2745,8 +2715,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2823,8 +2792,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2889,8 +2857,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3015,8 +2982,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3069,8 +3035,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3119,8 +3084,7 @@ "kind": "className" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3189,8 +3153,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3255,8 +3218,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3445,8 +3407,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3499,8 +3460,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3553,8 +3513,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunction.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunction.baseline index efe6ccd7130..278e9396fb6 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunction.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunction.baseline @@ -73,8 +73,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -175,8 +174,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -225,8 +223,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -327,8 +324,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -377,8 +373,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -455,8 +450,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -549,8 +543,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -667,8 +660,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -733,8 +725,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -851,8 +842,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -917,8 +907,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -995,8 +984,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunctionLikeInTypeAlias.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunctionLikeInTypeAlias.baseline index 92763ef5b10..50f0ac16a1c 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunctionLikeInTypeAlias.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInFunctionLikeInTypeAlias.baseline @@ -69,8 +69,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -143,8 +142,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -217,8 +215,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInInterface.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInInterface.baseline index 80da1f19ef9..715811f9918 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInInterface.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInInterface.baseline @@ -37,8 +37,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -103,8 +102,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -233,8 +231,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -283,8 +280,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -413,8 +409,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -463,8 +458,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -529,8 +523,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -659,8 +652,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -781,8 +773,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -831,8 +822,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -953,8 +943,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1003,8 +992,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1069,8 +1057,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1191,8 +1178,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1321,8 +1307,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1467,8 +1452,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1517,8 +1501,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1663,8 +1646,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1713,8 +1695,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1779,8 +1760,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1925,8 +1905,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1979,8 +1958,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2021,8 +1999,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2151,8 +2128,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2273,8 +2249,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2327,8 +2302,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2457,8 +2431,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2527,8 +2500,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2621,8 +2593,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2663,8 +2634,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2821,8 +2791,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2863,8 +2832,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -2941,8 +2909,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3099,8 +3066,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3177,8 +3143,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3271,8 +3236,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3429,8 +3393,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3579,8 +3542,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3621,8 +3583,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3699,8 +3660,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3849,8 +3809,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -3927,8 +3886,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4021,8 +3979,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4171,8 +4128,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4357,8 +4313,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4559,8 +4514,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4601,8 +4555,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4679,8 +4632,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4881,8 +4833,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -4959,8 +4910,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5053,8 +5003,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5255,8 +5204,7 @@ "kind": "typeParameterName" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5321,8 +5269,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5391,8 +5338,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5433,8 +5379,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5611,8 +5556,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5665,8 +5609,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5719,8 +5662,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5889,8 +5831,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5943,8 +5884,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -5997,8 +5937,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -6063,8 +6002,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -6253,8 +6191,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -6307,8 +6244,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -6361,8 +6297,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInTypeAlias.baseline b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInTypeAlias.baseline index 0f24ff6c767..e6f1d451288 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInTypeAlias.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsTypeParameterInTypeAlias.baseline @@ -61,8 +61,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -135,8 +134,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -209,8 +207,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -291,8 +288,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -381,8 +377,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -471,8 +466,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsVar.baseline b/tests/baselines/reference/quickInfoDisplayPartsVar.baseline index 250f10ff533..b56e1b31542 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsVar.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsVar.baseline @@ -37,8 +37,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -87,8 +86,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -129,8 +127,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -171,8 +168,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -221,8 +217,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -283,8 +278,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -345,8 +339,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -407,8 +400,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -469,8 +461,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -615,8 +606,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -761,8 +751,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -907,8 +896,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1013,8 +1001,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1119,8 +1106,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsVar.shims-pp.baseline b/tests/baselines/reference/quickInfoDisplayPartsVar.shims-pp.baseline index 5d072155c95..dfe65565790 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsVar.shims-pp.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsVar.shims-pp.baseline @@ -37,8 +37,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -87,8 +86,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -129,8 +127,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -171,8 +168,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -221,8 +217,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -283,8 +278,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -345,8 +339,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -407,8 +400,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -469,8 +461,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -615,8 +606,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -761,8 +751,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -907,8 +896,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1013,8 +1001,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1119,8 +1106,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsVar.shims.baseline b/tests/baselines/reference/quickInfoDisplayPartsVar.shims.baseline index 448595e3f64..249772f416e 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsVar.shims.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsVar.shims.baseline @@ -37,8 +37,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -87,8 +86,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -129,8 +127,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -171,8 +168,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -221,8 +217,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -283,8 +278,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -345,8 +339,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -407,8 +400,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -469,8 +461,7 @@ "kind": "keyword" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -615,8 +606,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -761,8 +751,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -907,8 +896,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1013,8 +1001,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -1119,8 +1106,7 @@ "kind": "punctuation" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/baselines/reference/quickInfoDisplayPartsVarWithStringTypes01.baseline b/tests/baselines/reference/quickInfoDisplayPartsVarWithStringTypes01.baseline index 92a09a4d7fa..3c46a6ba6bd 100644 --- a/tests/baselines/reference/quickInfoDisplayPartsVarWithStringTypes01.baseline +++ b/tests/baselines/reference/quickInfoDisplayPartsVarWithStringTypes01.baseline @@ -37,8 +37,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -79,8 +78,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } }, { @@ -137,8 +135,7 @@ "kind": "stringLiteral" } ], - "documentation": [], - "tags": [] + "documentation": [] } } ] \ No newline at end of file diff --git a/tests/cases/fourslash/commentsCommentParsing.ts b/tests/cases/fourslash/commentsCommentParsing.ts index df3adca4c87..8f7d35ce0f9 100644 --- a/tests/cases/fourslash/commentsCommentParsing.ts +++ b/tests/cases/fourslash/commentsCommentParsing.ts @@ -244,8 +244,18 @@ verify.quickInfoAt("13q", "function noHelpComment2(): void"); verify.signatureHelp({ marker: "14", docComment: "" }); verify.quickInfoAt("14q", "function noHelpComment3(): void"); -goTo.marker('15'); -verify.completionListContains("sum", "function sum(a: number, b: number): number", "Adds two integers and returns the result"); +verify.completions({ + marker: "15", + includes: { + name: "sum", + text: "function sum(a: number, b: number): number", + documentation: "Adds two integers and returns the result", + tags: [ + { name: "param", text: "a first number" }, + { name: "param", text: "b second number" }, + ], + }, +}); const addTags: ReadonlyArray = [ { name: "param", text: "a first number" }, diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 2fb29e245da..cf4752a65ab 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -299,7 +299,7 @@ declare namespace FourSlashInterface { rangesAreDocumentHighlights(ranges?: Range[], options?: VerifyDocumentHighlightsOptions): void; rangesWithSameTextAreDocumentHighlights(): void; documentHighlightsOf(startRange: Range, ranges: Range[], options?: VerifyDocumentHighlightsOptions): void; - completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: ts.JSDocTagInfo[]): void; + completionEntryDetailIs(entryName: string, text: string, documentation?: string, kind?: string, tags?: JSDocTagInfo[]): void; /** * This method *requires* a contiguous, complete, and ordered stream of classifications for a file. */ @@ -331,7 +331,7 @@ declare namespace FourSlashInterface { verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: { start: number; length: number; - }, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: { name: string, text?: string }[]): void; + }, displayParts: ts.SymbolDisplayPart[], documentation: ts.SymbolDisplayPart[], tags: { name: string, text?: string }[] | undefined): void; getSyntacticDiagnostics(expected: ReadonlyArray): void; getSemanticDiagnostics(expected: ReadonlyArray): void; getSuggestionDiagnostics(expected: ReadonlyArray): void; @@ -550,6 +550,7 @@ declare namespace FourSlashInterface { // details readonly text?: string, readonly documentation?: string, + readonly tags?: ReadonlyArray; readonly sourceDisplay?: string, }; @@ -632,8 +633,8 @@ declare namespace FourSlashInterface { } interface JSDocTagInfo { - name: string; - text: string | undefined; + readonly name: string; + readonly text: string | undefined; } type ArrayOrSingle = T | ReadonlyArray; diff --git a/tests/cases/fourslash/jsDocFunctionSignatures9.ts b/tests/cases/fourslash/jsDocFunctionSignatures9.ts index 6c3342c0a3f..68c906b93ef 100644 --- a/tests/cases/fourslash/jsDocFunctionSignatures9.ts +++ b/tests/cases/fourslash/jsDocFunctionSignatures9.ts @@ -20,4 +20,4 @@ verify.verifyQuickInfoDisplayParts('function', {"text": "void", "kind": "keyword"} ], [{"text": "first line of the comment\n\nthird line", "kind": "text"}], - []); + undefined); diff --git a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts index 1c499efc7e2..d915c55e320 100644 --- a/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts +++ b/tests/cases/fourslash/server/completionEntryDetailAcrossFiles02.ts @@ -15,6 +15,6 @@ //// a.fo/*2*/ verify.completions( - { marker: "1", includes: { name: "foo", text: "var foo: (p1: string) => void", documentation: "Modify the parameter" } }, - { marker: "2", exact: { name: "foo", text: "(property) a.foo: (p1: string) => void", documentation: "Modify the parameter" } }, + { marker: "1", includes: { name: "foo", text: "var foo: (p1: string) => void", documentation: "Modify the parameter", tags: [{ name: "param", text: "p1" }] } }, + { marker: "2", exact: { name: "foo", text: "(property) a.foo: (p1: string) => void", documentation: "Modify the parameter", tags: [{ name: "param", text: "p1" }] } }, ); From 905578cf371ad287bf3b975ecdb8c4a43c20270b Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 13 Sep 2018 09:02:02 -0700 Subject: [PATCH 113/146] Use existing identifier when possible for renaming functions --- src/services/codefixes/convertToAsyncFunction.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 235f50226eb..51511c2207c 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -178,10 +178,11 @@ namespace ts.codefix { // if the identifier refers to a function we want to add the new synthesized variable for the declaration (ex. blob in let blob = res(arg)) // Note - the choice of the last call signature is arbitrary if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { - const name = lastCallSignature.parameters[0].name; - const synthName = getNewNameIfConflict(createIdentifier(name), allVarNames); + const firstParameter = lastCallSignature.parameters[0]; + const ident = isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || createOptimisticUniqueName("result"); + const synthName = getNewNameIfConflict(ident, allVarNames); synthNamesMap.set(symbolIdString, synthName); - allVarNames.push({ identifier: synthName.identifier, symbol, originalName: name }); + allVarNames.push({ identifier: synthName.identifier, symbol, originalName: ident.text }); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { @@ -449,7 +450,7 @@ namespace ts.codefix { function getLastCallSignature(type: Type, checker: TypeChecker): Signature | undefined { const callSignatures = checker.getSignaturesOfType(type, SignatureKind.Call); - return callSignatures && callSignatures[callSignatures.length - 1]; + return lastOrUndefined(callSignatures); } From 504b5f298542236b902892d6af66b4eab2cc966c Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 13 Sep 2018 09:04:52 -0700 Subject: [PATCH 114/146] Add and update tests --- .../unittests/convertToAsyncFunction.ts | 10 ++++++++++ .../convertToAsyncFunction_bindingPattern.ts | 4 ++-- ...yncFunction_bindingPatternNameCollision.ts | 20 +++++++++++++++++++ 3 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index f774c58de94..05df4f297e8 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -1207,6 +1207,16 @@ function [#|f|]():Promise { function res({ status, trailer }){ console.log(status); } +`); + + _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` +function [#|f|]():Promise { + const result = 'https://typescriptlang.org'; + return fetch(result).then(res); +} +function res({ status, trailer }){ + console.log(status); +} `); }); diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts index f7d26faa980..97c68d57260 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts @@ -10,8 +10,8 @@ function res({ status, trailer }){ // ==ASYNC FUNCTION::Convert to async function== async function f():Promise { - const __0 = await fetch('https://typescriptlang.org'); - return res(__0); + const result = await fetch('https://typescriptlang.org'); + return res(result); } function res({ status, trailer }){ console.log(status); diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts new file mode 100644 index 00000000000..db0c63535c7 --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts @@ -0,0 +1,20 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/():Promise { + const result = 'https://typescriptlang.org'; + return fetch(result).then(res); +} +function res({ status, trailer }){ + console.log(status); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f():Promise { + const result = 'https://typescriptlang.org'; + const result_1 = await fetch(result); + return res(result_1); +} +function res({ status, trailer }){ + console.log(status); +} From d12110d3e5fe2682fa9f89718c033d975924d306 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 13 Sep 2018 09:32:38 -0700 Subject: [PATCH 115/146] Respond to CR --- .../codefixes/convertToAsyncFunction.ts | 5 +++-- src/services/utilities.ts | 11 +++++----- .../unittests/convertToAsyncFunction.ts | 6 +++--- ...convertToAsyncFunction_MultipleReturns2.ts | 4 ++-- .../convertToAsyncFunction_bindingPattern.js | 18 +++++++++++++++++ .../convertToAsyncFunction_bindingPattern.ts | 4 ++-- ...yncFunction_bindingPatternNameCollision.js | 20 +++++++++++++++++++ ...yncFunction_bindingPatternNameCollision.ts | 4 ++-- 8 files changed, 55 insertions(+), 17 deletions(-) create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.js create mode 100644 tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.js diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index 51511c2207c..e698218baf9 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -186,20 +186,21 @@ namespace ts.codefix { } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { + const originalName = node.text; // if the identifier name conflicts with a different identifier that we've already seen if (allVarNames.some(ident => ident.originalName === node.text && ident.symbol !== symbol)) { const newName = getNewNameIfConflict(node, allVarNames); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - allVarNames.push({ identifier: newName.identifier, symbol, originalName: node.text }); + allVarNames.push({ identifier: newName.identifier, symbol, originalName }); } else { const identifier = getSynthesizedDeepClone(node); identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { - allVarNames.push({ identifier, symbol, originalName: node.text }); + allVarNames.push({ identifier, symbol, originalName }); } } } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 4559a88881e..01613a23b0d 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1654,11 +1654,10 @@ namespace ts { return clone; } - export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { - + export function getSynthesizedDeepCloneWithRenames(node: T, includeTrivia = true, renameMap?: Map, checker?: TypeChecker, callback?: (originalNode: Node, clone: Node) => any): T { let clone; - if (node && isIdentifier(node!) && renameMap && checker) { - const symbol = checker.getSymbolAtLocation(node!); + if (isIdentifier(node) && renameMap && checker) { + const symbol = checker.getSymbolAtLocation(node); const renameInfo = symbol && renameMap.get(String(getSymbolId(symbol))); if (renameInfo) { @@ -1667,11 +1666,11 @@ namespace ts { } if (!clone) { - clone = node && getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); + clone = getSynthesizedDeepCloneWorker(node as NonNullable, renameMap, checker, callback); } if (clone && !includeTrivia) suppressLeadingAndTrailingTrivia(clone); - if (callback && node && clone) callback(node!, clone); + if (callback && clone) callback(node, clone); return clone as T; } diff --git a/src/testRunner/unittests/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 05df4f297e8..047df5ffadc 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/convertToAsyncFunction.ts @@ -823,7 +823,7 @@ function [#|f|](): Promise { } return x.then(resp => { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); - return fetch("https://micorosft.com").then(res => console.log("Another one!")); + return fetch("https://microsoft.com").then(res => console.log("Another one!")); }); } ` @@ -1201,7 +1201,7 @@ function [#|f|]() { `); _testConvertToAsyncFunction("convertToAsyncFunction_bindingPattern", ` -function [#|f|]():Promise { +function [#|f|]() { return fetch('https://typescriptlang.org').then(res); } function res({ status, trailer }){ @@ -1210,7 +1210,7 @@ function res({ status, trailer }){ `); _testConvertToAsyncFunction("convertToAsyncFunction_bindingPatternNameCollision", ` -function [#|f|]():Promise { +function [#|f|]() { const result = 'https://typescriptlang.org'; return fetch(result).then(res); } diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts index 389faf61891..59a02875d84 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_MultipleReturns2.ts @@ -7,7 +7,7 @@ function /*[#|*/f/*|]*/(): Promise { } return x.then(resp => { var blob = resp.blob().then(blob => blob.byteOffset).catch(err => 'Error'); - return fetch("https://micorosft.com").then(res => console.log("Another one!")); + return fetch("https://microsoft.com").then(res => console.log("Another one!")); }); } @@ -21,6 +21,6 @@ async function f(): Promise { } const resp = await x; var blob = resp.blob().then(blob_1 => blob_1.byteOffset).catch(err => 'Error'); - const res_2 = await fetch("https://micorosft.com"); + const res_2 = await fetch("https://microsoft.com"); return console.log("Another one!"); } diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.js new file mode 100644 index 00000000000..f06ce44e78b --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.js @@ -0,0 +1,18 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + return fetch('https://typescriptlang.org').then(res); +} +function res({ status, trailer }){ + console.log(status); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + const result = await fetch('https://typescriptlang.org'); + return res(result); +} +function res({ status, trailer }){ + console.log(status); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts index 97c68d57260..f06ce44e78b 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPattern.ts @@ -1,6 +1,6 @@ // ==ORIGINAL== -function /*[#|*/f/*|]*/():Promise { +function /*[#|*/f/*|]*/() { return fetch('https://typescriptlang.org').then(res); } function res({ status, trailer }){ @@ -9,7 +9,7 @@ function res({ status, trailer }){ // ==ASYNC FUNCTION::Convert to async function== -async function f():Promise { +async function f() { const result = await fetch('https://typescriptlang.org'); return res(result); } diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.js b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.js new file mode 100644 index 00000000000..6813472966a --- /dev/null +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.js @@ -0,0 +1,20 @@ +// ==ORIGINAL== + +function /*[#|*/f/*|]*/() { + const result = 'https://typescriptlang.org'; + return fetch(result).then(res); +} +function res({ status, trailer }){ + console.log(status); +} + +// ==ASYNC FUNCTION::Convert to async function== + +async function f() { + const result = 'https://typescriptlang.org'; + const result_1 = await fetch(result); + return res(result_1); +} +function res({ status, trailer }){ + console.log(status); +} diff --git a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts index db0c63535c7..6813472966a 100644 --- a/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts +++ b/tests/baselines/reference/convertToAsyncFunction/convertToAsyncFunction_bindingPatternNameCollision.ts @@ -1,6 +1,6 @@ // ==ORIGINAL== -function /*[#|*/f/*|]*/():Promise { +function /*[#|*/f/*|]*/() { const result = 'https://typescriptlang.org'; return fetch(result).then(res); } @@ -10,7 +10,7 @@ function res({ status, trailer }){ // ==ASYNC FUNCTION::Convert to async function== -async function f():Promise { +async function f() { const result = 'https://typescriptlang.org'; const result_1 = await fetch(result); return res(result_1); From e700022cef4dbee7b10d44f91d0320d2a89d8922 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Thu, 13 Sep 2018 09:46:40 -0700 Subject: [PATCH 116/146] Remove unnecessary case --- src/services/codefixes/convertToAsyncFunction.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index e698218baf9..bceee6811bb 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -520,10 +520,6 @@ namespace ts.codefix { name = getMapEntryIfExists(param); } } - // currently not relevant, since we don't produce a valid transformation if the argument to a promise operation is a CallExpression - else if (isCallExpression(funcNode) && funcNode.arguments.length > 0 && isIdentifier(funcNode.arguments[0])) { - name = { identifier: funcNode.arguments[0] as Identifier, types, numberOfAssignmentsOriginal }; - } else if (isIdentifier(funcNode)) { name = getMapEntryIfExists(funcNode); } From 37c3c5d8bb165dd5c08e0789c1b08184cc99cc9d Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 13 Sep 2018 09:24:54 -0700 Subject: [PATCH 117/146] Refactoring --- src/tsc/tsc.ts | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index 523fcefd88c..29cac24fdd0 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -53,14 +53,10 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - const result = performBuild(args.slice(1)); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === CharacterCodes.minus) { + const firstOption = args[0].slice(args[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } @@ -164,17 +160,17 @@ namespace ts { } } - function performBuild(args: string[]): number | undefined { + function performBuild(args: string[]) { const { buildOptions, projects, errors } = parseBuildCommand(args); if (errors.length > 0) { errors.forEach(reportDiagnostic); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.help) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } // Update to pretty if host supports it @@ -182,12 +178,12 @@ namespace ts { if (projects.length === 0) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.watch) { reportWatchModeWithoutSysSupport(); @@ -196,16 +192,15 @@ namespace ts { // TODO: change this to host if watch => watchHost otherwiue without wathc const builder = createSolutionBuilder(createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); if (buildOptions.clean) { - return builder.cleanAllProjects(); + return sys.exit(builder.cleanAllProjects()); } if (buildOptions.watch) { builder.buildAllProjects(); - builder.startWatching(); - return undefined; + return builder.startWatching(); } - return builder.buildAllProjects(); + return sys.exit(builder.buildAllProjects()); } function performCompilation(rootNames: string[], projectReferences: ReadonlyArray | undefined, options: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { From 0d60348e45035ffacb775f8e1b4621ea7d1eb562 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 13 Sep 2018 09:54:35 -0700 Subject: [PATCH 118/146] Unify the commandline parsing worker --- src/compiler/commandLineParser.ts | 70 ++++++++++++++-------------- src/compiler/diagnosticMessages.json | 15 +++--- src/compiler/tsbuild.ts | 16 +++++-- 3 files changed, 58 insertions(+), 43 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 055bccbb2ad..0d7b6f6085c 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -62,7 +62,8 @@ namespace ts { /* @internal */ export const libMap = createMapFromEntries(libEntries); - const commonOptionsWithBuild: CommandLineOption[] = [ + /* @internal */ + export const commonOptionsWithBuild: CommandLineOption[] = [ { name: "help", shortName: "h", @@ -903,17 +904,27 @@ namespace ts { } } - export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { - const options: CompilerOptions = {}; + /* @internal */ + export interface OptionsBase { + [option: string]: CompilerOptionsValue | undefined; + } + + /** Tuple with error messages for 'unknown compiler option', 'option requires type' */ + type ParseCommandLineWorkerDiagnostics = [DiagnosticMessage, DiagnosticMessage]; + + function parseCommandLineWorker( + getOptionNameMap: () => OptionNameMap, + [unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics, + commandLine: ReadonlyArray, + readFile?: (path: string) => string | undefined) { + const options = {} as T; const fileNames: string[] = []; - const projectReferences: ProjectReference[] | undefined = undefined; const errors: Diagnostic[] = []; parseStrings(commandLine); return { options, fileNames, - projectReferences, errors }; @@ -926,7 +937,7 @@ namespace ts { parseResponseFile(s.slice(1)); } else if (s.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionFromName(s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); + const opt = getOptionDeclarationFromName(getOptionNameMap, s.slice(s.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); if (opt) { if (opt.isTSConfigOnly) { errors.push(createCompilerDiagnostic(Diagnostics.Option_0_can_only_be_specified_in_tsconfig_json_file, opt.name)); @@ -934,7 +945,7 @@ namespace ts { else { // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { - errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_expects_an_argument, opt.name)); + errors.push(createCompilerDiagnostic(optionTypeMismatchDiagnostic, opt.name)); } switch (opt.type) { @@ -971,7 +982,7 @@ namespace ts { } } else { - errors.push(createCompilerDiagnostic(Diagnostics.Unknown_compiler_option_0, s)); + errors.push(createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -1014,13 +1025,19 @@ namespace ts { } } + export function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine { + return parseCommandLineWorker(getOptionNameMap, [ + Diagnostics.Unknown_compiler_option_0, + Diagnostics.Compiler_option_0_expects_an_argument + ], commandLine, readFile); + } + /** @internal */ export function getOptionFromName(optionName: string, allowShort?: boolean): CommandLineOption | undefined { return getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort); } - /*@internal*/ - export function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { + function getOptionDeclarationFromName(getOptionNameMap: () => OptionNameMap, optionName: string, allowShort = false): CommandLineOption | undefined { optionName = optionName.toLowerCase(); const { optionNameMap, shortOptionNames } = getOptionNameMap(); // Try to translate short option names to their full equivalents. @@ -1044,25 +1061,10 @@ namespace ts { export function parseBuildCommand(args: string[]): ParsedBuildCommand { let buildOptionNameMap: OptionNameMap | undefined; const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts))); - - const buildOptions: BuildOptions = {}; - const projects: string[] = []; - let errors: Diagnostic[] | undefined; - for (const arg of args) { - if (arg.charCodeAt(0) === CharacterCodes.minus) { - const opt = getOptionDeclarationFromName(returnBuildOptionNameMap, arg.slice(arg.charCodeAt(1) === CharacterCodes.minus ? 2 : 1), /*allowShort*/ true); - if (opt) { - buildOptions[opt.name as keyof BuildOptions] = true; - } - else { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Unknown_build_option_0, arg)); - } - } - else { - // Not a flag, parse as filename - projects.push(arg); - } - } + const { options: buildOptions, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ + Diagnostics.Unknown_build_option_0, + Diagnostics.Build_option_0_requires_a_value_of_type_1 + ], args); if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." @@ -1071,19 +1073,19 @@ namespace ts { // Nonsensical combinations if (buildOptions.clean && buildOptions.force) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force")); } if (buildOptions.clean && buildOptions.verbose) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose")); } if (buildOptions.clean && buildOptions.watch) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch")); } if (buildOptions.watch && buildOptions.dry) { - (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); + errors.push(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry")); } - return { buildOptions, projects, errors: errors || emptyArray }; + return { buildOptions, projects, errors }; } function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 56a255bead6..941250c467d 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2920,7 +2920,10 @@ "category": "Error", "code": 5072 }, - + "Build option '{0}' requires a value of type {1}.": { + "category": "Error", + "code": 5073 + }, "Generates a sourcemap for each corresponding '.d.ts' file.": { "category": "Message", @@ -4604,7 +4607,7 @@ "category": "Message", "code": 95062 }, - + "Add missing enum member '{0}'": { "category": "Message", "code": 95063 @@ -4613,12 +4616,12 @@ "category": "Message", "code": 95064 }, - "Convert to async function":{ + "Convert to async function": { "category": "Message", - "code": 95065 + "code": 95065 }, "Convert all to async functions": { - "category": "Message", - "code": 95066 + "category": "Message", + "code": 95066 } } diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 2c064bea137..8947310c1af 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -17,7 +17,7 @@ namespace ts { referencingProjectsMap: ConfigFileMap>; } - export interface BuildOptions { + export interface BuildOptions extends OptionsBase { dry?: boolean; force?: boolean; verbose?: boolean; @@ -370,6 +370,14 @@ namespace ts { return host; } + function getCompilerOptionsOfBuildOptions(buildOptions: BuildOptions): CompilerOptions { + const result = {} as CompilerOptions; + commonOptionsWithBuild.forEach(option => { + result[option.name] = buildOptions[option.name]; + }); + return result; + } + /** * A SolutionBuilder has an immutable set of rootNames that are the "entry point" projects, but * can dynamically add/remove other projects based on changes on the rootNames' references @@ -384,6 +392,7 @@ namespace ts { // State of the solution let options = defaultOptions; + let baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); type ConfigFileCacheEntry = ParsedCommandLine | Diagnostic; const configFileCache = createFileMap(toPath); /** Map from output file name to its pre-build timestamp */ @@ -430,6 +439,7 @@ namespace ts { function resetBuildContext(opts = defaultOptions) { options = opts; + baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); configFileCache.clear(); unchangedOutputs.clear(); projectStatus.clear(); @@ -463,7 +473,7 @@ namespace ts { let diagnostic: Diagnostic | undefined; parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = d => diagnostic = d; - const parsed = getParsedCommandLineOfConfigFile(configFilePath, {}, parseConfigFileHost); + const parsed = getParsedCommandLineOfConfigFile(configFilePath, baseCompilerOptions, parseConfigFileHost); parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = noop; configFileCache.setValue(configFilePath, parsed || diagnostic!); return parsed; @@ -475,7 +485,7 @@ namespace ts { function reportWatchStatus(message: DiagnosticMessage, ...args: (string | number | undefined)[]) { if (hostWithWatch.onWatchStatusChange) { - hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), { preserveWatchOutput: options.preserveWatchOutput }); + hostWithWatch.onWatchStatusChange(createCompilerDiagnostic(message, ...args), host.getNewLine(), baseCompilerOptions); } } From 4cf746cdc40f822efcb664e97ea46263bc3cb025 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 13 Sep 2018 11:17:03 -0700 Subject: [PATCH 119/146] Enable listFiles and listEmittedFiles as build option --- src/compiler/commandLineParser.ts | 24 ++++++------ src/compiler/tsbuild.ts | 38 ++++++++++++------- src/compiler/watch.ts | 6 +-- src/testRunner/unittests/tsbuild.ts | 57 +++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 29 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 0d7b6f6085c..9391fac72ed 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -84,6 +84,18 @@ namespace ts { category: Diagnostics.Command_line_Options, description: Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen, }, + { + name: "listFiles", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_files_part_of_the_compilation + }, + { + name: "listEmittedFiles", + type: "boolean", + category: Diagnostics.Advanced_Options, + description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation + }, { name: "watch", shortName: "w", @@ -562,18 +574,6 @@ namespace ts { category: Diagnostics.Advanced_Options, description: Diagnostics.Include_modules_imported_with_json_extension }, - { - name: "listFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_files_part_of_the_compilation - }, - { - name: "listEmittedFiles", - type: "boolean", - category: Diagnostics.Advanced_Options, - description: Diagnostics.Print_names_of_generated_files_part_of_the_compilation - }, { name: "out", diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 8947310c1af..58b470b8b9d 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -21,10 +21,14 @@ namespace ts { dry?: boolean; force?: boolean; verbose?: boolean; + /*@internal*/ clean?: boolean; /*@internal*/ watch?: boolean; /*@internal*/ help?: boolean; + preserveWatchOutput?: boolean; + listEmittedFiles?: boolean; + listFiles?: boolean; } enum BuildResultFlags { @@ -44,8 +48,9 @@ namespace ts { SyntaxErrors = 1 << 3, TypeErrors = 1 << 4, DeclarationEmitErrors = 1 << 5, + EmitErrors = 1 << 6, - AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors + AnyErrors = ConfigFileErrors | SyntaxErrors | TypeErrors | DeclarationEmitErrors | EmitErrors } export enum UpToDateStatusType { @@ -401,6 +406,7 @@ namespace ts { const projectStatus = createFileMap(toPath); const missingRoots = createMap(); let globalDependencyGraph: DependencyGraph | undefined; + const writeFileName = (s: string) => host.trace && host.trace(s); // Watch state const diagnostics = createFileMap>(toPath); @@ -1014,35 +1020,28 @@ namespace ts { ...program.getConfigFileParsingDiagnostics(), ...program.getSyntacticDiagnostics()]; if (syntaxDiagnostics.length) { - resultFlags |= BuildResultFlags.SyntaxErrors; - reportAndStoreErrors(proj, syntaxDiagnostics); - projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Syntactic errors" }); - return resultFlags; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // Don't emit .d.ts if there are decl file errors if (getEmitDeclarations(program.getCompilerOptions())) { const declDiagnostics = program.getDeclarationDiagnostics(); if (declDiagnostics.length) { - resultFlags |= BuildResultFlags.DeclarationEmitErrors; - reportAndStoreErrors(proj, declDiagnostics); - projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Declaration file errors" }); - return resultFlags; + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // Same as above but now for semantic diagnostics const semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { - resultFlags |= BuildResultFlags.TypeErrors; - reportAndStoreErrors(proj, semanticDiagnostics); - projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: "Semantic errors" }); - return resultFlags; + return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } let newestDeclarationFileContentChangedTime = minimumDate; let anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => { + let emitDiagnostics: Diagnostic[] | undefined; + const reportEmitDiagnostic = (d: Diagnostic) => (emitDiagnostics || (emitDiagnostics = [])).push(d); + emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, (fileName, content, writeBom, onError) => { let priorChangeTime: Date | undefined; if (!anyDtsChanged && isDeclarationFile(fileName)) { // Check for unchanged .d.ts files @@ -1062,12 +1061,23 @@ namespace ts { } }); + if (emitDiagnostics) { + return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); + } + const status: UpToDateStatus = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; projectStatus.setValue(proj, status); return resultFlags; + + function buildErrors(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` }); + return resultFlags; + } } function updateOutputTimestamps(proj: ParsedCommandLine) { diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index c091ad5c30c..f442a1a88e8 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -101,7 +101,7 @@ namespace ts { getGlobalDiagnostics(): ReadonlyArray; getSemanticDiagnostics(): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; - emit(): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; } export type ReportEmitErrorSummary = (errorCount: number) => void; @@ -109,7 +109,7 @@ namespace ts { /** * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ - export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary) { + export function emitFilesAndReportErrors(program: ProgramToEmitFilesAndReportErrors, reportDiagnostic: DiagnosticReporter, writeFileName?: (s: string) => void, reportSummary?: ReportEmitErrorSummary, writeFile?: WriteFileCallback) { // First get and report any syntactic errors. const diagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = diagnostics.length; @@ -128,7 +128,7 @@ namespace ts { } // Emit and report any errors we ran into. - const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(); + const { emittedFiles, emitSkipped, diagnostics: emitDiagnostics } = program.emit(/*targetSourceFile*/ undefined, writeFile); addRange(diagnostics, emitDiagnostics); if (reportSemanticDiagnostics) { diff --git a/src/testRunner/unittests/tsbuild.ts b/src/testRunner/unittests/tsbuild.ts index 6ddd6d069f7..f54e3c93215 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -264,6 +264,63 @@ export class cNew {}`); verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeAndFiles.json"); }); }); + + describe("tsbuild - lists files", () => { + it("listFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + ...getLibs(), + "/src/core/anotherModule.ts", + "/src/core/index.ts", + "/src/core/some_decl.d.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.ts", + ...getLibs(), + ...getCoreOutputs(), + "/src/logic/index.d.ts", + "/src/tests/index.ts" + ]); + + function getLibs() { + return [ + "/lib/lib.d.ts", + "/lib/lib.es5.d.ts", + "/lib/lib.dom.d.ts", + "/lib/lib.webworker.importscripts.d.ts", + "/lib/lib.scripthost.d.ts" + ]; + } + + function getCoreOutputs() { + return [ + "/src/core/index.d.ts", + "/src/core/anotherModule.d.ts" + ]; + } + }); + + it("listEmittedFiles", () => { + const fs = projFs.shadow(); + const host = new fakes.SolutionBuilderHost(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], { listEmittedFiles: true }); + builder.buildAllProjects(); + assert.deepEqual(host.traces, [ + "TSFILE: /src/core/anotherModule.js", + "TSFILE: /src/core/anotherModule.d.ts", + "TSFILE: /src/core/index.js", + "TSFILE: /src/core/index.d.ts", + "TSFILE: /src/logic/index.js", + "TSFILE: /src/logic/index.js.map", + "TSFILE: /src/logic/index.d.ts", + "TSFILE: /src/tests/index.js", + "TSFILE: /src/tests/index.d.ts", + ]); + }); + }); } export namespace OutFile { From 1a69f78fba3340013a353ecb72c9d8fe6dc4f310 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 13 Sep 2018 12:53:46 -0700 Subject: [PATCH 120/146] Fix bug: Ensure `export =` symbol always has a valueDeclaration (#26973) --- src/compiler/binder.ts | 27 ++++++++++++------- ...ForConflictingExportEqualsValue.errors.txt | 9 ++++--- .../errorForConflictingExportEqualsValue.js | 10 ++++--- ...rorForConflictingExportEqualsValue.symbols | 10 ++++--- ...errorForConflictingExportEqualsValue.types | 10 ++++--- .../errorForConflictingExportEqualsValue.ts | 5 +++- 6 files changed, 47 insertions(+), 24 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 489f212967d..3205b2c5a55 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -234,13 +234,17 @@ namespace ts { } if (symbolFlags & SymbolFlags.Value) { - const { valueDeclaration } = symbol; - if (!valueDeclaration || - (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || - (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { - // other kinds of value declarations take precedence over modules and assignment declarations - symbol.valueDeclaration = node; - } + setValueDeclaration(symbol, node); + } + } + + function setValueDeclaration(symbol: Symbol, node: Declaration): void { + const { valueDeclaration } = symbol; + if (!valueDeclaration || + (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) || + (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) { + // other kinds of value declarations take precedence over modules and assignment declarations + symbol.valueDeclaration = node; } } @@ -2286,14 +2290,19 @@ namespace ts { bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)!); } else { - const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) + const flags = exportAssignmentIsAlias(node) // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression; ? SymbolFlags.Alias // An export default clause with any other expression exports a value : SymbolFlags.Property; // If there is an `export default x;` alias declaration, can't `export default` anything else. // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.) - declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + const symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.All); + + if (node.isExportEquals) { + // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set. + setValueDeclaration(symbol, node); + } } } diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt b/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt index 9a5858f46ab..19ebd6ebb20 100644 --- a/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.errors.txt @@ -1,9 +1,10 @@ -tests/cases/compiler/errorForConflictingExportEqualsValue.ts(2,1): error TS2309: An export assignment cannot be used in a module with other exported elements. +/a.ts(2,1): error TS2309: An export assignment cannot be used in a module with other exported elements. -==== tests/cases/compiler/errorForConflictingExportEqualsValue.ts (1 errors) ==== +==== /a.ts (1 errors) ==== export var x; - export = {}; - ~~~~~~~~~~~~ + export = x; + ~~~~~~~~~~~ !!! error TS2309: An export assignment cannot be used in a module with other exported elements. + import("./a"); \ No newline at end of file diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.js b/tests/baselines/reference/errorForConflictingExportEqualsValue.js index 88762e7e846..65adec35902 100644 --- a/tests/baselines/reference/errorForConflictingExportEqualsValue.js +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.js @@ -1,8 +1,10 @@ -//// [errorForConflictingExportEqualsValue.ts] +//// [a.ts] export var x; -export = {}; +export = x; +import("./a"); -//// [errorForConflictingExportEqualsValue.js] +//// [a.js] "use strict"; -module.exports = {}; +Promise.resolve().then(function () { return require("./a"); }); +module.exports = exports.x; diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.symbols b/tests/baselines/reference/errorForConflictingExportEqualsValue.symbols index a66ef69c1cb..138f37f4a5e 100644 --- a/tests/baselines/reference/errorForConflictingExportEqualsValue.symbols +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.symbols @@ -1,6 +1,10 @@ -=== tests/cases/compiler/errorForConflictingExportEqualsValue.ts === +=== /a.ts === export var x; ->x : Symbol(x, Decl(errorForConflictingExportEqualsValue.ts, 0, 10)) +>x : Symbol(x, Decl(a.ts, 0, 10)) -export = {}; +export = x; +>x : Symbol(x, Decl(a.ts, 0, 10)) + +import("./a"); +>"./a" : Symbol("/a", Decl(a.ts, 0, 0)) diff --git a/tests/baselines/reference/errorForConflictingExportEqualsValue.types b/tests/baselines/reference/errorForConflictingExportEqualsValue.types index f2484e83d0d..b9915169120 100644 --- a/tests/baselines/reference/errorForConflictingExportEqualsValue.types +++ b/tests/baselines/reference/errorForConflictingExportEqualsValue.types @@ -1,7 +1,11 @@ -=== tests/cases/compiler/errorForConflictingExportEqualsValue.ts === +=== /a.ts === export var x; >x : any -export = {}; ->{} : {} +export = x; +>x : any + +import("./a"); +>import("./a") : Promise +>"./a" : "./a" diff --git a/tests/cases/compiler/errorForConflictingExportEqualsValue.ts b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts index 59af1f46690..a91ecc390b5 100644 --- a/tests/cases/compiler/errorForConflictingExportEqualsValue.ts +++ b/tests/cases/compiler/errorForConflictingExportEqualsValue.ts @@ -1,2 +1,5 @@ +// @lib: es6 +// @Filename: /a.ts export var x; -export = {}; +export = x; +import("./a"); From 4ed63e52ef130ee82e2191769985fa162c2154f6 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 13 Sep 2018 13:00:06 -0700 Subject: [PATCH 121/146] Add test for preserveWatchOutput on command line #26873 --- src/testRunner/unittests/tsbuildWatchMode.ts | 58 ++++++++++++-------- 1 file changed, 34 insertions(+), 24 deletions(-) diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index d9dcda94bff..563200b1cf5 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -2,7 +2,7 @@ namespace ts.tscWatch { export import libFile = TestFSWithWatch.libFile; function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { const host = createSolutionBuilderWithWatchHost(system); - return ts.createSolutionBuilder(host, rootNames, defaultOptions || { dry: false, force: false, verbose: false, watch: true }); + return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true }); } function createSolutionBuilderWithWatch(host: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { @@ -95,11 +95,11 @@ namespace ts.tscWatch { const allFiles: ReadonlyArray = [libFile, ...core, ...logic, ...tests, ...ui]; const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path); - function createSolutionInWatchMode(allFiles: ReadonlyArray) { + function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation }); - createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`]); + createSolutionBuilderWithWatch(host, [`${project}/${SubProject.tests}`], defaultOptions); verifyWatches(host); - checkOutputErrorsInitial(host, emptyArray); + checkOutputErrorsInitial(host, emptyArray, disableConsoleClears); const outputFileStamps = getOutputFileStamps(host); for (const stamp of outputFileStamps) { assert.isDefined(stamp[1], `${stamp[0]} expected to be present`); @@ -351,32 +351,42 @@ function myFunc() { return 100; }`); } }); - it("reports errors in all projects on incremental compile", () => { - const host = createSolutionInWatchMode(allFiles); - const outputFileStamps = getOutputFileStamps(host); + describe("reports errors in all projects on incremental compile", () => { + function verifyIncrementalErrors(defaultBuildOptions?: BuildOptions, disabledConsoleClear?: boolean) { + const host = createSolutionInWatchMode(allFiles, defaultBuildOptions, disabledConsoleClear); + const outputFileStamps = getOutputFileStamps(host); - host.writeFile(logic[1].path, `${logic[1].content} + host.writeFile(logic[1].path, `${logic[1].content} let y: string = 10;`); - host.checkTimeoutQueueLengthAndRun(1); // Builds logic - const changedLogic = getOutputFileStamps(host); - verifyChangedFiles(changedLogic, outputFileStamps, emptyArray); - host.checkTimeoutQueueLength(0); - checkOutputErrorsIncremental(host, [ - `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` - ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host); + verifyChangedFiles(changedLogic, outputFileStamps, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); - host.writeFile(core[1].path, `${core[1].content} + host.writeFile(core[1].path, `${core[1].content} let x: string = 10;`); - host.checkTimeoutQueueLengthAndRun(1); // Builds core - const changedCore = getOutputFileStamps(host); - verifyChangedFiles(changedCore, changedLogic, emptyArray); - host.checkTimeoutQueueLength(0); - checkOutputErrorsIncremental(host, [ - `sample1/core/index.ts(5,5): error TS2322: Type '10' is not assignable to type 'string'.\n`, - `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` - ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host); + verifyChangedFiles(changedCore, changedLogic, emptyArray); + host.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, [ + `sample1/core/index.ts(5,5): error TS2322: Type '10' is not assignable to type 'string'.\n`, + `sample1/logic/index.ts(8,5): error TS2322: Type '10' is not assignable to type 'string'.\n` + ], disabledConsoleClear); + } + + it("when preserveWatchOutput is not used", () => { + verifyIncrementalErrors(); + }); + + it("when preserveWatchOutput is passed on command line", () => { + verifyIncrementalErrors({ preserveWatchOutput: true, watch: true }, /*disabledConsoleClear*/ true); + }); }); // TODO: write tests reporting errors but that will have more involved work since file }); From e2edb696385c2992b8174dc27312569d4375105f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 1 Aug 2018 15:30:14 -0700 Subject: [PATCH 122/146] Instead of watching individual script infos, watch the node modules folder for script infos in node modules --- src/compiler/sys.ts | 16 ++- src/server/editorServices.ts | 109 ++++++++++++++++-- src/server/scriptInfo.ts | 3 + .../unittests/tsserverProjectSystem.ts | 23 +++- .../reference/api/tsserverlibrary.d.ts | 5 + 5 files changed, 134 insertions(+), 22 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index eaa910a0b5c..713085f1922 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -317,18 +317,22 @@ namespace ts { const newTime = modifiedTime.getTime(); if (oldTime !== newTime) { watchedFile.mtime = modifiedTime; - const eventKind = oldTime === 0 - ? FileWatcherEventKind.Created - : newTime === 0 - ? FileWatcherEventKind.Deleted - : FileWatcherEventKind.Changed; - watchedFile.callback(watchedFile.fileName, eventKind); + watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime)); return true; } return false; } + /*@internal*/ + export function getFileWatcherEventKind(oldTime: number, newTime: number) { + return oldTime === 0 + ? FileWatcherEventKind.Created + : newTime === 0 + ? FileWatcherEventKind.Deleted + : FileWatcherEventKind.Changed; + } + /*@internal*/ export interface RecursiveDirectoryWatcherHost { watchDirectory: HostWatchDirectory; diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index b1f88dff3b7..f4d8265bc19 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -291,7 +291,8 @@ namespace ts.server { ClosedScriptInfo = "Closed Script info", ConfigFileForInferredRoot = "Config file for the inferred project root", FailedLookupLocation = "Directory of Failed lookup locations in module resolution", - TypeRoots = "Type root directory" + TypeRoots = "Type root directory", + NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them", } const enum ConfigFileWatcherStatus { @@ -353,10 +354,18 @@ namespace ts.server { return !!(infoOrFileName as ScriptInfo).containingProjects; } + interface ScriptInfoInNodeModulesWatcher extends FileWatcher { + refCount: number; + } + function getDetailWatchInfo(watchType: WatchType, project: Project | undefined) { return `Project: ${project ? project.getProjectName() : ""} WatchType: ${watchType}`; } + function isScriptInfoWatchedFromNodeModules(info: ScriptInfo) { + return !info.isScriptOpen() && info.mTime !== undefined; + } + /*@internal*/ export function updateProjectIfDirty(project: Project) { return project.dirty && project.updateGraph(); @@ -380,6 +389,7 @@ namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo = createMap(); + private readonly scriptInfoInNodeModulesWatchers = createMap (); /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -1923,18 +1933,97 @@ namespace ts.server { if (!info.isDynamicOrHasMixedContent() && (!this.globalCacheLocationDirectoryPath || !startsWith(info.path, this.globalCacheLocationDirectoryPath))) { - const { fileName } = info; - info.fileWatcher = this.watchFactory.watchFilePath( - this.host, - fileName, - (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), - PollingInterval.Medium, - info.path, - WatchType.ClosedScriptInfo - ); + const indexOfNodeModules = info.path.indexOf("/node_modules/"); + if (!this.host.getModifiedTime || indexOfNodeModules === -1) { + info.fileWatcher = this.watchFactory.watchFilePath( + this.host, + info.fileName, + (fileName, eventKind, path) => this.onSourceFileChanged(fileName, eventKind, path), + PollingInterval.Medium, + info.path, + WatchType.ClosedScriptInfo + ); + } + else { + info.mTime = this.getModifiedTime(info); + info.fileWatcher = this.watchClosedScriptInfoInNodeModules(info.path.substr(0, indexOfNodeModules) as Path); + } } } + private watchClosedScriptInfoInNodeModules(dir: Path): ScriptInfoInNodeModulesWatcher { + // Watch only directory + const existing = this.scriptInfoInNodeModulesWatchers.get(dir); + if (existing) { + existing.refCount++; + return existing; + } + + const watchDir = dir + "/node_modules" as Path; + const watcher = this.watchFactory.watchDirectory( + this.host, + watchDir, + (fileOrDirectory) => { + const fileOrDirectoryPath = this.toPath(fileOrDirectory); + // Has extension + Debug.assert(result.refCount > 0); + if (watchDir === fileOrDirectoryPath) { + this.refreshScriptInfosInDirectory(watchDir); + } + else { + const info = this.getScriptInfoForPath(fileOrDirectoryPath); + if (info) { + if (isScriptInfoWatchedFromNodeModules(info)) { + this.refreshScriptInfo(info); + } + } + // Folder + else if (!hasExtension(fileOrDirectoryPath)) { + this.refreshScriptInfosInDirectory(fileOrDirectoryPath); + } + } + }, + WatchDirectoryFlags.Recursive, + WatchType.NodeModulesForClosedScriptInfo + ); + const result: ScriptInfoInNodeModulesWatcher = { + close: () => { + if (result.refCount === 1) { + watcher.close(); + this.scriptInfoInNodeModulesWatchers.delete(dir); + } + else { + result.refCount--; + } + }, + refCount: 1 + }; + this.scriptInfoInNodeModulesWatchers.set(dir, result); + return result; + } + + private getModifiedTime(info: ScriptInfo) { + return (this.host.getModifiedTime!(info.path) || missingFileModifiedTime).getTime(); + } + + private refreshScriptInfo(info: ScriptInfo) { + const mTime = this.getModifiedTime(info); + if (mTime !== info.mTime) { + const eventKind = getFileWatcherEventKind(info.mTime!, mTime); + info.mTime = mTime; + this.onSourceFileChanged(info.fileName, eventKind, info.path); + } + } + + private refreshScriptInfosInDirectory(dir: Path) { + dir = dir + directorySeparator as Path; + this.filenameToScriptInfo.forEach(info => { + if (isScriptInfoWatchedFromNodeModules(info) && startsWith(info.path, dir)) { + this.refreshScriptInfo(info); + } + }); + } + private stopWatchingScriptInfo(info: ScriptInfo) { if (info.fileWatcher) { info.fileWatcher.close(); diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 5c4eaa9a374..e52c597ffa1 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -250,6 +250,9 @@ namespace ts.server { /*@internal*/ cacheSourceFile: DocumentRegistrySourceFileCache; + /*@internal*/ + mTime?: number; + constructor( private readonly host: ServerHost, readonly fileName: NormalizedPath, diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 988ccbc3bfe..ed130f6772b 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -3136,7 +3136,7 @@ namespace ts.projectSystem { const project = projectService.configuredProjects.get(configFile.path)!; assert.isDefined(project); checkProjectActualFiles(project, [file1.path, libFile.path, module1.path, module2.path, configFile.path]); - checkWatchedFiles(host, [libFile.path, module1.path, module2.path, configFile.path]); + checkWatchedFiles(host, [libFile.path, configFile.path]); checkWatchedDirectories(host, [], /*recursive*/ false); const watchedRecursiveDirectories = getTypeRootsFromLocation(root + "/a/b/src"); watchedRecursiveDirectories.push(`${root}/a/b/src/node_modules`, `${root}/a/b/node_modules`); @@ -7435,7 +7435,7 @@ namespace ts.projectSystem { const projectFilePaths = map(projectFiles, f => f.path); checkProjectActualFiles(project, projectFilePaths); - const filesWatched = filter(projectFilePaths, p => p !== app.path); + const filesWatched = filter(projectFilePaths, p => p !== app.path && p.indexOf("/a/b/node_modules") === -1); checkWatchedFiles(host, filesWatched); checkWatchedDirectories(host, typeRootDirectories.concat(recursiveWatchedDirectories), /*recursive*/ true); checkWatchedDirectories(host, [], /*recursive*/ false); @@ -8658,10 +8658,21 @@ new C();` } function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray) { - checkWatchedFiles(host, mapDefined(files, f => f === openFile ? undefined : f.path)); + const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); + checkWatchedFiles(host, mapDefined(files, f => { + if (f === openFile) { + return undefined; + } + const indexOfNodeModules = f.path.indexOf("/node_modules/"); + if (indexOfNodeModules === -1) { + return f.path; + } + expectedRecursiveDirectories.set(f.path.substr(0, indexOfNodeModules + "/node_modules".length), true); + return undefined; + })); checkWatchedDirectories(host, [], /*recursive*/ false); - checkWatchedDirectories(host, [projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)], /*recursive*/ true); - } + checkWatchedDirectories(host, arrayFrom(expectedRecursiveDirectories.keys()), /*recursive*/ true); + } describe("from files in same folder", () => { function getFiles(fileContent: string) { @@ -8862,7 +8873,7 @@ new C();` verifyTrace(resolutionTrace, expectedTrace); const currentDirectory = getDirectoryPath(file1.path); - const watchedFiles = mapDefined(files, f => f === file1 ? undefined : f.path); + const watchedFiles = mapDefined(files, f => f === file1 || f.path.indexOf("/node_modules/") !== -1 ? undefined : f.path); forEachAncestorDirectory(currentDirectory, d => { watchedFiles.push(combinePaths(d, "tsconfig.json"), combinePaths(d, "jsconfig.json")); }); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9465a512a1f..4ca8445f4af 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8382,6 +8382,7 @@ declare namespace ts.server { * Container of all known scripts */ private readonly filenameToScriptInfo; + private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that * it does not reset when creating script info again @@ -8552,6 +8553,10 @@ declare namespace ts.server { private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo | undefined; private watchClosedScriptInfo; + private watchClosedScriptInfoInNodeModules; + private getModifiedTime; + private refreshScriptInfo; + private refreshScriptInfosInDirectory; private stopWatchingScriptInfo; private getOrCreateScriptInfoNotOpenedByClientForNormalizedPath; private getOrCreateScriptInfoOpenedByClientForNormalizedPath; From 2b0e9e686b83ba18aaf9de9aa19d73f4d4182da0 Mon Sep 17 00:00:00 2001 From: Dan Rollo Date: Thu, 13 Sep 2018 17:23:56 -0400 Subject: [PATCH 123/146] typo: missing word: "to" (#27079) Change: ...a resolve callback used resolve the promise... to: ...a resolve callback used to resolve the promise... This PR suggested from: https://github.com/Microsoft/TypeScript/pull/27075 --- src/lib/es2015.promise.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/es2015.promise.d.ts b/src/lib/es2015.promise.d.ts index 14602c0b5ed..2a98f215193 100644 --- a/src/lib/es2015.promise.d.ts +++ b/src/lib/es2015.promise.d.ts @@ -7,7 +7,7 @@ interface PromiseConstructor { /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: - * a resolve callback used resolve the promise with a value or the result of another promise, + * a resolve callback used to resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new (executor: (resolve: (value?: T | PromiseLike) => void, reject: (reason?: any) => void) => void): Promise; @@ -193,4 +193,4 @@ interface PromiseConstructor { resolve(): Promise; } -declare var Promise: PromiseConstructor; \ No newline at end of file +declare var Promise: PromiseConstructor; From 64d0e0d448453ab8a84d6e551359d934aa244a5e Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 13 Sep 2018 15:05:57 -0700 Subject: [PATCH 124/146] Shorten more internal names to JS or TS (#27080) --- src/compiler/checker.ts | 58 ++++++++++---------- src/compiler/emitter.ts | 2 +- src/compiler/moduleNameResolver.ts | 8 +-- src/compiler/moduleSpecifiers.ts | 8 +-- src/compiler/program.ts | 8 +-- src/compiler/resolutionCache.ts | 2 +- src/compiler/transformers/declarations.ts | 2 +- src/compiler/tsbuild.ts | 4 +- src/compiler/utilities.ts | 42 +++++++------- src/harness/fourslash.ts | 2 +- src/harness/harnessLanguageService.ts | 2 +- src/harness/vpath.ts | 4 +- src/jsTyping/jsTyping.ts | 4 +- src/server/editorServices.ts | 10 ++-- src/server/scriptInfo.ts | 2 +- src/services/jsDoc.ts | 2 +- src/testRunner/unittests/moduleResolution.ts | 6 +- src/tsserver/server.ts | 2 +- 18 files changed, 84 insertions(+), 84 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6f541461b09..f4314726942 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2219,7 +2219,7 @@ namespace ts { const sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { - if (resolvedModule.isExternalLibraryImport && !extensionIsTypeScript(resolvedModule.extension)) { + if (resolvedModule.isExternalLibraryImport && !extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -2240,7 +2240,7 @@ namespace ts { } // May be an untyped module. If so, ignore resolutionDiagnostic. - if (resolvedModule && !resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { + if (resolvedModule && !resolutionExtensionIsTSOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) { if (isForAugmentation) { const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); @@ -2273,7 +2273,7 @@ namespace ts { error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName); } else { - const tsExtension = tryExtractTypeScriptExtension(moduleReference); + const tsExtension = tryExtractTSExtension(moduleReference); if (tsExtension) { const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead; error(errorNode, diag, tsExtension, removeExtension(moduleReference, tsExtension)); @@ -3351,7 +3351,7 @@ namespace ts { if (symbol) { const isConstructorObject = getObjectFlags(type) & ObjectFlags.Anonymous && type.symbol && type.symbol.flags & SymbolFlags.Class; id = (isConstructorObject ? "+" : "") + getSymbolId(symbol); - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { // Instance and static types share the same symbol; only add 'typeof' for the static side. const isInstanceType = type === getInferredClassType(symbol) ? SymbolFlags.Type : SymbolFlags.Value; return symbolToTypeNode(symbol, context, isInstanceType); @@ -5563,7 +5563,7 @@ namespace ts { const constraint = getBaseConstraintOfType(type); return !!constraint && isValidBaseType(constraint) && isMixinConstructorType(constraint); } - return isJavascriptConstructorType(type); + return isJSConstructorType(type); } function getBaseTypeNodeOfClass(type: InterfaceType): ExpressionWithTypeArguments | undefined { @@ -5573,7 +5573,7 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { + if (isJSConstructorType(type) && !typeArgCount) { return getSignaturesOfType(type, SignatureKind.Call); } return filter(getSignaturesOfType(type, SignatureKind.Construct), @@ -5668,8 +5668,8 @@ namespace ts { else if (baseConstructorType.flags & TypeFlags.Any) { baseType = baseConstructorType; } - else if (isJavascriptConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { - baseType = getJavascriptClassType(baseConstructorType.symbol) || anyType; + else if (isJSConstructorType(baseConstructorType) && !baseTypeNode.typeArguments) { + baseType = getJSClassType(baseConstructorType.symbol) || anyType; } else { // The class derives from a "class-like" constructor function, check that we have at least one construct signature @@ -10176,7 +10176,7 @@ namespace ts { } } let outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true); - if (isJavascriptConstructor(declaration)) { + if (isJSConstructor(declaration)) { const templateTagParameters = getTypeParametersFromDeclaration(declaration as DeclarationWithTypeParameters); outerTypeParameters = addRange(outerTypeParameters, templateTagParameters); } @@ -10862,13 +10862,13 @@ namespace ts { } if (!ignoreReturnTypes) { - const targetReturnType = (target.declaration && isJavascriptConstructor(target.declaration)) ? - getJavascriptClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); + const targetReturnType = (target.declaration && isJSConstructor(target.declaration)) ? + getJSClassType(target.declaration.symbol)! : getReturnTypeOfSignature(target); if (targetReturnType === voidType) { return result; } - const sourceReturnType = (source.declaration && isJavascriptConstructor(source.declaration)) ? - getJavascriptClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); + const sourceReturnType = (source.declaration && isJSConstructor(source.declaration)) ? + getJSClassType(source.declaration.symbol)! : getReturnTypeOfSignature(source); // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions const targetTypePredicate = getTypePredicateOfSignature(target); @@ -12132,8 +12132,8 @@ namespace ts { return Ternary.True; } - const sourceIsJSConstructor = source.symbol && isJavascriptConstructor(source.symbol.valueDeclaration); - const targetIsJSConstructor = target.symbol && isJavascriptConstructor(target.symbol.valueDeclaration); + const sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration); + const targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration); const sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === SignatureKind.Construct) ? SignatureKind.Call : kind); @@ -15821,7 +15821,7 @@ namespace ts { if (isInJS && className) { const classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { - const classType = getJavascriptClassType(classSymbol); + const classType = getJSClassType(classSymbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -15834,7 +15834,7 @@ namespace ts { else if (isInJS && (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && getJSDocClassTag(container)) { - const classType = getJavascriptClassType(container.symbol); + const classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -19851,7 +19851,7 @@ namespace ts { if (callSignatures.length) { const signature = resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); if (!noImplicitAny) { - if (signature.declaration && !isJavascriptConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { + if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } if (getThisTypeOfSignature(signature) === voidType) { @@ -20134,7 +20134,7 @@ namespace ts { * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node: Declaration | undefined): boolean { + function isJSConstructor(node: Declaration | undefined): boolean { if (node && isInJSFile(node)) { // If the node has a @class tag, treat it like a constructor. if (getJSDocClassTag(node)) return true; @@ -20150,22 +20150,22 @@ namespace ts { return false; } - function isJavascriptConstructorType(type: Type) { + function isJSConstructorType(type: Type) { if (type.flags & TypeFlags.Object) { const resolved = resolveStructuredTypeMembers(type); - return resolved.callSignatures.length === 1 && isJavascriptConstructor(resolved.callSignatures[0].declaration); + return resolved.callSignatures.length === 1 && isJSConstructor(resolved.callSignatures[0].declaration); } return false; } - function getJavascriptClassType(symbol: Symbol): Type | undefined { + function getJSClassType(symbol: Symbol): Type | undefined { let inferred: Type | undefined; - if (isJavascriptConstructor(symbol.valueDeclaration)) { + if (isJSConstructor(symbol.valueDeclaration)) { inferred = getInferredClassType(symbol); } const assigned = getAssignedClassType(symbol); const valueType = getTypeOfSymbol(symbol); - if (valueType.symbol && !isInferredClassType(valueType) && isJavascriptConstructor(valueType.symbol.valueDeclaration)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -20180,14 +20180,14 @@ namespace ts { isBinaryExpression(decl.parent) && getSymbolOfNode(decl.parent.left) || isVariableDeclaration(decl.parent) && getSymbolOfNode(decl.parent)); if (assignmentSymbol) { - const prototype = forEach(assignmentSymbol.declarations, getAssignedJavascriptPrototype); + const prototype = forEach(assignmentSymbol.declarations, getAssignedJSPrototype); if (prototype) { return checkExpression(prototype); } } } - function getAssignedJavascriptPrototype(node: Node) { + function getAssignedJSPrototype(node: Node) { if (!node.parent) { return false; } @@ -20248,7 +20248,7 @@ namespace ts { if (!funcSymbol && node.expression.kind === SyntaxKind.Identifier) { funcSymbol = getResolvedSymbol(node.expression as Identifier); } - const type = funcSymbol && getJavascriptClassType(funcSymbol); + const type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -20897,7 +20897,7 @@ namespace ts { return undefined; } if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && - !(isJavascriptConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { + !(isJSConstructor(func) && aggregatedTypes.some(t => t.symbol === func.symbol))) { // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined pushIfUnique(aggregatedTypes, undefinedType); } @@ -25811,7 +25811,7 @@ namespace ts { // that the base type is a class or interface type (and not, for example, an anonymous object type). // (Javascript constructor functions have this property trivially true since their return type is ignored.) const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); - if (forEach(constructors, sig => !isJavascriptConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { + if (forEach(constructors, sig => !isJSConstructor(sig.declaration) && getReturnTypeOfSignature(sig) !== baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index bce36bca73c..62dfb46f7c5 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -192,7 +192,7 @@ namespace ts { } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; // Setup and perform the transformation to retrieve declarations from the input files - const nonJsFiles = filter(sourceFiles, isSourceFileNotJavascript); + const nonJsFiles = filter(sourceFiles, isSourceFileNotJS); const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles, !isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : nonJsFiles; if (emitOnlyDtsFiles && !getEmitDeclarations(compilerOptions)) { // Checker wont collect the linked aliases since thats only done when declaration is enabled. diff --git a/src/compiler/moduleNameResolver.ts b/src/compiler/moduleNameResolver.ts index aedd1d4c3dc..335e47286b7 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -74,7 +74,7 @@ namespace ts { if (!resolved) { return undefined; } - Debug.assert(extensionIsTypeScript(resolved.extension)); + Debug.assert(extensionIsTS(resolved.extension)); return { fileName: resolved.path, packageId: resolved.packageId }; } @@ -778,7 +778,7 @@ namespace ts { * Throws an error if the module can't be resolved. */ /* @internal */ - export function resolveJavascriptModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { + export function resolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string { const { resolvedModule, failedLookupLocations } = nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, /*jsOnly*/ true); if (!resolvedModule) { @@ -958,7 +958,7 @@ namespace ts { // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (hasJavascriptFileExtension(candidate)) { + if (hasJSFileExtension(candidate)) { const extensionless = removeFileExtension(candidate); if (state.traceEnabled) { const extension = candidate.substring(extensionless.length); @@ -1052,7 +1052,7 @@ namespace ts { const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { const potentialSubModule = jsPath.substring(packageDirectory.length + 1); - subModuleName = (forEach(supportedJavascriptExtensions, extension => + subModuleName = (forEach(supportedJSExtensions, extension => tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts; } else { diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index 6033d95b2a5..e50aaf99453 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -30,7 +30,7 @@ namespace ts.moduleSpecifiers { function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences { return { relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative, - ending: hasJavascriptOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension + ending: hasJSOrJsonFileExtension(oldImportSpecifier) ? Ending.JsExtension : getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal, }; } @@ -148,7 +148,7 @@ namespace ts.moduleSpecifiers { } function usesJsExtensionOnImports({ imports }: SourceFile): boolean { - return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJavascriptOrJsonFileExtension(text) : undefined) || false; + return firstDefined(imports, ({ text }) => pathIsRelative(text) ? hasJSOrJsonFileExtension(text) : undefined) || false; } function stringsEqual(a: string, b: string, getCanonicalFileName: GetCanonicalFileName): boolean { @@ -415,13 +415,13 @@ namespace ts.moduleSpecifiers { case Ending.Index: return noExtension; case Ending.JsExtension: - return noExtension + getJavascriptExtensionForFile(fileName, options); + return noExtension + getJSExtensionForFile(fileName, options); default: return Debug.assertNever(ending); } } - function getJavascriptExtensionForFile(fileName: string, options: CompilerOptions): Extension { + function getJSExtensionForFile(fileName: string, options: CompilerOptions): Extension { const ext = extensionFromPath(fileName); switch (ext) { case Extension.Ts: diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 61bf38db805..b2726696e3e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1440,7 +1440,7 @@ namespace ts { // constructs from within a JavaScript file as syntactic errors. if (isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavascriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -1538,7 +1538,7 @@ namespace ts { return true; } - function getJavascriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { + function getJSSyntacticDiagnosticsForFile(sourceFile: SourceFile): DiagnosticWithLocation[] { return runWithCancellationToken(() => { const diagnostics: DiagnosticWithLocation[] = []; let parent: Node = sourceFile; @@ -2273,7 +2273,7 @@ namespace ts { } const isFromNodeModulesSearch = resolution.isExternalLibraryImport; - const isJsFile = !resolutionExtensionIsTypeScriptOrJson(resolution.extension); + const isJsFile = !resolutionExtensionIsTSOrJson(resolution.extension); const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile; const resolvedFileName = resolution.resolvedFileName; @@ -2794,7 +2794,7 @@ namespace ts { return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames()); } - if (fileExtensionIsOneOf(filePath, supportedJavascriptExtensions) || fileExtensionIs(filePath, Extension.Dts)) { + if (fileExtensionIsOneOf(filePath, supportedJSExtensions) || fileExtensionIs(filePath, Extension.Dts)) { // Otherwise just check if sourceFile with the name exists const filePathWithoutExtension = removeFileExtension(filePath); return !!getSourceFileByPath((filePathWithoutExtension + Extension.Ts) as Path) || diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 2d7bcb34c2d..33e6dcd1221 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -226,7 +226,7 @@ namespace ts { // otherwise try to load typings from @types const globalCache = resolutionHost.getGlobalCache(); - if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + if (globalCache !== undefined && !isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && extensionIsTS(primaryResult.resolvedModule.extension))) { // create different collection of failed lookup locations for second pass // if it will fail and we've already found something during the first pass - we don't want to pollute its results const { resolvedModule, failedLookupLocations } = loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 14e7900b0da..5312efb5aac 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -5,7 +5,7 @@ namespace ts { return []; // No declaration diagnostics for js for now } const compilerOptions = host.getCompilerOptions(); - const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavascript), [transformDeclarations], /*allowDtsFiles*/ false); + const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJS), [transformDeclarations], /*allowDtsFiles*/ false); return result.diagnostics; } diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index 3692e9ca057..3a4b2b2429d 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -302,7 +302,7 @@ namespace ts { return changeExtension(outputPath, Extension.Dts); } - function getOutputJavascriptFileName(inputFileName: string, configFile: ParsedCommandLine) { + function getOutputJSFileName(inputFileName: string, configFile: ParsedCommandLine) { const relativePath = getRelativePathFromDirectory(rootDirOfOptions(configFile.options, configFile.options.configFilePath!), inputFileName, /*ignoreCase*/ true); const outputPath = resolvePath(configFile.options.outDir || getDirectoryPath(configFile.options.configFilePath!), relativePath); const newExtension = fileExtensionIs(inputFileName, Extension.Json) ? Extension.Json : @@ -317,7 +317,7 @@ namespace ts { } const outputs: string[] = []; - const js = getOutputJavascriptFileName(inputFileName, configFile); + const js = getOutputJSFileName(inputFileName, configFile); outputs.push(js); if (configFile.options.sourceMap) { outputs.push(`${js}.map`); diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1efbd278aed..82d1e57ad41 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1682,7 +1682,7 @@ namespace ts { return isInJSFile(file); } - export function isSourceFileNotJavascript(file: SourceFile): boolean { + export function isSourceFileNotJS(file: SourceFile): boolean { return !isInJSFile(file); } @@ -3818,8 +3818,8 @@ namespace ts { } /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ - export function tryExtractTypeScriptExtension(fileName: string): string | undefined { - return find(supportedTypescriptExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); + export function tryExtractTSExtension(fileName: string): string | undefined { + return find(supportedTSExtensionsForExtractExtension, extension => fileExtensionIs(fileName, extension)); } /** * Replace each instance of non-ascii characters by one, two, three, or four escape sequences @@ -8010,42 +8010,42 @@ namespace ts { /** * List of supported extensions in order of file resolution precedence. */ - export const supportedTypescriptExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; + export const supportedTSExtensions: ReadonlyArray = [Extension.Ts, Extension.Tsx, Extension.Dts]; /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */ - export const supportedTypescriptExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; - export const supportedJavascriptExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; - export const supportedJavascriptAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; - const allSupportedExtensions: ReadonlyArray = [...supportedTypescriptExtensions, ...supportedJavascriptExtensions]; + export const supportedTSExtensionsForExtractExtension: ReadonlyArray = [Extension.Dts, Extension.Ts, Extension.Tsx]; + export const supportedJSExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx]; + export const supportedJSAndJsonExtensions: ReadonlyArray = [Extension.Js, Extension.Jsx, Extension.Json]; + const allSupportedExtensions: ReadonlyArray = [...supportedTSExtensions, ...supportedJSExtensions]; export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: ReadonlyArray): ReadonlyArray { const needJsExtensions = options && options.allowJs; if (!extraFileExtensions || extraFileExtensions.length === 0) { - return needJsExtensions ? allSupportedExtensions : supportedTypescriptExtensions; + return needJsExtensions ? allSupportedExtensions : supportedTSExtensions; } const extensions = [ - ...needJsExtensions ? allSupportedExtensions : supportedTypescriptExtensions, - ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJavascriptLike(x.scriptKind) ? x.extension : undefined) + ...needJsExtensions ? allSupportedExtensions : supportedTSExtensions, + ...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined) ]; return deduplicate(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive); } - function isJavascriptLike(scriptKind: ScriptKind | undefined): boolean { + function isJSLike(scriptKind: ScriptKind | undefined): boolean { return scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSX; } - export function hasJavascriptFileExtension(fileName: string): boolean { - return some(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasJSFileExtension(fileName: string): boolean { + return some(supportedJSExtensions, extension => fileExtensionIs(fileName, extension)); } - export function hasJavascriptOrJsonFileExtension(fileName: string): boolean { - return supportedJavascriptAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); + export function hasJSOrJsonFileExtension(fileName: string): boolean { + return supportedJSAndJsonExtensions.some(ext => fileExtensionIs(fileName, ext)); } - export function hasTypescriptFileExtension(fileName: string): boolean { - return some(supportedTypescriptExtensions, extension => fileExtensionIs(fileName, extension)); + export function hasTSFileExtension(fileName: string): boolean { + return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension)); } export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: ReadonlyArray) { @@ -8181,12 +8181,12 @@ namespace ts { } /** True if an extension is one of the supported TypeScript extensions. */ - export function extensionIsTypeScript(ext: Extension): boolean { + export function extensionIsTS(ext: Extension): boolean { return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts; } - export function resolutionExtensionIsTypeScriptOrJson(ext: Extension) { - return extensionIsTypeScript(ext) || ext === Extension.Json; + export function resolutionExtensionIsTSOrJson(ext: Extension) { + return extensionIsTS(ext) || ext === Extension.Json; } /** diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index a1f3517b6e6..fb1ed9fcb1b 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -593,7 +593,7 @@ namespace FourSlash { public verifyNoErrors() { ts.forEachKey(this.inputFiles, fileName => { if (!ts.isAnySupportedFileExtension(fileName) - || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTypeScript(ts.extensionFromPath(fileName))) return; + || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTS(ts.extensionFromPath(fileName))) return; const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); if (errors.length) { this.printErrorLog(/*expectErrors*/ false, errors); diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index abb03babc8d..e90f29446c3 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -268,7 +268,7 @@ namespace Harness.LanguageService { getHost(): LanguageServiceAdapterHost { return this.host; } getLanguageService(): ts.LanguageService { return ts.createLanguageService(this.host); } getClassifier(): ts.Classifier { return ts.createClassifier(); } - getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJavascriptFileExtension(fileName)); } + getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { return ts.preProcessFile(fileContents, /* readImportFiles */ true, ts.hasJSFileExtension(fileName)); } } /// Shim adapter diff --git a/src/harness/vpath.ts b/src/harness/vpath.ts index f21ee7fb6bb..68ba0465e50 100644 --- a/src/harness/vpath.ts +++ b/src/harness/vpath.ts @@ -21,8 +21,8 @@ namespace vpath { export import relative = ts.getRelativePathFromDirectory; export import beneath = ts.containsPath; export import changeExtension = ts.changeAnyExtension; - export import isTypeScript = ts.hasTypescriptFileExtension; - export import isJavaScript = ts.hasJavascriptFileExtension; + export import isTypeScript = ts.hasTSFileExtension; + export import isJavaScript = ts.hasJSFileExtension; const invalidRootComponentRegExp = /^(?!(\/|\/\/\w+\/|[a-zA-Z]:\/?|)$)/; const invalidNavigableComponentRegExp = /[:*?"<>|]/; diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index 3b1868aea84..ad21068d578 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -122,7 +122,7 @@ namespace ts.JsTyping { // Only infer typings for .js and .jsx files fileNames = mapDefined(fileNames, fileName => { const path = normalizePath(fileName); - if (hasJavascriptFileExtension(path)) { + if (hasJSFileExtension(path)) { return path; } }); @@ -218,7 +218,7 @@ namespace ts.JsTyping { */ function getTypingNamesFromSourceFileNames(fileNames: string[]) { const fromFileNames = mapDefined(fileNames, j => { - if (!hasJavascriptFileExtension(j)) return undefined; + if (!hasJSFileExtension(j)) return undefined; const inferredTypingName = removeFileExtension(getBaseFileName(j.toLowerCase())); const cleanedTypingName = removeMinAndVersionNumbers(inferredTypingName); diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index b1f88dff3b7..b5ea4e52c3f 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1447,14 +1447,14 @@ namespace ts.server { for (const f of fileNames) { const fileName = propertyReader.getFileName(f); - if (hasTypescriptFileExtension(fileName)) { + if (hasTSFileExtension(fileName)) { continue; } totalNonTsFileSize += this.host.getFileSize(fileName); if (totalNonTsFileSize > maxProgramSizeForNonTsFiles || totalNonTsFileSize > availableSpace) { - this.logger.info(getExceedLimitMessage({ propertyReader, hasTypescriptFileExtension, host: this.host }, totalNonTsFileSize)); + this.logger.info(getExceedLimitMessage({ propertyReader, hasTSFileExtension, host: this.host }, totalNonTsFileSize)); // Keep the size as zero since it's disabled return fileName; } @@ -1464,14 +1464,14 @@ namespace ts.server { return; - function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTypescriptFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { + function getExceedLimitMessage(context: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }, totalNonTsFileSize: number) { const files = getTop5LargestFiles(context); return `Non TS file size exceeded limit (${totalNonTsFileSize}). Largest files: ${files.map(file => `${file.name}:${file.size}`).join(", ")}`; } - function getTop5LargestFiles({ propertyReader, hasTypescriptFileExtension, host }: { propertyReader: FilePropertyReader, hasTypescriptFileExtension: (filename: string) => boolean, host: ServerHost }) { + function getTop5LargestFiles({ propertyReader, hasTSFileExtension, host }: { propertyReader: FilePropertyReader, hasTSFileExtension: (filename: string) => boolean, host: ServerHost }) { return fileNames.map(f => propertyReader.getFileName(f)) - .filter(name => hasTypescriptFileExtension(name)) + .filter(name => hasTSFileExtension(name)) .map(name => ({ name, size: host.getFileSize!(name) })) // TODO: GH#18217 .sort((a, b) => b.size - a.size) .slice(0, 5); diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 5c4eaa9a374..48c54a6fba8 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -167,7 +167,7 @@ namespace ts.server { const fileName = tempFileName || this.fileName; const getText = () => text === undefined ? (text = this.host.readFile(fileName) || "") : text; // Only non typescript files have size limitation - if (!hasTypescriptFileExtension(this.fileName)) { + if (!hasTSFileExtension(this.fileName)) { const fileSize = this.host.getFileSize ? this.host.getFileSize(fileName) : getText().length; if (fileSize > maxFileSize) { Debug.assert(!!this.info.containingProjects.length); diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index 442df61e073..8016b0e9ff6 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -312,7 +312,7 @@ namespace ts.JsDoc { const preamble = "/**" + newLine + indentationStr + " * "; const result = preamble + newLine + - parameterDocComments(parameters, hasJavascriptFileExtension(sourceFile.fileName), indentationStr, newLine) + + parameterDocComments(parameters, hasJSFileExtension(sourceFile.fileName), indentationStr, newLine) + indentationStr + " */" + (tokenStart === position ? newLine + indentationStr : ""); diff --git a/src/testRunner/unittests/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index e12e60e49ea..a3ebf4f84a7 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -83,7 +83,7 @@ namespace ts { describe("Node module resolution - relative paths", () => { function testLoadAsFile(containingFileName: string, moduleFileNameNoExt: string, moduleName: string): void { - for (const ext of supportedTypescriptExtensions) { + for (const ext of supportedTSExtensions) { test(ext, /*hasDirectoryExists*/ false); test(ext, /*hasDirectoryExists*/ true); } @@ -96,7 +96,7 @@ namespace ts { const failedLookupLocations: string[] = []; const dir = getDirectoryPath(containingFileName); - for (const e of supportedTypescriptExtensions) { + for (const e of supportedTSExtensions) { if (e === ext) { break; } @@ -137,7 +137,7 @@ namespace ts { const resolution = nodeModuleNameResolver(moduleName, containingFile.name, {}, createModuleResolutionHost(hasDirectoryExists, containingFile, packageJson, moduleFile)); checkResolvedModule(resolution.resolvedModule, createResolvedModule(moduleFile.name)); // expect three failed lookup location - attempt to load module as file with all supported extensions - assert.equal(resolution.failedLookupLocations.length, supportedTypescriptExtensions.length); + assert.equal(resolution.failedLookupLocations.length, supportedTSExtensions.length); } } diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 9c05bf0cf16..951b158c152 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -891,7 +891,7 @@ namespace ts.server { sys.require = (initialDir: string, moduleName: string): RequireResult => { try { - return { module: require(resolveJavascriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error }; From ebfcc1b52db6eacd814e20efd33c2984b3b43538 Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 13 Sep 2018 15:24:49 -0700 Subject: [PATCH 125/146] Fix bug: Ignore @enum tag in TS (#27076) --- src/compiler/binder.ts | 2 +- tests/baselines/reference/jsdocInTypeScript.errors.txt | 4 ++++ tests/baselines/reference/jsdocInTypeScript.js | 7 +++++++ tests/baselines/reference/jsdocInTypeScript.symbols | 7 +++++++ tests/baselines/reference/jsdocInTypeScript.types | 10 ++++++++++ tests/cases/compiler/jsdocInTypeScript.ts | 4 ++++ 6 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 3205b2c5a55..81d4857ad07 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2666,7 +2666,7 @@ namespace ts { } if (!isBindingPattern(node.name)) { - const isEnum = !!getJSDocEnumTag(node); + const isEnum = isInJSFile(node) && !!getJSDocEnumTag(node); const enumFlags = (isEnum ? SymbolFlags.RegularEnum : SymbolFlags.None); const enumExcludes = (isEnum ? SymbolFlags.RegularEnumExcludes : SymbolFlags.None); if (isBlockOrCatchScoped(node)) { diff --git a/tests/baselines/reference/jsdocInTypeScript.errors.txt b/tests/baselines/reference/jsdocInTypeScript.errors.txt index 7903ef8057f..c8972bb0f0a 100644 --- a/tests/baselines/reference/jsdocInTypeScript.errors.txt +++ b/tests/baselines/reference/jsdocInTypeScript.errors.txt @@ -67,4 +67,8 @@ tests/cases/compiler/jsdocInTypeScript.ts(42,12): error TS2503: Cannot find name * @type {{foo: (function(string, string): string)}} */ const obj = { foo: (a, b) => a + b }; + + /** @enum {string} */ + var E = {}; + E[""]; \ No newline at end of file diff --git a/tests/baselines/reference/jsdocInTypeScript.js b/tests/baselines/reference/jsdocInTypeScript.js index e79f400d039..ebff5629c37 100644 --- a/tests/baselines/reference/jsdocInTypeScript.js +++ b/tests/baselines/reference/jsdocInTypeScript.js @@ -47,6 +47,10 @@ import M = N; // Error: @typedef does not create namespaces in TypeScript code. * @type {{foo: (function(string, string): string)}} */ const obj = { foo: (a, b) => a + b }; + +/** @enum {string} */ +var E = {}; +E[""]; //// [jsdocInTypeScript.js] @@ -79,3 +83,6 @@ var M = N; // Error: @typedef does not create namespaces in TypeScript code. * @type {{foo: (function(string, string): string)}} */ var obj = { foo: function (a, b) { return a + b; } }; +/** @enum {string} */ +var E = {}; +E[""]; diff --git a/tests/baselines/reference/jsdocInTypeScript.symbols b/tests/baselines/reference/jsdocInTypeScript.symbols index 52caadb2064..c65d1215abe 100644 --- a/tests/baselines/reference/jsdocInTypeScript.symbols +++ b/tests/baselines/reference/jsdocInTypeScript.symbols @@ -83,3 +83,10 @@ const obj = { foo: (a, b) => a + b }; >a : Symbol(a, Decl(jsdocInTypeScript.ts, 47, 20)) >b : Symbol(b, Decl(jsdocInTypeScript.ts, 47, 22)) +/** @enum {string} */ +var E = {}; +>E : Symbol(E, Decl(jsdocInTypeScript.ts, 50, 3)) + +E[""]; +>E : Symbol(E, Decl(jsdocInTypeScript.ts, 50, 3)) + diff --git a/tests/baselines/reference/jsdocInTypeScript.types b/tests/baselines/reference/jsdocInTypeScript.types index 8916e006242..010efb68b7a 100644 --- a/tests/baselines/reference/jsdocInTypeScript.types +++ b/tests/baselines/reference/jsdocInTypeScript.types @@ -93,3 +93,13 @@ const obj = { foo: (a, b) => a + b }; >a : any >b : any +/** @enum {string} */ +var E = {}; +>E : {} +>{} : {} + +E[""]; +>E[""] : any +>E : {} +>"" : "" + diff --git a/tests/cases/compiler/jsdocInTypeScript.ts b/tests/cases/compiler/jsdocInTypeScript.ts index bceac17aa2c..4d1f0fbbe42 100644 --- a/tests/cases/compiler/jsdocInTypeScript.ts +++ b/tests/cases/compiler/jsdocInTypeScript.ts @@ -46,3 +46,7 @@ import M = N; // Error: @typedef does not create namespaces in TypeScript code. * @type {{foo: (function(string, string): string)}} */ const obj = { foo: (a, b) => a + b }; + +/** @enum {string} */ +var E = {}; +E[""]; From ea67e3ac563f51568c3a71cfd7c68f1d0a08dda8 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 13 Sep 2018 15:18:53 -0700 Subject: [PATCH 126/146] Fix watch of project with project references --- src/compiler/builder.ts | 29 ++++++++----- src/compiler/program.ts | 41 +++++++++++++------ src/compiler/types.ts | 3 +- src/compiler/utilities.ts | 6 +++ src/compiler/watch.ts | 23 +++++++---- src/server/project.ts | 4 +- src/services/services.ts | 5 ++- .../unittests/reuseProgramStructure.ts | 3 +- src/testRunner/unittests/tsbuildWatchMode.ts | 8 ++++ src/testRunner/unittests/tscWatchMode.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 15 ++++--- tests/baselines/reference/api/typescript.d.ts | 15 ++++--- 12 files changed, 102 insertions(+), 52 deletions(-) diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index f4a61267144..fbc2dc3f7d2 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -294,7 +294,7 @@ namespace ts { configFileParsingDiagnostics: ReadonlyArray; } - export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderCreationParameters { + export function getBuilderCreationParameters(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: BuilderProgram | CompilerHost, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderCreationParameters { let host: BuilderProgramHost; let newProgram: Program; let oldProgram: BuilderProgram; @@ -307,7 +307,14 @@ namespace ts { } else if (isArray(newProgramOrRootNames)) { oldProgram = configFileParsingDiagnosticsOrOldProgram as BuilderProgram; - newProgram = createProgram(newProgramOrRootNames, hostOrOptions as CompilerOptions, oldProgramOrHost as CompilerHost, oldProgram && oldProgram.getProgram(), configFileParsingDiagnostics); + newProgram = createProgram({ + rootNames: newProgramOrRootNames, + options: hostOrOptions as CompilerOptions, + host: oldProgramOrHost as CompilerHost, + oldProgram: oldProgram && oldProgram.getProgram(), + configFileParsingDiagnostics, + projectReferences + }); host = oldProgramOrHost as CompilerHost; } else { @@ -623,9 +630,9 @@ namespace ts { * Create the builder to manage semantic diagnostics and cache them */ export function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + export function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.SemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** @@ -633,18 +640,18 @@ namespace ts { * to emit the those files and manage semantic diagnostics cache as well */ export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray) { - return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics)); + export function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + export function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray) { + return createBuilderProgram(BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences)); } /** * Creates a builder thats just abstraction over program and can be used with watch */ export function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram { - const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics); + export function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; + export function createAbstractBuilder(newProgramOrRootNames: Program | ReadonlyArray | undefined, hostOrOptions: BuilderProgramHost | CompilerOptions | undefined, oldProgramOrHost?: CompilerHost | BuilderProgram, configFileParsingDiagnosticsOrOldProgram?: ReadonlyArray | BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram { + const { newProgram: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return { // Only return program, all other methods are not implemented getProgram: () => program, diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 61bf38db805..ab19041611d 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -442,6 +442,7 @@ namespace ts { fileExists: (fileName: string) => boolean, hasInvalidatedResolution: HasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames: boolean, + projectReferences: ReadonlyArray | undefined ): boolean { // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date if (!program || hasChangedAutomaticTypeDirectiveNames) { @@ -453,6 +454,11 @@ namespace ts { return false; } + // If project references dont match + if (!arrayIsEqualTo(program.getProjectReferences(), projectReferences)) { + return false; + } + // If any file is not up-to-date, then the whole program is not up-to-date if (program.getSourceFiles().some(sourceFileNotUptoDate)) { return false; @@ -759,7 +765,8 @@ namespace ts { isEmittedFile, getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences + getProjectReferences, + getResolvedProjectReferences }; verifyCompilerOptions(); @@ -1007,15 +1014,21 @@ namespace ts { } // Check if any referenced project tsconfig files are different - const oldRefs = oldProgram.getProjectReferences(); + + // If array of references is changed, we cant resue old program + const oldProjectReferences = oldProgram.getProjectReferences(); + if (!arrayIsEqualTo(oldProjectReferences!, projectReferences, projectReferencesIsEqualTo)) { + return oldProgram.structureIsReused = StructureIsReused.Not; + } + + // Check the json files for the project references + const oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { - if (!oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } + Debug.assert(!!oldRefs); for (let i = 0; i < projectReferences.length; i++) { - const oldRef = oldRefs[i]; + const oldRef = oldRefs![i]; + const newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (oldRef) { - const newRef = parseProjectReferenceConfigFile(projectReferences[i]); if (!newRef || newRef.sourceFile !== oldRef.sourceFile) { // Resolved project reference has gone missing or changed return oldProgram.structureIsReused = StructureIsReused.Not; @@ -1023,16 +1036,14 @@ namespace ts { } else { // A previously-unresolved reference may be resolved now - if (parseProjectReferenceConfigFile(projectReferences[i]) !== undefined) { + if (newRef !== undefined) { return oldProgram.structureIsReused = StructureIsReused.Not; } } } } else { - if (oldRefs) { - return oldProgram.structureIsReused = StructureIsReused.Not; - } + Debug.assert(!oldRefs); } // check if program source files has changed in the way that can affect structure of the program @@ -1219,7 +1230,7 @@ namespace ts { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); + resolvedProjectReferences = oldProgram.getResolvedProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; @@ -1257,10 +1268,14 @@ namespace ts { }; } - function getProjectReferences() { + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes(): InputFiles[] { if (!projectReferences) { return emptyArray; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a0d07e00591..85b52e0637f 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2815,7 +2815,8 @@ namespace ts { /* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } /* @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1efbd278aed..c84a9b34980 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -249,6 +249,12 @@ namespace ts { sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } + export function projectReferencesIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { + return oldRef.path === newRef.path && + !oldRef.prepend === !newRef.prepend && + !oldRef.circular === !newRef.circular; + } + export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean { return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport && oldResolution.extension === newResolution.extension && diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index c091ad5c30c..a3b0cc23c23 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -263,10 +263,11 @@ namespace ts { /** * Creates the watch compiler host from system for compiling root files and options in watch mode */ - export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions { + export function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions { const host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus) as WatchCompilerHostOfFilesAndCompilerOptions; host.rootFiles = rootFiles; host.options = options; + host.projectReferences = projectReferences; return host; } } @@ -274,7 +275,7 @@ namespace ts { namespace ts { export type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + export type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ export interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -360,6 +361,9 @@ namespace ts { /** Compiler options */ options: CompilerOptions; + + /** Project References */ + projectReferences?: ReadonlyArray; } /** @@ -413,11 +417,11 @@ namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; export function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; - export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { + export function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; + export function createWatchCompilerHost(rootFilesOrConfigFileName: string | string[], options: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions | WatchCompilerHostOfConfigFile { if (isArray(rootFilesOrConfigFileName)) { - return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus); // TODO: GH#18217 + return createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options!, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences); // TODO: GH#18217 } else { return createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); @@ -463,7 +467,7 @@ namespace ts { const getCurrentDirectory = () => currentDirectory; const readFile: (path: string, encoding?: string) => string | undefined = (path, encoding) => host.readFile(path, encoding); const { configFileName, optionsToExtend: optionsToExtendForConfigFile = {}, createProgram } = host; - let { rootFiles: rootFileNames, options: compilerOptions } = host; + let { rootFiles: rootFileNames, options: compilerOptions, projectReferences } = host; let configFileSpecs: ConfigFileSpecs; let configFileParsingDiagnostics: ReadonlyArray | undefined; let hasChangedConfigFileParsingErrors = false; @@ -589,9 +593,9 @@ namespace ts { // All resolutions are invalid if user provided resolutions const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); - if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) { if (hasChangedConfigFileParsingErrors) { - builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); hasChangedConfigFileParsingErrors = false; } } @@ -620,7 +624,7 @@ namespace ts { resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences); resolutionCache.finishCachingPerDirectoryResolution(); // Update watches @@ -861,6 +865,7 @@ namespace ts { rootFileNames = configFileParseResult.fileNames; compilerOptions = configFileParseResult.options; configFileSpecs = configFileParseResult.configFileSpecs!; // TODO: GH#18217 + projectReferences = configFileParseResult.projectReferences; configFileParsingDiagnostics = getConfigFileParsingDiagnostics(configFileParseResult); hasChangedConfigFileParsingErrors = true; } diff --git a/src/server/project.ts b/src/server/project.ts index f20530c88a9..3cabc8793db 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -574,7 +574,7 @@ namespace ts.server { for (const f of this.program.getSourceFiles()) { this.detachScriptInfoIfNotRoot(f.fileName); } - const projectReferences = this.program.getProjectReferences(); + const projectReferences = this.program.getResolvedProjectReferences(); if (projectReferences) { for (const ref of projectReferences) { if (ref) { @@ -1390,7 +1390,7 @@ namespace ts.server { /*@internal*/ getResolvedProjectReferences() { const program = this.getCurrentProgram(); - return program && program.getProjectReferences(); + return program && program.getResolvedProjectReferences(); } enablePlugins() { diff --git a/src/services/services.ts b/src/services/services.ts index 7f2ac2bcc81..0cbd4107028 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1175,9 +1175,10 @@ namespace ts { const rootFileNames = hostCache.getRootFileNames(); const hasInvalidatedResolution: HasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse; + const projectReferences = hostCache.getProjectReferences(); // If the program is already up-to-date, we can reuse it - if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames)) { + if (isProgramUptoDate(program, rootFileNames, hostCache.compilationSettings(), path => hostCache!.getVersion(path), fileExists, hasInvalidatedResolution, !!host.hasChangedAutomaticTypeDirectiveNames, projectReferences)) { return; } @@ -1240,7 +1241,7 @@ namespace ts { options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences }; program = createProgram(options); diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f0f9cc6493b..3fec096d4fa 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -914,7 +914,8 @@ namespace ts { program, newRootFileNames, newOptions, path => program.getSourceFileByPath(path)!.version, /*fileExists*/ returnFalse, /*hasInvalidatedResolution*/ returnFalse, - /*hasChangedAutomaticTypeDirectiveNames*/ false + /*hasChangedAutomaticTypeDirectiveNames*/ false, + /*projectReferences*/ undefined ); assert.isTrue(actual); } diff --git a/src/testRunner/unittests/tsbuildWatchMode.ts b/src/testRunner/unittests/tsbuildWatchMode.ts index daa1276e023..7de3437c1fa 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -149,6 +149,14 @@ export class someClass2 { }`); } }); + it("tsc-watch works with project references", () => { + // Build the composite project + const host = createSolutionInWatchMode(); + + createWatchOfConfigFile(tests[0].path, host); + checkOutputErrorsInitial(host, emptyArray); + }); + // TODO: write tests reporting errors but that will have more involved work since file }); } diff --git a/src/testRunner/unittests/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index da1c4fd0d70..8e7bb175136 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -20,7 +20,7 @@ namespace ts.tscWatch { checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); } - function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + export function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; const watch = createWatchProgram(compilerHost); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9465a512a1f..73b29d8ad4d 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1811,7 +1811,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -4315,23 +4316,23 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -4393,6 +4394,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4430,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 66ba75bbd93..2093992e223 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1811,7 +1811,8 @@ declare namespace ts { getTypeChecker(): TypeChecker; isSourceFileFromExternalLibrary(file: SourceFile): boolean; isSourceFileDefaultLibrary(file: SourceFile): boolean; - getProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; + getProjectReferences(): ReadonlyArray | undefined; + getResolvedProjectReferences(): (ResolvedProjectReference | undefined)[] | undefined; } interface ResolvedProjectReference { commandLine: ParsedCommandLine; @@ -4315,23 +4316,23 @@ declare namespace ts { * Create the builder to manage semantic diagnostics and cache them */ function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; - function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): SemanticDiagnosticsBuilderProgram; /** * Create the builder that can handle the changes in program and iterate through changed files * to emit the those files and manage semantic diagnostics cache as well */ function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; - function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): EmitAndSemanticDiagnosticsBuilderProgram; /** * Creates a builder thats just abstraction over program and can be used with watch */ function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; - function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: BuilderProgram, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray): BuilderProgram; } declare namespace ts { type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string, options: CompilerOptions) => void; /** Create the program with rootNames and options, if they are undefined, oldProgram and new configFile diagnostics create new program */ - type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray) => T; + type CreateProgram = (rootNames: ReadonlyArray | undefined, options: CompilerOptions | undefined, host?: CompilerHost, oldProgram?: T, configFileParsingDiagnostics?: ReadonlyArray, projectReferences?: ReadonlyArray | undefined) => T; /** Host that has watch functionality used in --watch mode */ interface WatchHost { /** If provided, called with Diagnostic message that informs about change in watch status */ @@ -4393,6 +4394,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4430,8 @@ declare namespace ts { /** * Create the watch compiler host for either configFile or fileNames and its options */ - function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter, projectReferences?: ReadonlyArray): WatchCompilerHostOfFilesAndCompilerOptions; /** * Creates the watch from the host for root files and compiler options */ From f71d6005a259c3c29c2e2a19bd4d0ee42392328c Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 13 Sep 2018 15:49:06 -0700 Subject: [PATCH 127/146] Use nextToken() after parsing a tag name so we can parse type keywords (#26915) * Use nextToken() after parsing a tag name so we can parse type keywords * Make callback to skipWhitespaceOrAsterisk non-optional --- src/compiler/checker.ts | 9 +++++---- src/compiler/parser.ts | 19 ++++++++++--------- ...ocComments.parsesCorrectly.@link tags.json | 4 ++-- ...cComments.parsesCorrectly.templateTag.json | 4 ++-- ...Comments.parsesCorrectly.templateTag2.json | 4 ++-- ...Comments.parsesCorrectly.templateTag3.json | 4 ++-- ...Comments.parsesCorrectly.templateTag4.json | 4 ++-- ...Comments.parsesCorrectly.templateTag5.json | 4 ++-- ...Comments.parsesCorrectly.templateTag6.json | 4 ++-- tests/baselines/reference/enumTag.errors.txt | 2 +- tests/baselines/reference/enumTag.symbols | 2 +- tests/baselines/reference/enumTag.types | 2 +- .../reference/paramTagWrapping.errors.txt | 8 ++++---- tests/cases/conformance/jsdoc/enumTag.ts | 2 +- 14 files changed, 37 insertions(+), 35 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f4314726942..3e9a3300726 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -29938,10 +29938,11 @@ namespace ts { } function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { - const jsdocTypeParameters = isInJSFile(node) && getJSDocTypeParameterDeclarations(node); - if (node.typeParameters || jsdocTypeParameters && jsdocTypeParameters.length) { - const { pos, end } = node.typeParameters || jsdocTypeParameters && jsdocTypeParameters[0] || node; - return grammarErrorAtPos(node, pos, end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); + const jsdocTypeParameters = isInJSFile(node) ? getJSDocTypeParameterDeclarations(node) : undefined; + const range = node.typeParameters || jsdocTypeParameters && firstOrUndefined(jsdocTypeParameters); + if (range) { + const pos = range.pos === range.end ? range.pos : skipTrivia(getSourceFileOfNode(node).text, range.pos); + return grammarErrorAtPos(node, pos, range.end - pos, Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration); } } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 415a62e5627..33829fccb7a 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -6517,7 +6517,7 @@ namespace ts { } } - function skipWhitespaceOrAsterisk(): void { + function skipWhitespaceOrAsterisk(next: () => void): void { if (token() === SyntaxKind.WhitespaceTrivia || token() === SyntaxKind.NewLineTrivia) { if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) { return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range @@ -6532,7 +6532,7 @@ namespace ts { else if (token() === SyntaxKind.AsteriskToken) { precedingLineBreak = false; } - nextJSDocToken(); + next(); } } @@ -6542,8 +6542,9 @@ namespace ts { atToken.end = scanner.getTextPos(); nextJSDocToken(); - const tagName = parseJSDocIdentifierName(); - skipWhitespaceOrAsterisk(); + // Use 'nextToken' instead of 'nextJsDocToken' so we can parse a type like 'number' in `@enum number` + const tagName = parseJSDocIdentifierName(/*message*/ undefined, nextToken); + skipWhitespaceOrAsterisk(nextToken); let tag: JSDocTag | undefined; switch (tagName.escapedText) { @@ -6687,7 +6688,7 @@ namespace ts { } function tryParseTypeExpression(): JSDocTypeExpression | undefined { - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); return token() === SyntaxKind.OpenBraceToken ? parseJSDocTypeExpression() : undefined; } @@ -6727,7 +6728,7 @@ namespace ts { function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); const { name, isBracketed } = parseBracketNameInPropertyAndParamTag(); skipWhitespace(); @@ -6861,7 +6862,7 @@ namespace ts { function parseTypedefTag(atToken: AtToken, tagName: Identifier, indent: number): JSDocTypedefTag { const typeExpression = tryParseTypeExpression(); - skipWhitespaceOrAsterisk(); + skipWhitespaceOrAsterisk(nextJSDocToken); const typedefTag = createNode(SyntaxKind.JSDocTypedefTag, atToken.pos); typedefTag.atToken = atToken; @@ -7114,7 +7115,7 @@ namespace ts { return entity; } - function parseJSDocIdentifierName(message?: DiagnosticMessage): Identifier { + function parseJSDocIdentifierName(message?: DiagnosticMessage, next: () => void = nextJSDocToken): Identifier { if (!tokenIsIdentifierOrKeyword(token())) { return createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ !message, message || Diagnostics.Identifier_expected); } @@ -7125,7 +7126,7 @@ namespace ts { result.escapedText = escapeLeadingUnderscores(scanner.getTokenText()); finishNode(result, end); - nextJSDocToken(); + next(); return result; } } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json index c694d240371..2ea60ed3e42 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json @@ -6,7 +6,7 @@ "0": { "kind": "JSDocTag", "pos": 63, - "end": 68, + "end": 67, "atToken": { "kind": "AtToken", "pos": 63, @@ -22,7 +22,7 @@ }, "length": 1, "pos": 63, - "end": 68 + "end": 67 }, "comment": "{@link first link}\nInside {@link link text} thing" } \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index 4d16157d91d..cd453fce8c5 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -31,7 +31,7 @@ } }, "length": 1, - "pos": 18, + "pos": 17, "end": 19 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index 3f5f2a54ec7..bfc59a6a3bb 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 18, + "pos": 17, "end": 21 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index 193c5c0eb01..e6ad0c0d0f3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 18, + "pos": 17, "end": 22 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index 193c5c0eb01..e6ad0c0d0f3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 18, + "pos": 17, "end": 22 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index fca64bcb430..f09001e97e2 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 18, + "pos": 17, "end": 23 } }, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 90158499b17..566a03b96ea 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -21,7 +21,7 @@ "typeParameters": { "0": { "kind": "TypeParameter", - "pos": 18, + "pos": 17, "end": 19, "name": { "kind": "Identifier", @@ -42,7 +42,7 @@ } }, "length": 2, - "pos": 18, + "pos": 17, "end": 24 }, "comment": "Description of type parameters." diff --git a/tests/baselines/reference/enumTag.errors.txt b/tests/baselines/reference/enumTag.errors.txt index 0c2524a1dc1..4e995ba885a 100644 --- a/tests/baselines/reference/enumTag.errors.txt +++ b/tests/baselines/reference/enumTag.errors.txt @@ -15,7 +15,7 @@ tests/cases/conformance/jsdoc/a.js(37,16): error TS2339: Property 'UNKNOWN' does /** @type {number} */ OK_I_GUESS: 2 } - /** @enum {number} */ + /** @enum number */ const Second = { MISTAKE: "end", ~~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/enumTag.symbols b/tests/baselines/reference/enumTag.symbols index ed0c11522f4..a54b9f4a3d8 100644 --- a/tests/baselines/reference/enumTag.symbols +++ b/tests/baselines/reference/enumTag.symbols @@ -19,7 +19,7 @@ const Target = { OK_I_GUESS: 2 >OK_I_GUESS : Symbol(OK_I_GUESS, Decl(a.js, 5, 15)) } -/** @enum {number} */ +/** @enum number */ const Second = { >Second : Symbol(Second, Decl(a.js, 10, 5)) diff --git a/tests/baselines/reference/enumTag.types b/tests/baselines/reference/enumTag.types index fa8e537b6f5..a8eddab88c7 100644 --- a/tests/baselines/reference/enumTag.types +++ b/tests/baselines/reference/enumTag.types @@ -25,7 +25,7 @@ const Target = { >OK_I_GUESS : number >2 : 2 } -/** @enum {number} */ +/** @enum number */ const Second = { >Second : { MISTAKE: string; OK: number; FINE: number; } >{ MISTAKE: "end", OK: 1, /** @type {number} */ FINE: 2,} : { MISTAKE: string; OK: number; FINE: number; } diff --git a/tests/baselines/reference/paramTagWrapping.errors.txt b/tests/baselines/reference/paramTagWrapping.errors.txt index 48100f0e746..3263443dbac 100644 --- a/tests/baselines/reference/paramTagWrapping.errors.txt +++ b/tests/baselines/reference/paramTagWrapping.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/jsdoc/bad.js(2,11): error TS1003: Identifier expected. -tests/cases/conformance/jsdoc/bad.js(2,11): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. +tests/cases/conformance/jsdoc/bad.js(2,10): error TS1003: Identifier expected. +tests/cases/conformance/jsdoc/bad.js(2,10): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(5,4): error TS1003: Identifier expected. tests/cases/conformance/jsdoc/bad.js(5,4): error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. tests/cases/conformance/jsdoc/bad.js(6,19): error TS1003: Identifier expected. @@ -27,9 +27,9 @@ tests/cases/conformance/jsdoc/bad.js(9,20): error TS7006: Parameter 'z' implicit ==== tests/cases/conformance/jsdoc/bad.js (9 errors) ==== /** * @param * - + !!! error TS1003: Identifier expected. - + !!! error TS8024: JSDoc '@param' tag has name '', but there is no parameter with that name. * {number} x Arg x. * @param {number} diff --git a/tests/cases/conformance/jsdoc/enumTag.ts b/tests/cases/conformance/jsdoc/enumTag.ts index bd740d879a1..a857d4eccce 100644 --- a/tests/cases/conformance/jsdoc/enumTag.ts +++ b/tests/cases/conformance/jsdoc/enumTag.ts @@ -11,7 +11,7 @@ const Target = { /** @type {number} */ OK_I_GUESS: 2 } -/** @enum {number} */ +/** @enum number */ const Second = { MISTAKE: "end", OK: 1, From ee7d0e21dad5ea53be7170e06a8636a19c0d8d6d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 13 Sep 2018 15:49:42 -0700 Subject: [PATCH 128/146] getEditsForFileRename: Don't resolve to `a.js` when `a.ts` is moved (#27081) --- src/services/getEditsForFileRename.ts | 22 +++++++++++++------ ...tEditsForFileRename_notAffectedByJsFile.ts | 18 +++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) create mode 100644 tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts diff --git a/src/services/getEditsForFileRename.ts b/src/services/getEditsForFileRename.ts index 07c3eb7ad22..a18fab4766f 100644 --- a/src/services/getEditsForFileRename.ts +++ b/src/services/getEditsForFileRename.ts @@ -196,15 +196,23 @@ namespace ts { } function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined { - return resolved && ( - (resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, getIfExists)); + // Search through all locations looking for a moved file, and only then test already existing files. + // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. + return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function getIfExists(oldLocation: string): ToImport | undefined { - const newLocation = oldToNew(oldLocation); + function tryEach(cb: (oldFileName: string) => ToImport | undefined): ToImport | undefined { + return resolved && ( + (resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, cb)); + } - return host.fileExists!(oldLocation) || newLocation !== undefined && host.fileExists!(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + function tryGetNewFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists!(newFileName) ? { newFileName, updated: true } : undefined; // TODO: GH#18217 + } + + function tryGetOldFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return host.fileExists!(oldFileName) ? newFileName !== undefined ? { newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } diff --git a/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts b/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts new file mode 100644 index 00000000000..f1b1497f2ef --- /dev/null +++ b/tests/cases/fourslash/getEditsForFileRename_notAffectedByJsFile.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /a.ts +////export const x = 0; + +// @Filename: /a.js +////exports.x = 0; + +// @Filename: /b.ts +////import { x } from "./a"; + +verify.getEditsForFileRename({ + oldPath: "/a.ts", + newPath: "/a2.ts", + newFileContents: { + "/b.ts": 'import { x } from "./a2";', + }, +}); From 57a6dbd6fa7715e3176339743b30c1de7ed55d73 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Fri, 14 Sep 2018 08:50:18 -0700 Subject: [PATCH 129/146] Add clarifying comments --- src/services/codefixes/convertToAsyncFunction.ts | 3 ++- src/services/suggestionDiagnostics.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index ba230aa95e4..b12d4daf1c8 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -393,9 +393,10 @@ namespace ts.codefix { const shouldReturn = transformer.setOfExpressionsToReturn.get(getNodeId(parent).toString()); switch (func.kind) { case SyntaxKind.NullKeyword: - // do not produce a transformed statement for a null or undefined argument + // do not produce a transformed statement for a null argument break; case SyntaxKind.Identifier: + // identifier includes undefined if (!hasArgName) break; const synthCall = createCall(getSynthesizedDeepClone(func) as Identifier, /*typeArguments*/ undefined, [argName.identifier]); diff --git a/src/services/suggestionDiagnostics.ts b/src/services/suggestionDiagnostics.ts index 3df40c8d9df..66360948ea7 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -196,7 +196,7 @@ namespace ts { function isFixablePromiseArgument(arg: Expression): boolean { switch (arg.kind) { case SyntaxKind.NullKeyword: - case SyntaxKind.Identifier: + case SyntaxKind.Identifier: // identifier includes undefined case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: From 009dc0f1b9a624a535dd5f5f3ccc2b52536231f7 Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 14 Sep 2018 09:20:11 -0700 Subject: [PATCH 130/146] For completion in string literal union, don't include strings already in the union (#26755) --- src/services/completions.ts | 30 ++++++++++++------- .../fourslash/completionListForStringUnion.ts | 13 ++++---- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/services/completions.ts b/src/services/completions.ts index ff8c3147824..7744186126a 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -390,11 +390,12 @@ namespace ts.Completions { } type StringLiteralCompletion = { readonly kind: StringLiteralCompletionKind.Paths, readonly paths: ReadonlyArray } | StringLiteralCompletionsFromProperties | StringLiteralCompletionsFromTypes; function getStringLiteralCompletionEntries(sourceFile: SourceFile, node: StringLiteralLike, position: number, typeChecker: TypeChecker, compilerOptions: CompilerOptions, host: LanguageServiceHost): StringLiteralCompletion | undefined { - switch (node.parent.kind) { + const { parent } = node; + switch (parent.kind) { case SyntaxKind.LiteralType: - switch (node.parent.parent.kind) { + switch (parent.parent.kind) { case SyntaxKind.TypeReference: - return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent as LiteralTypeNode)), isNewIdentifier: false }; + return { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent as LiteralTypeNode)), isNewIdentifier: false }; case SyntaxKind.IndexedAccessType: // Get all apparent property names // i.e. interface Foo { @@ -402,17 +403,21 @@ namespace ts.Completions { // bar: string; // } // let x: Foo["/*completion position*/"] - return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((node.parent.parent as IndexedAccessTypeNode).objectType)); + return stringLiteralCompletionsFromProperties(typeChecker.getTypeFromTypeNode((parent.parent as IndexedAccessTypeNode).objectType)); case SyntaxKind.ImportType: return { kind: StringLiteralCompletionKind.Paths, paths: PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) }; - case SyntaxKind.UnionType: - return isTypeReferenceNode(node.parent.parent.parent) ? { kind: StringLiteralCompletionKind.Types, types: getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(node.parent.parent as UnionTypeNode)), isNewIdentifier: false } : undefined; + case SyntaxKind.UnionType: { + if (!isTypeReferenceNode(parent.parent.parent)) return undefined; + const alreadyUsedTypes = getAlreadyUsedTypesInStringLiteralUnion(parent.parent as UnionTypeNode, parent as LiteralTypeNode); + const types = getStringLiteralTypes(typeChecker.getTypeArgumentConstraint(parent.parent as UnionTypeNode)).filter(t => !contains(alreadyUsedTypes, t.value)); + return { kind: StringLiteralCompletionKind.Types, types, isNewIdentifier: false }; + } default: return undefined; } case SyntaxKind.PropertyAssignment: - if (isObjectLiteralExpression(node.parent.parent) && (node.parent).name === node) { + if (isObjectLiteralExpression(parent.parent) && (parent).name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -425,12 +430,12 @@ namespace ts.Completions { // foo({ // '/*completion position*/' // }); - return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(node.parent.parent)); + return stringLiteralCompletionsFromProperties(typeChecker.getContextualType(parent.parent)); } return fromContextualType(); case SyntaxKind.ElementAccessExpression: { - const { expression, argumentExpression } = node.parent as ElementAccessExpression; + const { expression, argumentExpression } = parent as ElementAccessExpression; if (node === argumentExpression) { // Get all names of properties on the expression // i.e. interface A { @@ -445,7 +450,7 @@ namespace ts.Completions { case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - if (!isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(node.parent)) { + if (!isRequireCall(parent, /*checkArgumentIsStringLiteralLike*/ false) && !isImportCall(parent)) { const argumentInfo = SignatureHelp.getArgumentInfoForCompletions(node, position, sourceFile); // Get string literal completions from specialized signatures of the target // i.e. declare function f(a: 'A'); @@ -476,6 +481,11 @@ namespace ts.Completions { } } + function getAlreadyUsedTypesInStringLiteralUnion(union: UnionTypeNode, current: LiteralTypeNode): ReadonlyArray { + return mapDefined(union.types, type => + type !== current && isLiteralTypeNode(type) && isStringLiteral(type.literal) ? type.literal.text : undefined); + } + function getStringLiteralCompletionsFromSignature(argumentInfo: SignatureHelp.ArgumentInfoForCompletions, checker: TypeChecker): StringLiteralCompletionsFromTypes { let isNewIdentifier = false; diff --git a/tests/cases/fourslash/completionListForStringUnion.ts b/tests/cases/fourslash/completionListForStringUnion.ts index 14e5979efbd..98755ea1e41 100644 --- a/tests/cases/fourslash/completionListForStringUnion.ts +++ b/tests/cases/fourslash/completionListForStringUnion.ts @@ -1,12 +1,11 @@ /// -//// type A = 'fooooo' | 'barrrrr'; +//// type A = 'foo' | 'bar' | 'baz'; //// type B = {}; -//// type C = B<'fooooo' | '/**/'> +//// type C = B<'foo' | '/**/'> - -goTo.marker(); -verify.completionListContains("fooooo"); -verify.completionListContains("barrrrr"); +verify.completions({ marker: "", exact: ["bar", "baz"] }); edit.insert("b"); -verify.completionListContains("barrrrr"); +verify.completions({ exact: ["bar", "baz"] }); +edit.insert("ar"); +verify.completions({ exact: ["bar", "baz"] }); From 95c1570c4b1156333980b35745722aa3ef85c4fd Mon Sep 17 00:00:00 2001 From: Andy Date: Fri, 14 Sep 2018 09:20:54 -0700 Subject: [PATCH 131/146] Fix bug: VariableDeclaration may have SemanticMeaning.All if an `@enum` in JS (#27085) --- src/services/utilities.ts | 4 +++- tests/cases/fourslash/findAllRefs_jsEnum.ts | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/findAllRefs_jsEnum.ts diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 40a9936b605..25678ad72a6 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -23,8 +23,10 @@ namespace ts { export function getMeaningFromDeclaration(node: Node): SemanticMeaning { switch (node.kind) { - case SyntaxKind.Parameter: case SyntaxKind.VariableDeclaration: + return isInJSFile(node) && getJSDocEnumTag(node) ? SemanticMeaning.All : SemanticMeaning.Value; + + case SyntaxKind.Parameter: case SyntaxKind.BindingElement: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: diff --git a/tests/cases/fourslash/findAllRefs_jsEnum.ts b/tests/cases/fourslash/findAllRefs_jsEnum.ts new file mode 100644 index 00000000000..c77b24256bf --- /dev/null +++ b/tests/cases/fourslash/findAllRefs_jsEnum.ts @@ -0,0 +1,16 @@ +/// + +// @allowJs: true + +// @Filename: /a.js +/////** @enum {string} */ +////const [|{| "isWriteAccess": true, "isDefinition": true |}E|] = { A: "" }; +////[|E|]["A"]; +/////** @type {[|E|]} */ +////const e = [|E|].A; + +verify.singleReferenceGroup( +`enum E +const E: { + A: string; +}`); From 98055ad54089faae5ed7f00747dfb985679d8b42 Mon Sep 17 00:00:00 2001 From: Benjamin Lichtman Date: Fri, 14 Sep 2018 09:46:58 -0700 Subject: [PATCH 132/146] Use separate map with smaller scope to track renames --- .../codefixes/convertToAsyncFunction.ts | 50 +++++++++++++------ 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/src/services/codefixes/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index bceee6811bb..94b311a1ea6 100644 --- a/src/services/codefixes/convertToAsyncFunction.ts +++ b/src/services/codefixes/convertToAsyncFunction.ts @@ -25,16 +25,15 @@ namespace ts.codefix { numberOfAssignmentsOriginal: number; } - interface SymbolAndIdentifierAndOriginalName { + interface SymbolAndIdentifier { identifier: Identifier; symbol: Symbol; - originalName: string; } interface Transformer { checker: TypeChecker; synthNamesMap: Map; // keys are the symbol id of the identifier - allVarNames: SymbolAndIdentifierAndOriginalName[]; + allVarNames: SymbolAndIdentifier[]; setOfExpressionsToReturn: Map; // keys are the node ids of the expressions constIdentifiers: Identifier[]; originalTypeMap: Map; // keys are the node id of the identifier @@ -61,7 +60,7 @@ namespace ts.codefix { const synthNamesMap: Map = createMap(); const originalTypeMap: Map = createMap(); - const allVarNames: SymbolAndIdentifierAndOriginalName[] = []; + const allVarNames: SymbolAndIdentifier[] = []; const isInJSFile = isInJavaScriptFile(functionToConvert); const setOfExpressionsToReturn = getAllPromiseExpressionsToReturn(functionToConvert, checker); const functionToConvertRenamed: FunctionLikeDeclaration = renameCollidingVarNames(functionToConvert, checker, synthNamesMap, context, setOfExpressionsToReturn, originalTypeMap, allVarNames); @@ -158,9 +157,10 @@ namespace ts.codefix { This function collects all existing identifier names and names of identifiers that will be created in the refactor. It then checks for any collisions and renames them through getSynthesizedDeepClone */ - function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifierAndOriginalName[]): FunctionLikeDeclaration { + function renameCollidingVarNames(nodeToRename: FunctionLikeDeclaration, checker: TypeChecker, synthNamesMap: Map, context: CodeFixContextBase, setOfAllExpressionsToReturn: Map, originalType: Map, allVarNames: SymbolAndIdentifier[]): FunctionLikeDeclaration { const identsToRenameMap: Map = createMap(); // key is the symbol id + const collidingSymbolMap: Map = createMap(); forEachChild(nodeToRename, function visit(node: Node) { if (!isIdentifier(node)) { forEachChild(node, visit); @@ -180,27 +180,31 @@ namespace ts.codefix { if (lastCallSignature && lastCallSignature.parameters.length && !synthNamesMap.has(symbolIdString)) { const firstParameter = lastCallSignature.parameters[0]; const ident = isParameter(firstParameter.valueDeclaration) && tryCast(firstParameter.valueDeclaration.name, isIdentifier) || createOptimisticUniqueName("result"); - const synthName = getNewNameIfConflict(ident, allVarNames); + const synthName = getNewNameIfConflict(ident, collidingSymbolMap); synthNamesMap.set(symbolIdString, synthName); - allVarNames.push({ identifier: synthName.identifier, symbol, originalName: ident.text }); + allVarNames.push({ identifier: synthName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, ident.text, symbol); } // we only care about identifiers that are parameters and declarations (don't care about other uses) else if (node.parent && (isParameter(node.parent) || isVariableDeclaration(node.parent))) { const originalName = node.text; + const collidingSymbols = collidingSymbolMap.get(originalName); // if the identifier name conflicts with a different identifier that we've already seen - if (allVarNames.some(ident => ident.originalName === node.text && ident.symbol !== symbol)) { - const newName = getNewNameIfConflict(node, allVarNames); + if (collidingSymbols && collidingSymbols.some(prevSymbol => prevSymbol !== symbol)) { + const newName = getNewNameIfConflict(node, collidingSymbolMap); identsToRenameMap.set(symbolIdString, newName.identifier); synthNamesMap.set(symbolIdString, newName); - allVarNames.push({ identifier: newName.identifier, symbol, originalName }); + allVarNames.push({ identifier: newName.identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } else { const identifier = getSynthesizedDeepClone(node); identsToRenameMap.set(symbolIdString, identifier); synthNamesMap.set(symbolIdString, { identifier, types: [], numberOfAssignmentsOriginal: allVarNames.filter(elem => elem.identifier.text === node.text).length/*, numberOfAssignmentsSynthesized: 0*/ }); if ((isParameter(node.parent) && isExpressionOrCallOnTypePromise(node.parent.parent)) || isVariableDeclaration(node.parent)) { - allVarNames.push({ identifier, symbol, originalName }); + allVarNames.push({ identifier, symbol }); + addNameToFrequencyMap(collidingSymbolMap, originalName, symbol); } } } @@ -243,8 +247,17 @@ namespace ts.codefix { } - function getNewNameIfConflict(name: Identifier, allVarNames: SymbolAndIdentifierAndOriginalName[]): SynthIdentifier { - const numVarsSameName = allVarNames.filter(elem => elem.originalName === name.text).length; + function addNameToFrequencyMap(renamedVarNameFrequencyMap: Map, originalName: string, symbol: Symbol) { + if (renamedVarNameFrequencyMap.has(originalName)) { + renamedVarNameFrequencyMap.get(originalName)!.push(symbol); + } + else { + renamedVarNameFrequencyMap.set(originalName, [symbol]); + } + } + + function getNewNameIfConflict(name: Identifier, originalNames: Map): SynthIdentifier { + const numVarsSameName = (originalNames.get(name.text) || []).length; const numberOfAssignmentsOriginal = 0; const identifier = numVarsSameName === 0 ? name : createIdentifier(name.text + "_" + numVarsSameName); return { identifier, types: [], numberOfAssignmentsOriginal }; @@ -289,13 +302,14 @@ namespace ts.codefix { prevArgName.numberOfAssignmentsOriginal = 2; // Try block and catch block transformer.synthNamesMap.forEach((val, key) => { if (val.identifier.text === prevArgName.identifier.text) { - transformer.synthNamesMap.set(key, getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames)); + const newSynthName = createUniqueSynthName(prevArgName); + transformer.synthNamesMap.set(key, newSynthName); } }); // update the constIdentifiers list if (transformer.constIdentifiers.some(elem => elem.text === prevArgName.identifier.text)) { - transformer.constIdentifiers.push(getNewNameIfConflict(prevArgName.identifier, transformer.allVarNames).identifier); + transformer.constIdentifiers.push(createUniqueSynthName(prevArgName).identifier); } } @@ -321,6 +335,12 @@ namespace ts.codefix { return varDeclList ? [varDeclList, tryStatement] : [tryStatement]; } + function createUniqueSynthName(prevArgName: SynthIdentifier) { + const renamedPrevArg = createOptimisticUniqueName(prevArgName.identifier.text); + const newSynthName = { identifier: renamedPrevArg, types: [], numberOfAssignmentsOriginal: 0 }; + return newSynthName; + } + function transformThen(node: CallExpression, transformer: Transformer, outermostParent: CallExpression, prevArgName?: SynthIdentifier): Statement[] { const [res, rej] = node.arguments; From 513a16264b42849fd0160f28763a533ad15a1f26 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 14 Sep 2018 10:02:42 -0700 Subject: [PATCH 133/146] Make parseCommandLineWorker non generic --- src/compiler/commandLineParser.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 9391fac72ed..05113f812db 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -912,12 +912,12 @@ namespace ts { /** Tuple with error messages for 'unknown compiler option', 'option requires type' */ type ParseCommandLineWorkerDiagnostics = [DiagnosticMessage, DiagnosticMessage]; - function parseCommandLineWorker( + function parseCommandLineWorker( getOptionNameMap: () => OptionNameMap, [unknownOptionDiagnostic, optionTypeMismatchDiagnostic]: ParseCommandLineWorkerDiagnostics, commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined) { - const options = {} as T; + const options = {} as OptionsBase; const fileNames: string[] = []; const errors: Diagnostic[] = []; @@ -1061,10 +1061,11 @@ namespace ts { export function parseBuildCommand(args: string[]): ParsedBuildCommand { let buildOptionNameMap: OptionNameMap | undefined; const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts))); - const { options: buildOptions, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ + const { options, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ Diagnostics.Unknown_build_option_0, Diagnostics.Build_option_0_requires_a_value_of_type_1 ], args); + const buildOptions = options as BuildOptions; if (projects.length === 0) { // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ." From 20f671ede2d9f2eb4cd4088e4b36aeed9bd0472f Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 14 Sep 2018 11:07:22 -0700 Subject: [PATCH 134/146] PR feedback --- src/compiler/program.ts | 4 +++- src/compiler/utilities.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 970689f93c3..d15b5935224 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1017,13 +1017,14 @@ namespace ts { // If array of references is changed, we cant resue old program const oldProjectReferences = oldProgram.getProjectReferences(); - if (!arrayIsEqualTo(oldProjectReferences!, projectReferences, projectReferencesIsEqualTo)) { + if (!arrayIsEqualTo(oldProjectReferences!, projectReferences, projectReferenceIsEqualTo)) { return oldProgram.structureIsReused = StructureIsReused.Not; } // Check the json files for the project references const oldRefs = oldProgram.getResolvedProjectReferences(); if (projectReferences) { + // Resolved project referenced should be array if projectReferences provided are array Debug.assert(!!oldRefs); for (let i = 0; i < projectReferences.length; i++) { const oldRef = oldRefs![i]; @@ -1043,6 +1044,7 @@ namespace ts { } } else { + // Resolved project referenced should be undefined if projectReferences is undefined Debug.assert(!oldRefs); } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 51315dbf455..907e921b91f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -249,7 +249,7 @@ namespace ts { sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective); } - export function projectReferencesIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { + export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) { return oldRef.path === newRef.path && !oldRef.prepend === !newRef.prepend && !oldRef.circular === !newRef.circular; From c63d58148a8abaf21f59a4f2bdf65ffa2372e635 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 14 Sep 2018 12:44:02 -0700 Subject: [PATCH 135/146] Fix the usage of createProgram in tsc --- src/tsc/tsc.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index 29cac24fdd0..ec2d029e60a 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -222,12 +222,12 @@ namespace ts { function updateWatchCompilationHost(watchCompilerHost: WatchCompilerHost) { const compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics) => { + watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics); + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = builderProgram => { From d6ffdde059e92173d7dd4c05258198dce71c2936 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 14 Sep 2018 12:57:40 -0700 Subject: [PATCH 136/146] Revert the API change to resolveProjectReferencePath introduced in #27062 --- src/compiler/program.ts | 13 ++++++++++--- tests/baselines/reference/api/tsserverlibrary.d.ts | 4 ++++ tests/baselines/reference/api/typescript.d.ts | 4 ++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 1ba3d3233cc..a9271d6fcbb 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -2820,13 +2820,20 @@ namespace ts { }; } + // For backward compatibility + /** @deprecated */ export interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } + /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ - // TODO: Does this need to be exposed - export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName { - return resolveConfigFileProjectName(ref.path); + export function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ export function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; + export function resolveProjectReferencePath(hostOrRef: ResolveProjectReferencePathHost | ProjectReference, ref?: ProjectReference): ResolvedConfigFileName { + const passedInRef = ref ? ref : hostOrRef as ProjectReference; + return resolveConfigFileProjectName(passedInRef.path); } /* @internal */ diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 388525096e1..d02e761f440 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4182,11 +4182,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + /** @deprecated */ interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 2a0dfb89b85..e6c104d3c5a 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4182,11 +4182,15 @@ declare namespace ts { * @returns A 'Program' object. */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program, configFileParsingDiagnostics?: ReadonlyArray): Program; + /** @deprecated */ interface ResolveProjectReferencePathHost { + fileExists(fileName: string): boolean; + } /** * Returns the target config filename of a project reference. * Note: The file might not exist. */ function resolveProjectReferencePath(ref: ProjectReference): ResolvedConfigFileName; + /** @deprecated */ function resolveProjectReferencePath(host: ResolveProjectReferencePathHost, ref: ProjectReference): ResolvedConfigFileName; } declare namespace ts { interface EmitOutput { From 4eb59a2d77acde13d808ec302f6a28f4fa49aa01 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 14 Sep 2018 14:18:47 -0700 Subject: [PATCH 137/146] Fixing react defaultize+generic default props interaction (#27088) * Add repro for fixed issue * Fix JSX propagating flags and contextual types * Accept slightly changed baselines * Add modern react.d.ts and regression test --- src/compiler/checker.ts | 14 +- ...xGenericTagHasCorrectInferences.errors.txt | 12 +- ...ypeContextualTypeSimplificationsSuceeds.js | 25 + ...ntextualTypeSimplificationsSuceeds.symbols | 68 + ...ContextualTypeSimplificationsSuceeds.types | 53 + ...xChildrenGenericContextualTypes.errors.txt | 4 +- .../jsxChildrenGenericContextualTypes.types | 6 +- ...actDefaultPropsInferenceSuccess.errors.txt | 67 + .../reactDefaultPropsInferenceSuccess.js | 112 + .../reactDefaultPropsInferenceSuccess.symbols | 131 + .../reactDefaultPropsInferenceSuccess.types | 146 + ...ypeContextualTypeSimplificationsSuceeds.ts | 16 + .../reactDefaultPropsInferenceSuccess.tsx | 54 + tests/lib/react16.d.ts | 2569 +++++++++++++++++ 14 files changed, 3261 insertions(+), 16 deletions(-) create mode 100644 tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.js create mode 100644 tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.symbols create mode 100644 tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.types create mode 100644 tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt create mode 100644 tests/baselines/reference/reactDefaultPropsInferenceSuccess.js create mode 100644 tests/baselines/reference/reactDefaultPropsInferenceSuccess.symbols create mode 100644 tests/baselines/reference/reactDefaultPropsInferenceSuccess.types create mode 100644 tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts create mode 100644 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx create mode 100644 tests/lib/react16.d.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3e9a3300726..c4cd1aa6051 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -17361,12 +17361,14 @@ namespace ts { let hasSpreadAnyType = false; let typeToIntersect: Type | undefined; let explicitlySpecifyChildrenAttribute = false; + let propagatingFlags: TypeFlags = 0; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); for (const attributeDecl of attributes.properties) { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); + propagatingFlags |= (exprType.flags & TypeFlags.PropagatingFlags); const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -17384,7 +17386,7 @@ namespace ts { else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); attributesTable = createSymbolTable(); } const exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -17392,7 +17394,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, openingLikeElement.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, exprType, openingLikeElement.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -17402,7 +17404,7 @@ namespace ts { if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } } @@ -17428,7 +17430,7 @@ namespace ts { const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), - attributes.symbol, /*typeFlags*/ 0, ObjectFlags.JsxAttributes); + attributes.symbol, propagatingFlags, ObjectFlags.JsxAttributes); } } @@ -17448,7 +17450,7 @@ namespace ts { */ function createJsxAttributesType() { const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= TypeFlags.ContainsObjectLiteral; + result.flags |= (propagatingFlags |= TypeFlags.ContainsObjectLiteral); result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.JsxAttributes; return result; } @@ -21957,7 +21959,7 @@ namespace ts { } function getContextNode(node: Expression): Node { - if (node.kind === SyntaxKind.JsxAttributes) { + if (node.kind === SyntaxKind.JsxAttributes && !isJsxSelfClosingElement(node.parent)) { return node.parent.parent; // Needs to be the root JsxElement, so it encompasses the attributes _and_ the children (which are essentially part of the attributes) } return node; diff --git a/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt b/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt index 6b81ccd77e1..36ebc70b76c 100644 --- a/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt +++ b/tests/baselines/reference/checkJsxGenericTagHasCorrectInferences.errors.txt @@ -1,5 +1,6 @@ -tests/cases/conformance/jsx/file.tsx(13,54): error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. - Type 'string' is not assignable to type '{ x: string; }'. +tests/cases/conformance/jsx/file.tsx(13,54): error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '((a: { x: string; }) => string) & ((cur: { x: string; }) => { x: string; })'. + Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. + Type 'string' is not assignable to type '{ x: string; }'. ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -17,6 +18,7 @@ tests/cases/conformance/jsx/file.tsx(13,54): error TS2322: Type '(a: { x: string let c = ({ x: a.x })} />; // No Error let d = a.x} />; // Error - `string` is not assignable to `{x: string}` ~~~~~~~~~~ -!!! error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. -!!! error TS2322: Type 'string' is not assignable to type '{ x: string; }'. -!!! related TS6500 tests/cases/conformance/jsx/file.tsx:13:54: The expected type comes from property 'nextValues' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & { initialValues: { x: string; }; nextValues: {}; } & BaseProps<{ x: string; }> & { children?: ReactNode; }' \ No newline at end of file +!!! error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '((a: { x: string; }) => string) & ((cur: { x: string; }) => { x: string; })'. +!!! error TS2322: Type '(a: { x: string; }) => string' is not assignable to type '(cur: { x: string; }) => { x: string; }'. +!!! error TS2322: Type 'string' is not assignable to type '{ x: string; }'. +!!! related TS6500 tests/cases/conformance/jsx/file.tsx:13:54: The expected type comes from property 'nextValues' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes string; }, { x: string; }>> & { initialValues: { x: string; }; nextValues: (a: { x: string; }) => string; } & BaseProps<{ x: string; }> & { children?: ReactNode; }' \ No newline at end of file diff --git a/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.js b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.js new file mode 100644 index 00000000000..7d140a32b42 --- /dev/null +++ b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.js @@ -0,0 +1,25 @@ +//// [conditionalTypeContextualTypeSimplificationsSuceeds.ts] +// repro from https://github.com/Microsoft/TypeScript/issues/26395 +interface Props { + when: (value: string) => boolean; +} + +function bad

( + attrs: string extends keyof P ? { [K in keyof P]: P[K] } : { [K in keyof P]: P[K] }) { } +function good1

( + attrs: string extends keyof P ? P : { [K in keyof P]: P[K] }) { } +function good2

( + attrs: { [K in keyof P]: P[K] }) { } + +bad({ when: value => false }); +good1({ when: value => false }); +good2({ when: value => false }); + +//// [conditionalTypeContextualTypeSimplificationsSuceeds.js] +"use strict"; +function bad(attrs) { } +function good1(attrs) { } +function good2(attrs) { } +bad({ when: function (value) { return false; } }); +good1({ when: function (value) { return false; } }); +good2({ when: function (value) { return false; } }); diff --git a/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.symbols b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.symbols new file mode 100644 index 00000000000..e9620b38656 --- /dev/null +++ b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.symbols @@ -0,0 +1,68 @@ +=== tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/26395 +interface Props { +>Props : Symbol(Props, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 0, 0)) + + when: (value: string) => boolean; +>when : Symbol(Props.when, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 1, 17)) +>value : Symbol(value, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 2, 11)) +} + +function bad

( +>bad : Symbol(bad, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 3, 1)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>Props : Symbol(Props, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 0, 0)) + + attrs: string extends keyof P ? { [K in keyof P]: P[K] } : { [K in keyof P]: P[K] }) { } +>attrs : Symbol(attrs, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 30)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 39)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 39)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 66)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 5, 13)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 66)) + +function good1

( +>good1 : Symbol(good1, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 92)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 15)) +>Props : Symbol(Props, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 0, 0)) + + attrs: string extends keyof P ? P : { [K in keyof P]: P[K] }) { } +>attrs : Symbol(attrs, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 32)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 15)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 15)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 8, 43)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 15)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 7, 15)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 8, 43)) + +function good2

( +>good2 : Symbol(good2, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 8, 69)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 9, 15)) +>Props : Symbol(Props, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 0, 0)) + + attrs: { [K in keyof P]: P[K] }) { } +>attrs : Symbol(attrs, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 9, 32)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 10, 14)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 9, 15)) +>P : Symbol(P, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 9, 15)) +>K : Symbol(K, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 10, 14)) + +bad({ when: value => false }); +>bad : Symbol(bad, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 3, 1)) +>when : Symbol(when, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 12, 5)) +>value : Symbol(value, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 12, 11)) + +good1({ when: value => false }); +>good1 : Symbol(good1, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 6, 92)) +>when : Symbol(when, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 13, 7)) +>value : Symbol(value, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 13, 13)) + +good2({ when: value => false }); +>good2 : Symbol(good2, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 8, 69)) +>when : Symbol(when, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 14, 7)) +>value : Symbol(value, Decl(conditionalTypeContextualTypeSimplificationsSuceeds.ts, 14, 13)) + diff --git a/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.types b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.types new file mode 100644 index 00000000000..cf55d7c3bcd --- /dev/null +++ b/tests/baselines/reference/conditionalTypeContextualTypeSimplificationsSuceeds.types @@ -0,0 +1,53 @@ +=== tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts === +// repro from https://github.com/Microsoft/TypeScript/issues/26395 +interface Props { + when: (value: string) => boolean; +>when : (value: string) => boolean +>value : string +} + +function bad

( +>bad :

(attrs: string extends keyof P ? { [K in keyof P]: P[K]; } : { [K in keyof P]: P[K]; }) => void + + attrs: string extends keyof P ? { [K in keyof P]: P[K] } : { [K in keyof P]: P[K] }) { } +>attrs : string extends keyof P ? { [K in keyof P]: P[K]; } : { [K in keyof P]: P[K]; } + +function good1

( +>good1 :

(attrs: string extends keyof P ? P : { [K in keyof P]: P[K]; }) => void + + attrs: string extends keyof P ? P : { [K in keyof P]: P[K] }) { } +>attrs : string extends keyof P ? P : { [K in keyof P]: P[K]; } + +function good2

( +>good2 :

(attrs: { [K in keyof P]: P[K]; }) => void + + attrs: { [K in keyof P]: P[K] }) { } +>attrs : { [K in keyof P]: P[K]; } + +bad({ when: value => false }); +>bad({ when: value => false }) : void +>bad :

(attrs: string extends keyof P ? { [K in keyof P]: P[K]; } : { [K in keyof P]: P[K]; }) => void +>{ when: value => false } : { when: (value: string) => false; } +>when : (value: string) => false +>value => false : (value: string) => false +>value : string +>false : false + +good1({ when: value => false }); +>good1({ when: value => false }) : void +>good1 :

(attrs: string extends keyof P ? P : { [K in keyof P]: P[K]; }) => void +>{ when: value => false } : { when: (value: string) => false; } +>when : (value: string) => false +>value => false : (value: string) => false +>value : string +>false : false + +good2({ when: value => false }); +>good2({ when: value => false }) : void +>good2 :

(attrs: { [K in keyof P]: P[K]; }) => void +>{ when: value => false } : { when: (value: string) => false; } +>when : (value: string) => false +>value => false : (value: string) => false +>value : string +>false : false + diff --git a/tests/baselines/reference/jsxChildrenGenericContextualTypes.errors.txt b/tests/baselines/reference/jsxChildrenGenericContextualTypes.errors.txt index 9c9b85fd04d..f9e193d104b 100644 --- a/tests/baselines/reference/jsxChildrenGenericContextualTypes.errors.txt +++ b/tests/baselines/reference/jsxChildrenGenericContextualTypes.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/jsxChildrenGenericContextualTypes.tsx(20,31): error TS2322: Type '(p: IntrinsicAttributes & LitProps<"x">) => "y"' is not assignable to type '(x: IntrinsicAttributes & LitProps<"x">) => "x"'. +tests/cases/compiler/jsxChildrenGenericContextualTypes.tsx(20,31): error TS2322: Type '(p: LitProps<"x">) => "y"' is not assignable to type '(x: IntrinsicAttributes & LitProps<"x">) => "x"'. Type '"y"' is not assignable to type '"x"'. tests/cases/compiler/jsxChildrenGenericContextualTypes.tsx(21,19): error TS2322: Type '{ children: (p: IntrinsicAttributes & LitProps<"x">) => "y"; prop: "x"; }' is not assignable to type 'IntrinsicAttributes & LitProps<"x" | "y">'. Type '{ children: (p: IntrinsicAttributes & LitProps<"x">) => "y"; prop: "x"; }' is not assignable to type 'LitProps<"x" | "y">'. @@ -39,7 +39,7 @@ tests/cases/compiler/jsxChildrenGenericContextualTypes.tsx(22,21): error TS2322: // Should error const arg = "y"} /> ~~~~~~~~ -!!! error TS2322: Type '(p: IntrinsicAttributes & LitProps<"x">) => "y"' is not assignable to type '(x: IntrinsicAttributes & LitProps<"x">) => "x"'. +!!! error TS2322: Type '(p: LitProps<"x">) => "y"' is not assignable to type '(x: IntrinsicAttributes & LitProps<"x">) => "x"'. !!! error TS2322: Type '"y"' is not assignable to type '"x"'. !!! related TS6500 tests/cases/compiler/jsxChildrenGenericContextualTypes.tsx:13:34: The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & LitProps<"x">' const argchild = {p => "y"} diff --git a/tests/baselines/reference/jsxChildrenGenericContextualTypes.types b/tests/baselines/reference/jsxChildrenGenericContextualTypes.types index 9287a8a02de..0e5cf26d4c7 100644 --- a/tests/baselines/reference/jsxChildrenGenericContextualTypes.types +++ b/tests/baselines/reference/jsxChildrenGenericContextualTypes.types @@ -117,9 +117,9 @@ const arg = "y"} /> > "y"} /> : JSX.Element >ElemLit : (p: LitProps) => JSX.Element >prop : "x" ->children : (p: JSX.IntrinsicAttributes & LitProps<"x">) => "y" ->p => "y" : (p: JSX.IntrinsicAttributes & LitProps<"x">) => "y" ->p : JSX.IntrinsicAttributes & LitProps<"x"> +>children : (p: LitProps<"x">) => "y" +>p => "y" : (p: LitProps<"x">) => "y" +>p : LitProps<"x"> >"y" : "y" const argchild = {p => "y"} diff --git a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt new file mode 100644 index 00000000000..2ec0fc09c92 --- /dev/null +++ b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.errors.txt @@ -0,0 +1,67 @@ +tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx(26,36): error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. + Type 'void' is not assignable to type 'boolean'. +tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx(48,37): error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. + Type 'void' is not assignable to type 'boolean'. + + +==== tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx (2 errors) ==== + /// + + import React from 'react'; + + interface BaseProps { + when?: (value: string) => boolean; + } + + interface Props extends BaseProps { + } + + class FieldFeedback

extends React.Component

{ + static defaultProps = { + when: () => true + }; + + render() { + return

Hello
; + } + } + + // OK + const Test1 = () => !!value} />; + + // Error: Void not assignable to boolean + const Test2 = () => console.log(value)} />; + ~~~~ +!!! error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. +!!! error TS2322: Type 'void' is not assignable to type 'boolean'. +!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:6:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children"> & Partial & Readonly, "when">> & Partial boolean; }, never>>' + + + interface MyPropsProps extends Props { + when: (value: string) => boolean; + } + + class FieldFeedback2

extends FieldFeedback

{ + static defaultProps = { + when: () => true + }; + + render() { + this.props.when("now"); // OK, always defined + return

Hello
; + } + } + + // OK + const Test3 = () => !!value} />; + + // Error: Void not assignable to boolean + const Test4 = () => console.log(value)} />; + ~~~~ +!!! error TS2322: Type '(value: string) => void' is not assignable to type '(value: string) => boolean'. +!!! error TS2322: Type 'void' is not assignable to type 'boolean'. +!!! related TS6500 tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx:30:3: The expected type comes from property 'when' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes> & Pick & Readonly, "children"> & Partial & Readonly, "when">> & Partial boolean; }, never>>' + + // OK + const Test5 = () => ; + \ No newline at end of file diff --git a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.js b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.js new file mode 100644 index 00000000000..84db36ee4da --- /dev/null +++ b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.js @@ -0,0 +1,112 @@ +//// [reactDefaultPropsInferenceSuccess.tsx] +/// + +import React from 'react'; + +interface BaseProps { + when?: (value: string) => boolean; +} + +interface Props extends BaseProps { +} + +class FieldFeedback

extends React.Component

{ + static defaultProps = { + when: () => true + }; + + render() { + return

Hello
; + } +} + +// OK +const Test1 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test2 = () => console.log(value)} />; + + +interface MyPropsProps extends Props { + when: (value: string) => boolean; +} + +class FieldFeedback2

extends FieldFeedback

{ + static defaultProps = { + when: () => true + }; + + render() { + this.props.when("now"); // OK, always defined + return

Hello
; + } +} + +// OK +const Test3 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test4 = () => console.log(value)} />; + +// OK +const Test5 = () => ; + + +//// [reactDefaultPropsInferenceSuccess.js] +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + } + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var react_1 = __importDefault(require("react")); +var FieldFeedback = /** @class */ (function (_super) { + __extends(FieldFeedback, _super); + function FieldFeedback() { + return _super !== null && _super.apply(this, arguments) || this; + } + FieldFeedback.prototype.render = function () { + return react_1["default"].createElement("div", null, "Hello"); + }; + FieldFeedback.defaultProps = { + when: function () { return true; } + }; + return FieldFeedback; +}(react_1["default"].Component)); +// OK +var Test1 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return !!value; } }); }; +// Error: Void not assignable to boolean +var Test2 = function () { return react_1["default"].createElement(FieldFeedback, { when: function (value) { return console.log(value); } }); }; +var FieldFeedback2 = /** @class */ (function (_super) { + __extends(FieldFeedback2, _super); + function FieldFeedback2() { + return _super !== null && _super.apply(this, arguments) || this; + } + FieldFeedback2.prototype.render = function () { + this.props.when("now"); // OK, always defined + return react_1["default"].createElement("div", null, "Hello"); + }; + FieldFeedback2.defaultProps = { + when: function () { return true; } + }; + return FieldFeedback2; +}(FieldFeedback)); +// OK +var Test3 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return !!value; } }); }; +// Error: Void not assignable to boolean +var Test4 = function () { return react_1["default"].createElement(FieldFeedback2, { when: function (value) { return console.log(value); } }); }; +// OK +var Test5 = function () { return react_1["default"].createElement(FieldFeedback2, null); }; diff --git a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.symbols b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.symbols new file mode 100644 index 00000000000..dadaf9ea745 --- /dev/null +++ b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.symbols @@ -0,0 +1,131 @@ +=== tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx === +/// + +import React from 'react'; +>React : Symbol(React, Decl(reactDefaultPropsInferenceSuccess.tsx, 2, 6)) + +interface BaseProps { +>BaseProps : Symbol(BaseProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 2, 26)) + + when?: (value: string) => boolean; +>when : Symbol(BaseProps.when, Decl(reactDefaultPropsInferenceSuccess.tsx, 4, 21)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 5, 10)) +} + +interface Props extends BaseProps { +>Props : Symbol(Props, Decl(reactDefaultPropsInferenceSuccess.tsx, 6, 1)) +>BaseProps : Symbol(BaseProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 2, 26)) +} + +class FieldFeedback

extends React.Component

{ +>FieldFeedback : Symbol(FieldFeedback, Decl(reactDefaultPropsInferenceSuccess.tsx, 9, 1)) +>P : Symbol(P, Decl(reactDefaultPropsInferenceSuccess.tsx, 11, 20)) +>Props : Symbol(Props, Decl(reactDefaultPropsInferenceSuccess.tsx, 6, 1)) +>BaseProps : Symbol(BaseProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 2, 26)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(reactDefaultPropsInferenceSuccess.tsx, 2, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>P : Symbol(P, Decl(reactDefaultPropsInferenceSuccess.tsx, 11, 20)) + + static defaultProps = { +>defaultProps : Symbol(FieldFeedback.defaultProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 11, 77)) + + when: () => true +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 12, 25)) + + }; + + render() { +>render : Symbol(FieldFeedback.render, Decl(reactDefaultPropsInferenceSuccess.tsx, 14, 4)) + + return

Hello
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + } +} + +// OK +const Test1 = () => !!value} />; +>Test1 : Symbol(Test1, Decl(reactDefaultPropsInferenceSuccess.tsx, 22, 5)) +>FieldFeedback : Symbol(FieldFeedback, Decl(reactDefaultPropsInferenceSuccess.tsx, 9, 1)) +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 22, 34)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 22, 41)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 22, 41)) + +// Error: Void not assignable to boolean +const Test2 = () => console.log(value)} />; +>Test2 : Symbol(Test2, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 5)) +>FieldFeedback : Symbol(FieldFeedback, Decl(reactDefaultPropsInferenceSuccess.tsx, 9, 1)) +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 34)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 41)) +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 41)) + + +interface MyPropsProps extends Props { +>MyPropsProps : Symbol(MyPropsProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 73)) +>Props : Symbol(Props, Decl(reactDefaultPropsInferenceSuccess.tsx, 6, 1)) + + when: (value: string) => boolean; +>when : Symbol(MyPropsProps.when, Decl(reactDefaultPropsInferenceSuccess.tsx, 28, 38)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 29, 9)) +} + +class FieldFeedback2

extends FieldFeedback

{ +>FieldFeedback2 : Symbol(FieldFeedback2, Decl(reactDefaultPropsInferenceSuccess.tsx, 30, 1)) +>P : Symbol(P, Decl(reactDefaultPropsInferenceSuccess.tsx, 32, 21)) +>MyPropsProps : Symbol(MyPropsProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 73)) +>MyPropsProps : Symbol(MyPropsProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 25, 73)) +>FieldFeedback : Symbol(FieldFeedback, Decl(reactDefaultPropsInferenceSuccess.tsx, 9, 1)) +>P : Symbol(P, Decl(reactDefaultPropsInferenceSuccess.tsx, 32, 21)) + + static defaultProps = { +>defaultProps : Symbol(FieldFeedback2.defaultProps, Decl(reactDefaultPropsInferenceSuccess.tsx, 32, 86)) + + when: () => true +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 33, 25)) + + }; + + render() { +>render : Symbol(FieldFeedback2.render, Decl(reactDefaultPropsInferenceSuccess.tsx, 35, 4)) + + this.props.when("now"); // OK, always defined +>this.props.when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 28, 38)) +>this.props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) +>this : Symbol(FieldFeedback2, Decl(reactDefaultPropsInferenceSuccess.tsx, 30, 1)) +>props : Symbol(React.Component.props, Decl(react16.d.ts, 367, 32)) +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 28, 38)) + + return

Hello
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + } +} + +// OK +const Test3 = () => !!value} />; +>Test3 : Symbol(Test3, Decl(reactDefaultPropsInferenceSuccess.tsx, 44, 5)) +>FieldFeedback2 : Symbol(FieldFeedback2, Decl(reactDefaultPropsInferenceSuccess.tsx, 30, 1)) +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 44, 35)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 44, 42)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 44, 42)) + +// Error: Void not assignable to boolean +const Test4 = () => console.log(value)} />; +>Test4 : Symbol(Test4, Decl(reactDefaultPropsInferenceSuccess.tsx, 47, 5)) +>FieldFeedback2 : Symbol(FieldFeedback2, Decl(reactDefaultPropsInferenceSuccess.tsx, 30, 1)) +>when : Symbol(when, Decl(reactDefaultPropsInferenceSuccess.tsx, 47, 35)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 47, 42)) +>console.log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>console : Symbol(console, Decl(lib.dom.d.ts, --, --)) +>log : Symbol(Console.log, Decl(lib.dom.d.ts, --, --)) +>value : Symbol(value, Decl(reactDefaultPropsInferenceSuccess.tsx, 47, 42)) + +// OK +const Test5 = () => ; +>Test5 : Symbol(Test5, Decl(reactDefaultPropsInferenceSuccess.tsx, 50, 5)) +>FieldFeedback2 : Symbol(FieldFeedback2, Decl(reactDefaultPropsInferenceSuccess.tsx, 30, 1)) + diff --git a/tests/baselines/reference/reactDefaultPropsInferenceSuccess.types b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.types new file mode 100644 index 00000000000..91d918b0923 --- /dev/null +++ b/tests/baselines/reference/reactDefaultPropsInferenceSuccess.types @@ -0,0 +1,146 @@ +=== tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx === +/// + +import React from 'react'; +>React : typeof React + +interface BaseProps { + when?: (value: string) => boolean; +>when : ((value: string) => boolean) | undefined +>value : string +} + +interface Props extends BaseProps { +} + +class FieldFeedback

extends React.Component

{ +>FieldFeedback : FieldFeedback

+>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + + static defaultProps = { +>defaultProps : { when: () => boolean; } +>{ when: () => true } : { when: () => boolean; } + + when: () => true +>when : () => boolean +>() => true : () => boolean +>true : true + + }; + + render() { +>render : () => JSX.Element + + return

Hello
; +>
Hello
: JSX.Element +>div : any +>div : any + } +} + +// OK +const Test1 = () => !!value} />; +>Test1 : () => JSX.Element +>() => !!value} /> : () => JSX.Element +> !!value} /> : JSX.Element +>FieldFeedback : typeof FieldFeedback +>when : (value: string) => boolean +>value => !!value : (value: string) => boolean +>value : string +>!!value : boolean +>!value : boolean +>value : string + +// Error: Void not assignable to boolean +const Test2 = () => console.log(value)} />; +>Test2 : () => JSX.Element +>() => console.log(value)} /> : () => JSX.Element +> console.log(value)} /> : JSX.Element +>FieldFeedback : typeof FieldFeedback +>when : (value: string) => void +>value => console.log(value) : (value: string) => void +>value : string +>console.log(value) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>value : string + + +interface MyPropsProps extends Props { + when: (value: string) => boolean; +>when : (value: string) => boolean +>value : string +} + +class FieldFeedback2

extends FieldFeedback

{ +>FieldFeedback2 : FieldFeedback2

+>FieldFeedback : FieldFeedback

+ + static defaultProps = { +>defaultProps : { when: () => boolean; } +>{ when: () => true } : { when: () => boolean; } + + when: () => true +>when : () => boolean +>() => true : () => boolean +>true : true + + }; + + render() { +>render : () => JSX.Element + + this.props.when("now"); // OK, always defined +>this.props.when("now") : boolean +>this.props.when : P["when"] +>this.props : Readonly<{ children?: React.ReactNode; }> & Readonly

+>this : this +>props : Readonly<{ children?: React.ReactNode; }> & Readonly

+>when : P["when"] +>"now" : "now" + + return

Hello
; +>
Hello
: JSX.Element +>div : any +>div : any + } +} + +// OK +const Test3 = () => !!value} />; +>Test3 : () => JSX.Element +>() => !!value} /> : () => JSX.Element +> !!value} /> : JSX.Element +>FieldFeedback2 : typeof FieldFeedback2 +>when : (value: string) => boolean +>value => !!value : (value: string) => boolean +>value : string +>!!value : boolean +>!value : boolean +>value : string + +// Error: Void not assignable to boolean +const Test4 = () => console.log(value)} />; +>Test4 : () => JSX.Element +>() => console.log(value)} /> : () => JSX.Element +> console.log(value)} /> : JSX.Element +>FieldFeedback2 : typeof FieldFeedback2 +>when : (value: string) => void +>value => console.log(value) : (value: string) => void +>value : string +>console.log(value) : void +>console.log : (message?: any, ...optionalParams: any[]) => void +>console : Console +>log : (message?: any, ...optionalParams: any[]) => void +>value : string + +// OK +const Test5 = () => ; +>Test5 : () => JSX.Element +>() => : () => JSX.Element +> : JSX.Element +>FieldFeedback2 : typeof FieldFeedback2 + diff --git a/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts b/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts new file mode 100644 index 00000000000..f585022cccf --- /dev/null +++ b/tests/cases/compiler/conditionalTypeContextualTypeSimplificationsSuceeds.ts @@ -0,0 +1,16 @@ +// @strict: true +// repro from https://github.com/Microsoft/TypeScript/issues/26395 +interface Props { + when: (value: string) => boolean; +} + +function bad

( + attrs: string extends keyof P ? { [K in keyof P]: P[K] } : { [K in keyof P]: P[K] }) { } +function good1

( + attrs: string extends keyof P ? P : { [K in keyof P]: P[K] }) { } +function good2

( + attrs: { [K in keyof P]: P[K] }) { } + +bad({ when: value => false }); +good1({ when: value => false }); +good2({ when: value => false }); \ No newline at end of file diff --git a/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx b/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx new file mode 100644 index 00000000000..9de13d119df --- /dev/null +++ b/tests/cases/compiler/reactDefaultPropsInferenceSuccess.tsx @@ -0,0 +1,54 @@ +// @jsx: react +// @strict: true +// @esModuleInterop: true +/// + +import React from 'react'; + +interface BaseProps { + when?: (value: string) => boolean; +} + +interface Props extends BaseProps { +} + +class FieldFeedback

extends React.Component

{ + static defaultProps = { + when: () => true + }; + + render() { + return

Hello
; + } +} + +// OK +const Test1 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test2 = () => console.log(value)} />; + + +interface MyPropsProps extends Props { + when: (value: string) => boolean; +} + +class FieldFeedback2

extends FieldFeedback

{ + static defaultProps = { + when: () => true + }; + + render() { + this.props.when("now"); // OK, always defined + return

Hello
; + } +} + +// OK +const Test3 = () => !!value} />; + +// Error: Void not assignable to boolean +const Test4 = () => console.log(value)} />; + +// OK +const Test5 = () => ; diff --git a/tests/lib/react16.d.ts b/tests/lib/react16.d.ts new file mode 100644 index 00000000000..4b91fb0c6fe --- /dev/null +++ b/tests/lib/react16.d.ts @@ -0,0 +1,2569 @@ +// Type definitions for React 16.4 +// Project: http://facebook.github.io/react/ +// Definitions by: Asana +// AssureSign +// Microsoft +// John Reilly +// Benoit Benezech +// Patricio Zavolinsky +// Digiguru +// Eric Anderson +// Albert Kurniawan +// Tanguy Krotoff +// Dovydas Navickas +// Stéphane Goetz +// Josh Rutherford +// Guilherme Hübner +// Ferdy Budhidharma +// Johann Rakotoharisoa +// Olivier Pascal +// Martin Hochel +// Frank Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +interface HTMLWebViewElement extends HTMLElement {} + +declare module "prop-types" { + // Type definitions for prop-types 15.5 + // Project: https://github.com/reactjs/prop-types + // Definitions by: DovydasNavickas + // Ferdy Budhidharma + // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + // TypeScript Version: 2.8 + + import { ReactNode, ReactElement } from 'react'; + + export const nominalTypeHack: unique symbol; + + export type IsOptional = undefined | null extends T ? true : undefined extends T ? true : null extends T ? true : false; + + export type RequiredKeys = { [K in keyof V]: V[K] extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; + export type OptionalKeys = Exclude>; + export type InferPropsInner = { [K in keyof V]: InferType; }; + + export interface Validator { + (props: object, propName: string, componentName: string, location: string, propFullName: string): Error | null; + [nominalTypeHack]?: T; + } + + export interface Requireable extends Validator { + isRequired: Validator>; + } + + export type ValidationMap = { [K in keyof T]-?: Validator }; + + export type InferType = V extends Validator ? T : any; + export type InferProps = + & InferPropsInner>> + & Partial>>>; + + export const any: Requireable; + export const array: Requireable; + export const bool: Requireable; + export const func: Requireable<(...args: any[]) => any>; + export const number: Requireable; + export const object: Requireable; + export const string: Requireable; + export const node: Requireable; + export const element: Requireable>; + export const symbol: Requireable; + export function instanceOf(expectedClass: new (...args: any[]) => T): Requireable; + export function oneOf(types: T[]): Requireable; + export function oneOfType>(types: T[]): Requireable>>; + export function arrayOf(type: Validator): Requireable; + export function objectOf(type: Validator): Requireable<{ [K in keyof any]: T; }>; + export function shape

>(type: P): Requireable>; + export function exact

>(type: P): Requireable>>; + + /** + * Assert that the values match with the type specs. + * Error messages are memorized and will only be shown once. + * + * @param typeSpecs Map of name to a ReactPropType + * @param values Runtime values that need to be type-checked + * @param location e.g. "prop", "context", "child context" + * @param componentName Name of the component for error messages. + * @param getStack Returns the component stack. + */ + export function checkPropTypes(typeSpecs: any, values: any, location: string, componentName: string, getStack?: () => any): void; + +} + +declare module "react" { + + import * as PropTypes from 'prop-types'; + + type NativeAnimationEvent = AnimationEvent; + type NativeClipboardEvent = ClipboardEvent; + type NativeCompositionEvent = CompositionEvent; + type NativeDragEvent = DragEvent; + type NativeFocusEvent = FocusEvent; + type NativeKeyboardEvent = KeyboardEvent; + type NativeMouseEvent = MouseEvent; + type NativeTouchEvent = TouchEvent; + type NativePointerEvent = PointerEvent; + type NativeTransitionEvent = TransitionEvent; + type NativeUIEvent = UIEvent; + type NativeWheelEvent = WheelEvent; + + // tslint:disable-next-line:export-just-namespace + export = React; + + namespace React { + // + // React Elements + // ---------------------------------------------------------------------- + + type ReactType

= string | ComponentType

; + type ComponentType

= ComponentClass

| StatelessComponent

; + + type Key = string | number; + + interface RefObject { + readonly current: T | null; + } + + type Ref = string | { bivarianceHack(instance: T | null): any }["bivarianceHack"] | RefObject; + + type ComponentState = any; + + interface Attributes { + key?: Key; + } + interface ClassAttributes extends Attributes { + ref?: Ref; + } + + interface ReactElement

{ + type: string | ComponentClass

| SFC

; + props: P; + key: Key | null; + } + + interface SFCElement

extends ReactElement

{ + type: SFC

; + } + + type CElement> = ComponentElement; + interface ComponentElement> extends ReactElement

{ + type: ComponentClass

; + ref?: Ref; + } + + type ClassicElement

= CElement>; + + // string fallback for custom web-components + interface DOMElement

| SVGAttributes, T extends Element> extends ReactElement

{ + type: string; + ref: Ref; + } + + // ReactHTML for ReactHTMLElement + // tslint:disable-next-line:no-empty-interface + interface ReactHTMLElement extends DetailedReactHTMLElement, T> { } + + interface DetailedReactHTMLElement

, T extends HTMLElement> extends DOMElement { + type: keyof ReactHTML; + } + + // ReactSVG for ReactSVGElement + interface ReactSVGElement extends DOMElement, SVGElement> { + type: keyof ReactSVG; + } + + interface ReactPortal extends ReactElement { + key: Key | null; + children: ReactNode; + } + + // + // Factories + // ---------------------------------------------------------------------- + + type Factory

= (props?: Attributes & P, ...children: ReactNode[]) => ReactElement

; + + type SFCFactory

= (props?: Attributes & P, ...children: ReactNode[]) => SFCElement

; + + type ComponentFactory> = + (props?: ClassAttributes & P, ...children: ReactNode[]) => CElement; + + type CFactory> = ComponentFactory; + type ClassicFactory

= CFactory>; + + type DOMFactory

, T extends Element> = + (props?: ClassAttributes & P | null, ...children: ReactNode[]) => DOMElement; + + // tslint:disable-next-line:no-empty-interface + interface HTMLFactory extends DetailedHTMLFactory, T> { } + + interface DetailedHTMLFactory

, T extends HTMLElement> extends DOMFactory { + (props?: ClassAttributes & P | null, ...children: ReactNode[]): DetailedReactHTMLElement; + } + + interface SVGFactory extends DOMFactory, SVGElement> { + (props?: ClassAttributes & SVGAttributes | null, ...children: ReactNode[]): ReactSVGElement; + } + + // + // React Nodes + // http://facebook.github.io/react/docs/glossary.html + // ---------------------------------------------------------------------- + + type ReactText = string | number; + type ReactChild = ReactElement | ReactText; + + interface ReactNodeArray extends Array { } + type ReactFragment = {} | ReactNodeArray; + type ReactNode = ReactChild | ReactFragment | ReactPortal | string | number | boolean | null | undefined; + + // + // Top Level API + // ---------------------------------------------------------------------- + + // DOM Elements + function createFactory( + type: keyof ReactHTML): HTMLFactory; + function createFactory( + type: keyof ReactSVG): SVGFactory; + function createFactory

, T extends Element>( + type: string): DOMFactory; + + // Custom components + function createFactory

(type: SFC

): SFCFactory

; + function createFactory

( + type: ClassType, ClassicComponentClass

>): CFactory>; + function createFactory, C extends ComponentClass

>( + type: ClassType): CFactory; + function createFactory

(type: ComponentClass

): Factory

; + + // DOM Elements + // TODO: generalize this to everything in `keyof ReactHTML`, not just "input" + function createElement( + type: "input", + props?: InputHTMLAttributes & ClassAttributes | null, + ...children: ReactNode[]): DetailedReactHTMLElement, HTMLInputElement>; + function createElement

, T extends HTMLElement>( + type: keyof ReactHTML, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): DetailedReactHTMLElement; + function createElement

, T extends SVGElement>( + type: keyof ReactSVG, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): DOMElement; + + // Custom components + function createElement

( + type: SFC

, + props?: Attributes & P | null, + ...children: ReactNode[]): SFCElement

; + function createElement

( + type: ClassType, ClassicComponentClass

>, + props?: ClassAttributes> & P | null, + ...children: ReactNode[]): CElement>; + function createElement, C extends ComponentClass

>( + type: ClassType, + props?: ClassAttributes & P | null, + ...children: ReactNode[]): CElement; + function createElement

( + type: SFC

| ComponentClass

| string, + props?: Attributes & P | null, + ...children: ReactNode[]): ReactElement

; + + // DOM Elements + // ReactHTMLElement + function cloneElement

, T extends HTMLElement>( + element: DetailedReactHTMLElement, + props?: P, + ...children: ReactNode[]): DetailedReactHTMLElement; + // ReactHTMLElement, less specific + function cloneElement

, T extends HTMLElement>( + element: ReactHTMLElement, + props?: P, + ...children: ReactNode[]): ReactHTMLElement; + // SVGElement + function cloneElement

, T extends SVGElement>( + element: ReactSVGElement, + props?: P, + ...children: ReactNode[]): ReactSVGElement; + // DOM Element (has to be the last, because type checking stops at first overload that fits) + function cloneElement

, T extends Element>( + element: DOMElement, + props?: DOMAttributes & P, + ...children: ReactNode[]): DOMElement; + + // Custom components + function cloneElement

( + element: SFCElement

, + props?: Partial

& Attributes, + ...children: ReactNode[]): SFCElement

; + function cloneElement>( + element: CElement, + props?: Partial

& ClassAttributes, + ...children: ReactNode[]): CElement; + function cloneElement

( + element: ReactElement

, + props?: Partial

& Attributes, + ...children: ReactNode[]): ReactElement

; + + // Context via RenderProps + interface ProviderProps { + value: T; + children?: ReactNode; + } + + interface ConsumerProps { + children: (value: T) => ReactNode; + unstable_observedBits?: number; + } + + type Provider = ComponentType>; + type Consumer = ComponentType>; + interface Context { + Provider: Provider; + Consumer: Consumer; + } + function createContext( + defaultValue: T, + calculateChangedBits?: (prev: T, next: T) => number + ): Context; + + function isValidElement

(object: {} | null | undefined): object is ReactElement

; + + const Children: ReactChildren; + const Fragment: ComponentType; + const StrictMode: ComponentType; + const version: string; + + // + // Component API + // ---------------------------------------------------------------------- + + type ReactInstance = Component | Element; + + // Base component for plain JS classes + // tslint:disable-next-line:no-empty-interface + interface Component

extends ComponentLifecycle { } + class Component { + constructor(props: Readonly

); + /** + * @deprecated + * https://reactjs.org/docs/legacy-context.html + */ + constructor(props: P, context?: any); + + // We MUST keep setState() as a unified signature because it allows proper checking of the method return type. + // See: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/18365#issuecomment-351013257 + // Also, the ` | S` allows intellisense to not be dumbisense + setState( + state: ((prevState: Readonly, props: Readonly

) => (Pick | S | null)) | (Pick | S | null), + callback?: () => void + ): void; + + forceUpdate(callBack?: () => void): void; + render(): ReactNode; + + // React.Props is now deprecated, which means that the `children` + // property is not available on `P` by default, even though you can + // always pass children as variadic arguments to `createElement`. + // In the future, if we can define its call signature conditionally + // on the existence of `children` in `P`, then we should remove this. + readonly props: Readonly<{ children?: ReactNode }> & Readonly

; + state: Readonly; + /** + * @deprecated + * https://reactjs.org/docs/legacy-context.html + */ + context: any; + /** + * @deprecated + * https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs + */ + refs: { + [key: string]: ReactInstance + }; + } + + class PureComponent

extends Component { } + + interface ClassicComponent

extends Component { + replaceState(nextState: S, callback?: () => void): void; + isMounted(): boolean; + getInitialState?(): S; + } + + interface ChildContextProvider { + getChildContext(): CC; + } + + // + // Class Interfaces + // ---------------------------------------------------------------------- + + type SFC

= StatelessComponent

; + interface StatelessComponent

{ + (props: P & { children?: ReactNode }, context?: any): ReactElement | null; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface RefForwardingComponent { + (props: P & { children?: ReactNode }, ref?: Ref): ReactElement | null; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface ComponentClass

extends StaticLifecycle { + new(props: P, context?: any): Component; + propTypes?: ValidationMap

; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + defaultProps?: Partial

; + displayName?: string; + } + + interface ClassicComponentClass

extends ComponentClass

{ + new(props: P, context?: any): ClassicComponent; + getDefaultProps?(): P; + } + + /** + * We use an intersection type to infer multiple type parameters from + * a single argument, which is useful for many top-level API defs. + * See https://github.com/Microsoft/TypeScript/issues/7234 for more info. + */ + type ClassType, C extends ComponentClass

> = + C & + (new (props: P, context?: any) => T) & + (new (props: P, context?: any) => { props: P }); + + // + // Component Specs and Lifecycle + // ---------------------------------------------------------------------- + + // This should actually be something like `Lifecycle | DeprecatedLifecycle`, + // as React will _not_ call the deprecated lifecycle methods if any of the new lifecycle + // methods are present. + interface ComponentLifecycle extends NewLifecycle, DeprecatedLifecycle { + /** + * Called immediately after a component is mounted. Setting state here will trigger re-rendering. + */ + componentDidMount?(): void; + /** + * Called to determine whether the change in props and state should trigger a re-render. + * + * `Component` always returns true. + * `PureComponent` implements a shallow comparison on props and state and returns true if any + * props or states have changed. + * + * If false is returned, `Component#render`, `componentWillUpdate` + * and `componentDidUpdate` will not be called. + */ + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + /** + * Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as + * cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`. + */ + componentWillUnmount?(): void; + /** + * Catches exceptions generated in descendant components. Unhandled exceptions will cause + * the entire component tree to unmount. + */ + componentDidCatch?(error: Error, errorInfo: ErrorInfo): void; + } + + // Unfortunately, we have no way of declaring that the component constructor must implement this + interface StaticLifecycle { + getDerivedStateFromProps?: GetDerivedStateFromProps; + } + + type GetDerivedStateFromProps = + /** + * Returns an update to a component's state based on its new props and old state. + * + * Note: its presence prevents any of the deprecated lifecycle methods from being invoked + */ + (nextProps: Readonly

, prevState: S) => Partial | null; + + // This should be "infer SS" but can't use it yet + interface NewLifecycle { + /** + * Runs before React applies the result of `render` to the document, and + * returns an object to be given to componentDidUpdate. Useful for saving + * things such as scroll position before `render` causes changes to it. + * + * Note: the presence of getSnapshotBeforeUpdate prevents any of the deprecated + * lifecycle events from running. + */ + getSnapshotBeforeUpdate?(prevProps: Readonly

, prevState: Readonly): SS | null; + /** + * Called immediately after updating occurs. Not called for the initial render. + * + * The snapshot is only present if getSnapshotBeforeUpdate is present and returns non-null. + */ + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, snapshot?: SS): void; + } + + interface DeprecatedLifecycle { + /** + * Called immediately before mounting occurs, and before `Component#render`. + * Avoid introducing any side-effects or subscriptions in this method. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use componentDidMount or the constructor instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillMount?(): void; + /** + * Called immediately before mounting occurs, and before `Component#render`. + * Avoid introducing any side-effects or subscriptions in this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use componentDidMount or the constructor instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#initializing-state + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillMount?(): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling `Component#setState` generally does not trigger this method. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use static getDerivedStateFromProps instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called when the component may be receiving new props. + * React may call this even if props have not changed, so be sure to compare new and existing + * props if you only want to handle changes. + * + * Calling `Component#setState` generally does not trigger this method. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use static getDerivedStateFromProps instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call `Component#setState` here. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17 + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + /** + * Called immediately before rendering when new props or state is received. Not called for the initial render. + * + * Note: You cannot call `Component#setState` here. + * + * This method will not stop working in React 17. + * + * Note: the presence of getSnapshotBeforeUpdate or getDerivedStateFromProps + * prevents this from being invoked. + * + * @deprecated 16.3, use getSnapshotBeforeUpdate instead + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#reading-dom-properties-before-an-update + * @see https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#gradual-migration-path + */ + UNSAFE_componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + } + + interface Mixin extends ComponentLifecycle { + mixins?: Array>; + statics?: { + [key: string]: any; + }; + + displayName?: string; + propTypes?: ValidationMap; + contextTypes?: ValidationMap; + childContextTypes?: ValidationMap; + + getDefaultProps?(): P; + getInitialState?(): S; + } + + interface ComponentSpec extends Mixin { + render(): ReactNode; + + [propertyName: string]: any; + } + + function createRef(): RefObject; + + function forwardRef(Component: RefForwardingComponent): ComponentType

>; + + // + // Event System + // ---------------------------------------------------------------------- + + interface SyntheticEvent { + bubbles: boolean; + /** + * A reference to the element on which the event listener is registered. + */ + currentTarget: EventTarget & T; + cancelable: boolean; + defaultPrevented: boolean; + eventPhase: number; + isTrusted: boolean; + nativeEvent: Event; + preventDefault(): void; + isDefaultPrevented(): boolean; + stopPropagation(): void; + isPropagationStopped(): boolean; + persist(): void; + // If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239 + /** + * A reference to the element from which the event was originally dispatched. + * This might be a child element to the element on which the event listener is registered. + * + * @see currentTarget + */ + target: EventTarget; + timeStamp: number; + type: string; + } + + interface ClipboardEvent extends SyntheticEvent { + clipboardData: DataTransfer; + nativeEvent: NativeClipboardEvent; + } + + interface CompositionEvent extends SyntheticEvent { + data: string; + nativeEvent: NativeCompositionEvent; + } + + interface DragEvent extends MouseEvent { + dataTransfer: DataTransfer; + nativeEvent: NativeDragEvent; + } + + interface PointerEvent extends MouseEvent { + pointerId: number; + pressure: number; + tiltX: number; + tiltY: number; + width: number; + height: number; + pointerType: 'mouse' | 'pen' | 'touch'; + isPrimary: boolean; + nativeEvent: NativePointerEvent; + } + + interface FocusEvent extends SyntheticEvent { + nativeEvent: NativeFocusEvent; + relatedTarget: EventTarget; + target: EventTarget & T; + } + + // tslint:disable-next-line:no-empty-interface + interface FormEvent extends SyntheticEvent { + } + + interface InvalidEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface ChangeEvent extends SyntheticEvent { + target: EventTarget & T; + } + + interface KeyboardEvent extends SyntheticEvent { + altKey: boolean; + charCode: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + /** + * See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values + */ + key: string; + keyCode: number; + locale: string; + location: number; + metaKey: boolean; + nativeEvent: NativeKeyboardEvent; + repeat: boolean; + shiftKey: boolean; + which: number; + } + + interface MouseEvent extends SyntheticEvent { + altKey: boolean; + button: number; + buttons: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeMouseEvent; + pageX: number; + pageY: number; + relatedTarget: EventTarget; + screenX: number; + screenY: number; + shiftKey: boolean; + } + + interface TouchEvent extends SyntheticEvent { + altKey: boolean; + changedTouches: TouchList; + ctrlKey: boolean; + /** + * See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method. + */ + getModifierState(key: string): boolean; + metaKey: boolean; + nativeEvent: NativeTouchEvent; + shiftKey: boolean; + targetTouches: TouchList; + touches: TouchList; + } + + interface UIEvent extends SyntheticEvent { + detail: number; + nativeEvent: NativeUIEvent; + view: AbstractView; + } + + interface WheelEvent extends MouseEvent { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + nativeEvent: NativeWheelEvent; + } + + interface AnimationEvent extends SyntheticEvent { + animationName: string; + elapsedTime: number; + nativeEvent: NativeAnimationEvent; + pseudoElement: string; + } + + interface TransitionEvent extends SyntheticEvent { + elapsedTime: number; + nativeEvent: NativeTransitionEvent; + propertyName: string; + pseudoElement: string; + } + + // + // Event Handler Types + // ---------------------------------------------------------------------- + + type EventHandler> = { bivarianceHack(event: E): void }["bivarianceHack"]; + + type ReactEventHandler = EventHandler>; + + type ClipboardEventHandler = EventHandler>; + type CompositionEventHandler = EventHandler>; + type DragEventHandler = EventHandler>; + type FocusEventHandler = EventHandler>; + type FormEventHandler = EventHandler>; + type ChangeEventHandler = EventHandler>; + type KeyboardEventHandler = EventHandler>; + type MouseEventHandler = EventHandler>; + type TouchEventHandler = EventHandler>; + type PointerEventHandler = EventHandler>; + type UIEventHandler = EventHandler>; + type WheelEventHandler = EventHandler>; + type AnimationEventHandler = EventHandler>; + type TransitionEventHandler = EventHandler>; + + // + // Props / DOM Attributes + // ---------------------------------------------------------------------- + + /** + * @deprecated. This was used to allow clients to pass `ref` and `key` + * to `createElement`, which is no longer necessary due to intersection + * types. If you need to declare a props object before passing it to + * `createElement` or a factory, use `ClassAttributes`: + * + * ```ts + * var b: Button | null; + * var props: ButtonProps & ClassAttributes