From 2c46f9b6870348bd14973c1e5abb2f3ba893c084 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Wed, 5 Oct 2016 17:09:58 +0200 Subject: [PATCH 01/74] Add ES8/ES2017 target (#10768) --- src/compiler/commandLineParser.ts | 2 ++ src/compiler/core.ts | 2 +- src/compiler/emitter.ts | 5 +++- src/compiler/transformer.ts | 6 +++-- src/compiler/transformers/ts.ts | 41 +++++++++++++++++++++++++------ src/compiler/types.ts | 4 ++- 6 files changed, 47 insertions(+), 13 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 648447ac26a..16d338cac6a 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -262,7 +262,9 @@ namespace ts { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, "es6": ScriptTarget.ES6, + "es8": ScriptTarget.ES8, "es2015": ScriptTarget.ES2015, + "es2017": ScriptTarget.ES2017, }), description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, paramType: Diagnostics.VERSION, diff --git a/src/compiler/core.ts b/src/compiler/core.ts index e63bcbf8474..3f2cc619cb3 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1191,7 +1191,7 @@ namespace ts { export function getEmitModuleKind(compilerOptions: CompilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : - getEmitScriptTarget(compilerOptions) === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; + getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; } /* @internal */ diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index b3242e211de..b0e31278ff0 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2192,7 +2192,10 @@ const _super = (function (geti, seti) { helpersEmitted = true; } - if (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions) { + // Only emit __awaiter function when target ES5/ES6. + // Only emit __generator function when target ES5. + // For target ES8 and above, we can emit async/await as is. + if ((languageVersion < ScriptTarget.ES8) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) { writeLines(awaiterHelper); if (languageVersion < ScriptTarget.ES6) { writeLines(generatorHelper); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 92407af2bb9..415a9ecd1d7 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -115,7 +115,9 @@ namespace ts { transformers.push(transformJsx); } - transformers.push(transformES7); + if (languageVersion < ScriptTarget.ES8) { + transformers.push(transformES7); + } if (languageVersion < ScriptTarget.ES6) { transformers.push(transformES6); @@ -339,4 +341,4 @@ namespace ts { return statements; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index f6e8074cb07..40b9e7f64e1 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -240,11 +240,14 @@ namespace ts { // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; + case SyntaxKind.AsyncKeyword: + // Async keyword is not elided for target ES8 + return languageVersion < ScriptTarget.ES8 ? undefined : node; + case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.AbstractKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ConstKeyword: case SyntaxKind.DeclareKeyword: case SyntaxKind.ReadonlyKeyword: @@ -2223,6 +2226,14 @@ namespace ts { /*location*/ node ); + // Add ES8 async function expression modifier + // Not sure this is the right place? Might be better to move this + // into createFunctionExpression itself. + if ((languageVersion >= ScriptTarget.ES8) && isAsyncFunctionLike(node)) { + const funcModifiers = visitNodes(node.modifiers, visitor, isModifier); + func.modifiers = createNodeArray(funcModifiers); + } + setOriginalNode(func, node); return func; @@ -2235,7 +2246,7 @@ namespace ts { */ function visitArrowFunction(node: ArrowFunction) { const func = createArrowFunction( - /*modifiers*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), /*typeParameters*/ undefined, visitNodes(node.parameters, visitor, isParameter), /*type*/ undefined, @@ -2250,7 +2261,7 @@ namespace ts { } function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { - if (isAsyncFunctionLike(node)) { + if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES8) { return transformAsyncFunctionBody(node); } @@ -2270,7 +2281,7 @@ namespace ts { } function transformConciseBody(node: ArrowFunction): ConciseBody { - if (isAsyncFunctionLike(node)) { + if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES8) { return transformAsyncFunctionBody(node); } @@ -2453,14 +2464,28 @@ namespace ts { * @param node The await expression node. */ function visitAwaitExpression(node: AwaitExpression): Expression { + const targetAtLeastES8 = languageVersion >= ScriptTarget.ES8; return setOriginalNode( - createYield( + targetAtLeastES8 ? createAwaitExpression() : createYieldExpression(), + node + ); + + function createAwaitExpression() { + const awaitExpression = createAwait( + visitNode(node.expression, visitor, isExpression), + /*location*/ node + ); + return awaitExpression; + } + + function createYieldExpression() { + const yieldExpression = createYield( /*asteriskToken*/ undefined, visitNode(node.expression, visitor, isExpression), /*location*/ node - ), - node - ); + ); + return yieldExpression; + } } /** diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4a4a25fd627..5b193beb155 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2831,8 +2831,10 @@ namespace ts { ES3 = 0, ES5 = 1, ES6 = 2, + ES8 = 3, ES2015 = ES6, - Latest = ES6, + ES2017 = ES8, + Latest = ES8, } export const enum LanguageVariant { From d16e846ab42e1da1558b8bbc6a28bb76ddae207f Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 6 Oct 2016 00:41:22 +0200 Subject: [PATCH 02/74] ES8/ES2017 target tests --- src/harness/unittests/commandLineParsing.ts | 2 +- .../convertCompilerOptionsFromJson.ts | 2 +- tests/baselines/reference/es8-async.js | 87 +++++++++++++ tests/baselines/reference/es8-async.symbols | 79 ++++++++++++ tests/baselines/reference/es8-async.types | 121 ++++++++++++++++++ tests/cases/compiler/es8-async.ts | 49 +++++++ 6 files changed, 338 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/es8-async.js create mode 100644 tests/baselines/reference/es8-async.symbols create mode 100644 tests/baselines/reference/es8-async.types create mode 100644 tests/cases/compiler/es8-async.ts diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 028786eef24..42fc242f08e 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -165,7 +165,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es8', 'es2015', 'es2017'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index ba25409a9b4..db3d6cfc102 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -176,7 +176,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es8', 'es2015', 'es2017'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/tests/baselines/reference/es8-async.js b/tests/baselines/reference/es8-async.js new file mode 100644 index 00000000000..3338b1f88a6 --- /dev/null +++ b/tests/baselines/reference/es8-async.js @@ -0,0 +1,87 @@ +//// [es8-async.ts] + +async (): Promise => { + await 0; +} + +async function asyncFunc() { + await 0; +} + +const asycnArrowFunc = async (): Promise => { + await 0; +} + +async function asyncIIFE() { + await 0; + + await (async function(): Promise { + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { + await 1; + })(); + + await (async (): Promise => { + await 1; + })(); +} + +class AsyncClass { + asyncPropFunc = async function(): Promise { + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { + await 2; + } + + asyncPropArrowFunc = async (): Promise => { + await 2; + } + + async asyncMethod(): Promise { + await 2; + } +} + + +//// [es8-async.js] +async () => { + await 0; +}; +async function asyncFunc() { + await 0; +} +const asycnArrowFunc = async () => { + await 0; +}; +async function asyncIIFE() { + await 0; + await (async function () { + await 1; + })(); + await (async function asyncNamedFunc() { + await 1; + })(); + await (async () => { + await 1; + })(); +} +class AsyncClass { + constructor() { + this.asyncPropFunc = async function () { + await 2; + }; + this.asyncPropNamedFunc = async function namedFunc() { + await 2; + }; + this.asyncPropArrowFunc = async () => { + await 2; + }; + } + async asyncMethod() { + await 2; + } +} diff --git a/tests/baselines/reference/es8-async.symbols b/tests/baselines/reference/es8-async.symbols new file mode 100644 index 00000000000..25a77351aef --- /dev/null +++ b/tests/baselines/reference/es8-async.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/es8-async.ts === + +async (): Promise => { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 0; +} + +async function asyncFunc() { +>asyncFunc : Symbol(asyncFunc, Decl(es8-async.ts, 3, 1)) + + await 0; +} + +const asycnArrowFunc = async (): Promise => { +>asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es8-async.ts, 9, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 0; +} + +async function asyncIIFE() { +>asyncIIFE : Symbol(asyncIIFE, Decl(es8-async.ts, 11, 1)) + + await 0; + + await (async function(): Promise { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { +>asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es8-async.ts, 20, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); + + await (async (): Promise => { +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 1; + })(); +} + +class AsyncClass { +>AsyncClass : Symbol(AsyncClass, Decl(es8-async.ts, 27, 1)) + + asyncPropFunc = async function(): Promise { +>asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es8-async.ts, 29, 18)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { +>asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es8-async.ts, 32, 5)) +>namedFunc : Symbol(namedFunc, Decl(es8-async.ts, 34, 24)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + asyncPropArrowFunc = async (): Promise => { +>asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es8-async.ts, 36, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } + + async asyncMethod(): Promise { +>asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es8-async.ts, 40, 5)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + await 2; + } +} + diff --git a/tests/baselines/reference/es8-async.types b/tests/baselines/reference/es8-async.types new file mode 100644 index 00000000000..da0ca063777 --- /dev/null +++ b/tests/baselines/reference/es8-async.types @@ -0,0 +1,121 @@ +=== tests/cases/compiler/es8-async.ts === + +async (): Promise => { +>async (): Promise => { await 0;} : () => Promise +>Promise : Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +async function asyncFunc() { +>asyncFunc : () => Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +const asycnArrowFunc = async (): Promise => { +>asycnArrowFunc : () => Promise +>async (): Promise => { await 0;} : () => Promise +>Promise : Promise + + await 0; +>await 0 : 0 +>0 : 0 +} + +async function asyncIIFE() { +>asyncIIFE : () => Promise + + await 0; +>await 0 : 0 +>0 : 0 + + await (async function(): Promise { +>await (async function(): Promise { await 1; })() : void +>(async function(): Promise { await 1; })() : Promise +>(async function(): Promise { await 1; }) : () => Promise +>async function(): Promise { await 1; } : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); + + await (async function asyncNamedFunc(): Promise { +>await (async function asyncNamedFunc(): Promise { await 1; })() : void +>(async function asyncNamedFunc(): Promise { await 1; })() : Promise +>(async function asyncNamedFunc(): Promise { await 1; }) : () => Promise +>async function asyncNamedFunc(): Promise { await 1; } : () => Promise +>asyncNamedFunc : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); + + await (async (): Promise => { +>await (async (): Promise => { await 1; })() : void +>(async (): Promise => { await 1; })() : Promise +>(async (): Promise => { await 1; }) : () => Promise +>async (): Promise => { await 1; } : () => Promise +>Promise : Promise + + await 1; +>await 1 : 1 +>1 : 1 + + })(); +} + +class AsyncClass { +>AsyncClass : AsyncClass + + asyncPropFunc = async function(): Promise { +>asyncPropFunc : () => Promise +>async function(): Promise { await 2; } : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + asyncPropNamedFunc = async function namedFunc(): Promise { +>asyncPropNamedFunc : () => Promise +>async function namedFunc(): Promise { await 2; } : () => Promise +>namedFunc : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + asyncPropArrowFunc = async (): Promise => { +>asyncPropArrowFunc : () => Promise +>async (): Promise => { await 2; } : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } + + async asyncMethod(): Promise { +>asyncMethod : () => Promise +>Promise : Promise + + await 2; +>await 2 : 2 +>2 : 2 + } +} + diff --git a/tests/cases/compiler/es8-async.ts b/tests/cases/compiler/es8-async.ts new file mode 100644 index 00000000000..0ceb6e397e5 --- /dev/null +++ b/tests/cases/compiler/es8-async.ts @@ -0,0 +1,49 @@ +// @target: es8 +// @lib: es2017 +// @noEmitHelpers: true + +async (): Promise => { + await 0; +} + +async function asyncFunc() { + await 0; +} + +const asycnArrowFunc = async (): Promise => { + await 0; +} + +async function asyncIIFE() { + await 0; + + await (async function(): Promise { + await 1; + })(); + + await (async function asyncNamedFunc(): Promise { + await 1; + })(); + + await (async (): Promise => { + await 1; + })(); +} + +class AsyncClass { + asyncPropFunc = async function(): Promise { + await 2; + } + + asyncPropNamedFunc = async function namedFunc(): Promise { + await 2; + } + + asyncPropArrowFunc = async (): Promise => { + await 2; + } + + async asyncMethod(): Promise { + await 2; + } +} From 9ca2569363809e3bd7aaf8bb817ec5a7020d231b Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 11:04:40 -0700 Subject: [PATCH 03/74] Use control flow analysis for variables initialized with [] --- src/compiler/binder.ts | 21 +++ src/compiler/checker.ts | 218 +++++++++++++++++++++------ src/compiler/diagnosticMessages.json | 2 +- src/compiler/types.ts | 14 +- 4 files changed, 210 insertions(+), 45 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 49434e80aba..624ea269d89 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -760,6 +760,15 @@ namespace ts { }; } + function createFlowArrayMutation(antecedent: FlowNode, node: Expression): FlowNode { + setFlowNodeReferenced(antecedent); + return { + flags: FlowFlags.ArrayMutation, + antecedent, + node + }; + } + function finishFlowLabel(flow: FlowLabel): FlowNode { const antecedents = flow.antecedents; if (!antecedents) { @@ -1136,6 +1145,12 @@ namespace ts { forEachChild(node, bind); if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) { bindAssignmentTargetFlow(node.left); + if (node.left.kind === SyntaxKind.ElementAccessExpression) { + const elementAccess = node.left; + if (isNarrowableReference(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, elementAccess.expression); + } + } } } } @@ -1196,6 +1211,12 @@ namespace ts { else { forEachChild(node, bind); } + if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { + const propertyAccess = node.expression; + if (isNarrowableReference(propertyAccess.expression) && propertyAccess.name.text === "push") { + currentFlow = createFlowArrayMutation(currentFlow, propertyAccess.expression); + } + } } function getContainerFlags(node: Node): ContainerFlags { diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 887a406bb8c..eff52967544 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -114,6 +114,7 @@ namespace ts { const intersectionTypes = createMap(); const stringLiteralTypes = createMap(); const numericLiteralTypes = createMap(); + const evolvingArrayTypes: AnonymousType[] = []; const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); @@ -175,6 +176,7 @@ namespace ts { let globalBooleanType: ObjectType; let globalRegExpType: ObjectType; let anyArrayType: Type; + let autoArrayType: Type; let anyReadonlyArrayType: Type; // The library files are only loaded when the feature is used. @@ -3051,9 +3053,14 @@ namespace ts { return undefined; } - function isAutoVariableInitializer(initializer: Expression) { - const expr = initializer && skipParentheses(initializer); - return !expr || expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; + function isNullOrUndefined(node: Expression) { + const expr = skipParentheses(node); + return expr.kind === SyntaxKind.NullKeyword || expr.kind === SyntaxKind.Identifier && getResolvedSymbol(expr) === undefinedSymbol; + } + + function isEmptyArrayLiteral(node: Expression) { + const expr = skipParentheses(node); + return expr.kind === SyntaxKind.ArrayLiteralExpression && (expr).elements.length === 0; } function addOptionality(type: Type, optional: boolean): Type { @@ -3094,12 +3101,18 @@ namespace ts { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } - // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer - // or a 'null' or 'undefined' initializer. if (declaration.kind === SyntaxKind.VariableDeclaration && !isBindingPattern(declaration.name) && - !(getCombinedNodeFlags(declaration) & NodeFlags.Const) && !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && - !isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { - return autoType; + !(getCombinedModifierFlags(declaration) & ModifierFlags.Export) && !isInAmbientContext(declaration)) { + // Use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no + // initializer or a 'null' or 'undefined' initializer. + if (!(getCombinedNodeFlags(declaration) & NodeFlags.Const) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) { + return autoType; + } + // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array + // literal initializer. + if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) { + return autoArrayType; + } } if (declaration.kind === SyntaxKind.Parameter) { @@ -8363,6 +8376,11 @@ namespace ts { getAssignedType(node); } + function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { + return node.kind === SyntaxKind.VariableDeclaration && (node).initializer && isEmptyArrayLiteral((node).initializer) || + node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && isEmptyArrayLiteral((node.parent).right); + } + function getReferenceCandidate(node: Expression): Expression { switch (node.kind) { case SyntaxKind.ParenthesizedExpression: @@ -8441,21 +8459,94 @@ namespace ts { return incomplete ? { flags: 0, type } : type; } + // An evolving array type tracks the element types that have so far been seen in an + // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving + // array types are ultimately converted into manifest array types (using getFinalArrayType) + // and never escape the getFlowTypeOfReference function. + function createEvolvingArrayType(elementType: Type): AnonymousType { + const result = createObjectType(TypeFlags.Anonymous); + result.elementType = elementType; + return result; + } + + function getEvolvingArrayType(elementType: Type): AnonymousType { + return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType)); + } + + // When adding evolving array element types we do not perform subtype reduction. Instead, + // we defer subtype reduction until the evolving array type is finalized into a manifest + // array type. + function addEvolvingArrayElementType(evolvingArrayType: AnonymousType, node: Expression): AnonymousType { + const elementType = getBaseTypeOfLiteralType(checkExpression(node)); + return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType])); + } + + function isEvolvingArrayType(type: Type) { + return type.flags & TypeFlags.Anonymous && !!(type).elementType; + } + + // We perform subtype reduction upon obtaining the final array type from an evolving array type. + function getFinalArrayType(evolvingArrayType: AnonymousType): Type { + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createArrayType(getUnionType([evolvingArrayType.elementType], /*subtypeReduction*/ true))); + } + + function finalizeEvolvingArrayType(type: Type): Type { + return isEvolvingArrayType(type) ? getFinalArrayType(type) : type; + } + + function getElementTypeOfEvolvingArrayType(evolvingArrayType: AnonymousType) { + return evolvingArrayType.elementType; + } + + // At flow control branch or loop junctions, if the type along every antecedent code path + // is an evolving array type, we construct a combined evolving array type. Otherwise we + // finalize all evolving array types. + function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) { + return types.length && every(types, isEvolvingArrayType) ? + getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : + getUnionType(map(types, finalizeEvolvingArrayType), subtypeReduction); + } + + // Return true if the given node is 'x' in an 'x.push(value)' operation. + function isPushCallTarget(node: Node) { + return node.parent.kind === SyntaxKind.PropertyAccessExpression && + (node.parent).name.text === "push" && + node.parent.parent.kind === SyntaxKind.CallExpression; + } + + // Return true if the given node is 'x' in an 'x[n] = value' operation, where 'n' is an + // expression of type any, undefined, or a number-like type. + function isElementAssignmentTarget(node: Node) { + const parent = node.parent; + return parent.kind === SyntaxKind.ElementAccessExpression && + (parent).expression === node && + parent.parent.kind === SyntaxKind.BinaryExpression && + (parent.parent).operatorToken.kind === SyntaxKind.EqualsToken && + (parent.parent).left === parent && + !isAssignmentTarget(parent.parent) && + isTypeAnyOrAllConstituentTypesHaveKind(checkExpression((parent).argumentExpression), TypeFlags.NumberLike | TypeFlags.Undefined); + } + function getFlowTypeOfReference(reference: Node, declaredType: Type, assumeInitialized: boolean, flowContainer: Node) { let key: string; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & TypeFlags.Narrowable)) { return declaredType; } const initialType = assumeInitialized ? declaredType : - declaredType === autoType ? undefinedType : + declaredType === autoType || declaredType === autoArrayType ? undefinedType : includeFalsyTypes(declaredType, TypeFlags.Undefined); const visitedFlowStart = visitedFlowCount; - const result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); + const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(result, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { + // When the reference is 'x' in an 'x.push(value)' or 'x[n] = value' operation, we give type + // 'any[]' to 'x' instead of using the type determed by control flow analysis such that new + // element types are not considered errors. + const isEvolvingArrayInferenceTarget = isEvolvingArrayType(evolvedType) && (isPushCallTarget(reference) || isElementAssignmentTarget(reference)); + const resultType = isEvolvingArrayInferenceTarget ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } - return result; + return resultType; function getTypeAtFlowNode(flow: FlowNode): FlowType { while (true) { @@ -8492,6 +8583,13 @@ namespace ts { getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow); } + else if (flow.flags & FlowFlags.ArrayMutation) { + type = getTypeAtFlowArrayMutation(flow); + if (!type) { + flow = (flow).antecedent; + continue; + } + } else if (flow.flags & FlowFlags.Start) { // Check if we should continue with the control flow of the containing function. const container = (flow).container; @@ -8504,8 +8602,8 @@ namespace ts { } else { // Unreachable code errors are reported in the binding phase. Here we - // simply return the declared type to reduce follow-on errors. - type = declaredType; + // simply return the non-auto declared type to reduce follow-on errors. + type = convertAutoToAny(declaredType); } if (flow.flags & FlowFlags.Shared) { // Record visited node and the associated type in the cache. @@ -8526,9 +8624,17 @@ namespace ts { const flowType = getTypeAtFlowNode(flow.antecedent); return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); } - return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : - declaredType.flags & TypeFlags.Union ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (declaredType === autoType || declaredType === autoArrayType) { + if (isEmptyArrayAssignment(node)) { + return getEvolvingArrayType(neverType); + } + const assignedType = getBaseTypeOfLiteralType(getInitialOrAssignedType(node)); + return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType; + } + if (declaredType.flags & TypeFlags.Union) { + return getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)); + } + return declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -8541,24 +8647,51 @@ namespace ts { return undefined; } + function getTypeAtFlowArrayMutation(flow: FlowArrayMutation): FlowType { + const node = flow.node; + if (isMatchingReference(reference, node)) { + const flowType = getTypeAtFlowNode(flow.antecedent); + const type = getTypeFromFlowType(flowType); + if (isEvolvingArrayType(type)) { + const parent = node.parent; + let evolvedType = type; + if (parent.kind === SyntaxKind.PropertyAccessExpression) { + for (const arg of (parent.parent).arguments) { + evolvedType = addEvolvingArrayElementType(evolvedType, arg); + } + } + else if (isTypeAnyOrAllConstituentTypesHaveKind(checkExpression((parent).argumentExpression), TypeFlags.NumberLike)) { + evolvedType = addEvolvingArrayElementType(evolvedType, (parent.parent).right); + } + return evolvedType === type ? flowType : createFlowType(evolvedType, isIncomplete(flowType)); + } + return flowType; + } + return undefined; + } + function getTypeAtFlowCondition(flow: FlowCondition): FlowType { const flowType = getTypeAtFlowNode(flow.antecedent); - let type = getTypeFromFlowType(flowType); - if (!(type.flags & TypeFlags.Never)) { - // If we have an antecedent type (meaning we're reachable in some way), we first - // attempt to narrow the antecedent type. If that produces the never type, and if - // the antecedent type is incomplete (i.e. a transient type in a loop), then we - // take the type guard as an indication that control *could* reach here once we - // have the complete type. We proceed by switching to the silent never type which - // doesn't report errors when operators are applied to it. Note that this is the - // *only* place a silent never type is ever generated. - const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0; - type = narrowType(type, flow.expression, assumeTrue); - if (type.flags & TypeFlags.Never && isIncomplete(flowType)) { - type = silentNeverType; - } + const type = getTypeFromFlowType(flowType); + if (type.flags & TypeFlags.Never) { + return flowType; } - return createFlowType(type, isIncomplete(flowType)); + // If we have an antecedent type (meaning we're reachable in some way), we first + // attempt to narrow the antecedent type. If that produces the never type, and if + // the antecedent type is incomplete (i.e. a transient type in a loop), then we + // take the type guard as an indication that control *could* reach here once we + // have the complete type. We proceed by switching to the silent never type which + // doesn't report errors when operators are applied to it. Note that this is the + // *only* place a silent never type is ever generated. + const assumeTrue = (flow.flags & FlowFlags.TrueCondition) !== 0; + const nonEvolvingType = finalizeEvolvingArrayType(type); + const narrowedType = narrowType(nonEvolvingType, flow.expression, assumeTrue); + if (narrowedType === nonEvolvingType) { + return flowType; + } + const incomplete = isIncomplete(flowType); + const resultType = incomplete && narrowedType.flags & TypeFlags.Never ? silentNeverType : narrowedType; + return createFlowType(resultType, incomplete); } function getTypeAtSwitchClause(flow: FlowSwitchClause): FlowType { @@ -8601,7 +8734,7 @@ namespace ts { seenIncomplete = true; } } - return createFlowType(getUnionType(antecedentTypes, subtypeReduction), seenIncomplete); + return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction), seenIncomplete); } function getTypeAtFlowLoopLabel(flow: FlowLabel): FlowType { @@ -8621,7 +8754,7 @@ namespace ts { // junction is always the non-looping control flow path that leads to the top. for (let i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionType(flowLoopTypes[i]), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -8664,7 +8797,7 @@ namespace ts { } // The result is incomplete if the first antecedent (the non-looping control flow path) // is incomplete. - const result = getUnionType(antecedentTypes, subtypeReduction); + const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction); if (isIncomplete(firstAntecedentType)) { return createFlowType(result, /*incomplete*/ true); } @@ -9143,19 +9276,19 @@ namespace ts { // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). const assumeInitialized = isParameter || isOuterVariable || - type !== autoType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) || + type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & TypeFlags.Any) !== 0) || isInAmbientContext(declaration); const flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (type === autoType) { - if (flowType === autoType) { + if (type === autoType || type === autoArrayType) { + if (flowType === type) { if (compilerOptions.noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); - error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(type)); + error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(type)); } - return anyType; + return convertAutoToAny(type); } } else if (!assumeInitialized && !(getFalsyFlags(type) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) { @@ -15904,7 +16037,7 @@ namespace ts { } function convertAutoToAny(type: Type) { - return type === autoType ? anyType : type; + return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type; } // Check variable, parameter, or property declaration @@ -19307,6 +19440,7 @@ namespace ts { } anyArrayType = createArrayType(anyType); + autoArrayType = createArrayType(autoType); const symbol = getGlobalSymbol("ReadonlyArray", SymbolFlags.Type, /*diagnostic*/ undefined); globalReadonlyArrayType = symbol && getTypeOfGlobalSymbol(symbol, /*arity*/ 1); diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index fe196b29216..7a73b31e1a8 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2953,7 +2953,7 @@ "category": "Error", "code": 7033 }, - "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined.": { + "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined.": { "category": "Error", "code": 7034 }, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index ab48ae543c2..5b34c5bfbf6 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1681,8 +1681,9 @@ namespace ts { TrueCondition = 1 << 5, // Condition known to be true FalseCondition = 1 << 6, // Condition known to be false SwitchClause = 1 << 7, // Switch statement clause - Referenced = 1 << 8, // Referenced as antecedent once - Shared = 1 << 9, // Referenced as antecedent more than once + ArrayMutation = 1 << 8, // Potential array mutation + Referenced = 1 << 9, // Referenced as antecedent once + Shared = 1 << 10, // Referenced as antecedent more than once Label = BranchLabel | LoopLabel, Condition = TrueCondition | FalseCondition } @@ -1725,6 +1726,13 @@ namespace ts { antecedent: FlowNode; } + // FlowArrayMutation represents a node potentially mutates an array, i.e. an + // operation of the form 'x.push(value)' or 'x[n] = value'. + export interface FlowArrayMutation extends FlowNode { + node: Expression; + antecedent: FlowNode; + } + export type FlowType = Type | IncompleteType; // Incomplete types occur during control flow analysis of loops. An IncompleteType @@ -2521,6 +2529,8 @@ namespace ts { export interface AnonymousType extends ObjectType { target?: AnonymousType; // Instantiation target mapper?: TypeMapper; // Instantiation mapper + elementType?: Type; // Element expressions of evolving array type + finalArrayType?: Type; // Final array type of evolving array type } /* @internal */ From b5c10553b5ef29da07d66b5ca0a0e3689dc14790 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 11:05:55 -0700 Subject: [PATCH 04/74] Accept new baselines --- .../reference/arrayLiterals2ES5.types | 8 ++--- .../genericTypeParameterEquivalence2.types | 2 +- .../reference/globalThisCapture.types | 4 +-- .../implicitAnyWidenToAny.errors.txt | 5 +-- .../reference/localClassesInLoop.types | 12 +++---- .../reference/localClassesInLoop_ES6.types | 12 +++---- .../strictNullChecksNoWidening.types | 2 +- tests/baselines/reference/typedArrays.types | 36 +++++++++---------- 8 files changed, 39 insertions(+), 42 deletions(-) diff --git a/tests/baselines/reference/arrayLiterals2ES5.types b/tests/baselines/reference/arrayLiterals2ES5.types index c3256db925e..4c5f895114d 100644 --- a/tests/baselines/reference/arrayLiterals2ES5.types +++ b/tests/baselines/reference/arrayLiterals2ES5.types @@ -193,10 +193,10 @@ var d5 = [...temp3]; >temp3 : any[] var d6 = [...temp4]; ->d6 : any[] ->[...temp4] : any[] ->...temp4 : any ->temp4 : any[] +>d6 : never[] +>[...temp4] : never[] +>...temp4 : never +>temp4 : never[] var d7 = [...[...temp1]]; >d7 : number[] diff --git a/tests/baselines/reference/genericTypeParameterEquivalence2.types b/tests/baselines/reference/genericTypeParameterEquivalence2.types index 6ab297fe32c..095ce27c752 100644 --- a/tests/baselines/reference/genericTypeParameterEquivalence2.types +++ b/tests/baselines/reference/genericTypeParameterEquivalence2.types @@ -105,7 +105,7 @@ function filter(f: (a: A) => boolean, ar: A[]): A[] { } ); return ret; ->ret : any[] +>ret : never[] } // length :: [a] -> Num diff --git a/tests/baselines/reference/globalThisCapture.types b/tests/baselines/reference/globalThisCapture.types index 063100ff78e..92a20ff930e 100644 --- a/tests/baselines/reference/globalThisCapture.types +++ b/tests/baselines/reference/globalThisCapture.types @@ -13,7 +13,7 @@ var parts = []; // Ensure that the generated code is correct parts[0]; ->parts[0] : any ->parts : any[] +>parts[0] : never +>parts : never[] >0 : 0 diff --git a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt index 95739a450a8..7a9314d982f 100644 --- a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt +++ b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt @@ -1,8 +1,7 @@ tests/cases/compiler/implicitAnyWidenToAny.ts(4,5): error TS7005: Variable 'widenArray' implicitly has an 'any[]' type. -tests/cases/compiler/implicitAnyWidenToAny.ts(5,5): error TS7005: Variable 'emptyArray' implicitly has an 'any[]' type. -==== tests/cases/compiler/implicitAnyWidenToAny.ts (2 errors) ==== +==== tests/cases/compiler/implicitAnyWidenToAny.ts (1 errors) ==== // these should be errors var x = null; // error at "x" var x1 = undefined; // error at "x1" @@ -10,8 +9,6 @@ tests/cases/compiler/implicitAnyWidenToAny.ts(5,5): error TS7005: Variable 'empt ~~~~~~~~~~ !!! error TS7005: Variable 'widenArray' implicitly has an 'any[]' type. var emptyArray = []; // error at "emptyArray" - ~~~~~~~~~~ -!!! error TS7005: Variable 'emptyArray' implicitly has an 'any[]' type. // these should not be error class AnimalObj { diff --git a/tests/baselines/reference/localClassesInLoop.types b/tests/baselines/reference/localClassesInLoop.types index c88bfc0435d..88050445898 100644 --- a/tests/baselines/reference/localClassesInLoop.types +++ b/tests/baselines/reference/localClassesInLoop.types @@ -35,12 +35,12 @@ use(data[0]() === data[1]()); >use(data[0]() === data[1]()) : any >use : (a: any) => any >data[0]() === data[1]() : boolean ->data[0]() : any ->data[0] : any ->data : any[] +>data[0]() : typeof C +>data[0] : () => typeof C +>data : (() => typeof C)[] >0 : 0 ->data[1]() : any ->data[1] : any ->data : any[] +>data[1]() : typeof C +>data[1] : () => typeof C +>data : (() => typeof C)[] >1 : 1 diff --git a/tests/baselines/reference/localClassesInLoop_ES6.types b/tests/baselines/reference/localClassesInLoop_ES6.types index 9d487f6c600..390f4b8b1dd 100644 --- a/tests/baselines/reference/localClassesInLoop_ES6.types +++ b/tests/baselines/reference/localClassesInLoop_ES6.types @@ -36,12 +36,12 @@ use(data[0]() === data[1]()); >use(data[0]() === data[1]()) : any >use : (a: any) => any >data[0]() === data[1]() : boolean ->data[0]() : any ->data[0] : any ->data : any[] +>data[0]() : typeof C +>data[0] : () => typeof C +>data : (() => typeof C)[] >0 : 0 ->data[1]() : any ->data[1] : any ->data : any[] +>data[1]() : typeof C +>data[1] : () => typeof C +>data : (() => typeof C)[] >1 : 1 diff --git a/tests/baselines/reference/strictNullChecksNoWidening.types b/tests/baselines/reference/strictNullChecksNoWidening.types index 375977ae375..e24797850ee 100644 --- a/tests/baselines/reference/strictNullChecksNoWidening.types +++ b/tests/baselines/reference/strictNullChecksNoWidening.types @@ -14,7 +14,7 @@ var a3 = void 0; >0 : 0 var b1 = []; ->b1 : never[] +>b1 : any[] >[] : never[] var b2 = [,]; diff --git a/tests/baselines/reference/typedArrays.types b/tests/baselines/reference/typedArrays.types index 444d6a74e43..cd2103f6461 100644 --- a/tests/baselines/reference/typedArrays.types +++ b/tests/baselines/reference/typedArrays.types @@ -1,7 +1,7 @@ === tests/cases/compiler/typedArrays.ts === function CreateTypedArrayTypes() { ->CreateTypedArrayTypes : () => any[] +>CreateTypedArrayTypes : () => (Int8ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor | Uint8ClampedArrayConstructor)[] var typedArrays = []; >typedArrays : any[] @@ -71,11 +71,11 @@ function CreateTypedArrayTypes() { >Uint8ClampedArray : Uint8ClampedArrayConstructor return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8ArrayConstructor | Uint8ArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor | Uint8ClampedArrayConstructor)[] } function CreateTypedArrayInstancesFromLength(obj: number) { ->CreateTypedArrayInstancesFromLength : (obj: number) => any[] +>CreateTypedArrayInstancesFromLength : (obj: number) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : number var typedArrays = []; @@ -164,11 +164,11 @@ function CreateTypedArrayInstancesFromLength(obj: number) { >obj : number return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateTypedArrayInstancesFromArray(obj: number[]) { ->CreateTypedArrayInstancesFromArray : (obj: number[]) => any[] +>CreateTypedArrayInstancesFromArray : (obj: number[]) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : number[] var typedArrays = []; @@ -257,11 +257,11 @@ function CreateTypedArrayInstancesFromArray(obj: number[]) { >obj : number[] return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateIntegerTypedArraysFromArray2(obj:number[]) { ->CreateIntegerTypedArraysFromArray2 : (obj: number[]) => any[] +>CreateIntegerTypedArraysFromArray2 : (obj: number[]) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : number[] var typedArrays = []; @@ -368,11 +368,11 @@ function CreateIntegerTypedArraysFromArray2(obj:number[]) { >obj : number[] return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateIntegerTypedArraysFromArrayLike(obj:ArrayLike) { ->CreateIntegerTypedArraysFromArrayLike : (obj: ArrayLike) => any[] +>CreateIntegerTypedArraysFromArrayLike : (obj: ArrayLike) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : ArrayLike >ArrayLike : ArrayLike @@ -480,11 +480,11 @@ function CreateIntegerTypedArraysFromArrayLike(obj:ArrayLike) { >obj : ArrayLike return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateTypedArraysOf(obj) { ->CreateTypedArraysOf : (obj: any) => any[] +>CreateTypedArraysOf : (obj: any) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : any var typedArrays = []; @@ -600,11 +600,11 @@ function CreateTypedArraysOf(obj) { >obj : any return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateTypedArraysOf2() { ->CreateTypedArraysOf2 : () => any[] +>CreateTypedArraysOf2 : () => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] var typedArrays = []; >typedArrays : any[] @@ -737,11 +737,11 @@ function CreateTypedArraysOf2() { >4 : 4 return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateTypedArraysFromMapFn(obj:ArrayLike, mapFn: (n:number, v:number)=> number) { ->CreateTypedArraysFromMapFn : (obj: ArrayLike, mapFn: (n: number, v: number) => number) => any[] +>CreateTypedArraysFromMapFn : (obj: ArrayLike, mapFn: (n: number, v: number) => number) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : ArrayLike >ArrayLike : ArrayLike >mapFn : (n: number, v: number) => number @@ -861,11 +861,11 @@ function CreateTypedArraysFromMapFn(obj:ArrayLike, mapFn: (n:number, v:n >mapFn : (n: number, v: number) => number return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } function CreateTypedArraysFromThisObj(obj:ArrayLike, mapFn: (n:number, v:number)=> number, thisArg: {}) { ->CreateTypedArraysFromThisObj : (obj: ArrayLike, mapFn: (n: number, v: number) => number, thisArg: {}) => any[] +>CreateTypedArraysFromThisObj : (obj: ArrayLike, mapFn: (n: number, v: number) => number, thisArg: {}) => (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] >obj : ArrayLike >ArrayLike : ArrayLike >mapFn : (n: number, v: number) => number @@ -995,5 +995,5 @@ function CreateTypedArraysFromThisObj(obj:ArrayLike, mapFn: (n:number, v >thisArg : {} return typedArrays; ->typedArrays : any[] +>typedArrays : (Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array)[] } From 9c4190b1fb31b6317efc15430c2047ca78779ff0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 13:25:42 -0700 Subject: [PATCH 05/74] Introduce sameMap function --- src/compiler/checker.ts | 26 ++++++++++++++++---------- src/compiler/core.ts | 24 ++++++++++++++++++++++-- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eff52967544..414a92ffed4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7404,7 +7404,7 @@ namespace ts { type.flags & TypeFlags.NumberLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getBaseTypeOfLiteralType)) : + type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getBaseTypeOfLiteralType)) : type; } @@ -7413,7 +7413,7 @@ namespace ts { type.flags & TypeFlags.NumberLiteral && type.flags & TypeFlags.FreshLiteral ? numberType : type.flags & TypeFlags.BooleanLiteral ? booleanType : type.flags & TypeFlags.EnumLiteral ? (type).baseType : - type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(map((type).types, getWidenedLiteralType)) : + type.flags & TypeFlags.Union && !(type.flags & TypeFlags.Enum) ? getUnionType(sameMap((type).types, getWidenedLiteralType)) : type; } @@ -7552,10 +7552,10 @@ namespace ts { return getWidenedTypeOfObjectLiteral(type); } if (type.flags & TypeFlags.Union) { - return getUnionType(map((type).types, getWidenedConstituentType)); + return getUnionType(sameMap((type).types, getWidenedConstituentType)); } if (isArrayType(type) || isTupleType(type)) { - return createTypeReference((type).target, map((type).typeArguments, getWidenedType)); + return createTypeReference((type).target, sameMap((type).typeArguments, getWidenedType)); } } return type; @@ -7973,7 +7973,7 @@ namespace ts { const widenLiteralTypes = context.inferences[index].topLevel && !hasPrimitiveConstraint(signature.typeParameters[index]) && (context.inferences[index].isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), signature.typeParameters[index])); - const baseInferences = widenLiteralTypes ? map(inferences, getWidenedLiteralType) : inferences; + const baseInferences = widenLiteralTypes ? sameMap(inferences, getWidenedLiteralType) : inferences; // Infer widened union or supertype, or the unknown type for no common supertype const unionOrSuperType = context.inferUnionTypes ? getUnionType(baseInferences, /*subtypeReduction*/ true) : getCommonSupertype(baseInferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; @@ -8485,9 +8485,15 @@ namespace ts { return type.flags & TypeFlags.Anonymous && !!(type).elementType; } + function createFinalArrayType(elementType: Type) { + return createArrayType(elementType !== neverType ? + getUnionType([elementType], /*subtypeReduction*/ true) : + strictNullChecks ? neverType : undefinedWideningType); + } + // We perform subtype reduction upon obtaining the final array type from an evolving array type. function getFinalArrayType(evolvingArrayType: AnonymousType): Type { - return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createArrayType(getUnionType([evolvingArrayType.elementType], /*subtypeReduction*/ true))); + return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType)); } function finalizeEvolvingArrayType(type: Type): Type { @@ -8504,7 +8510,7 @@ namespace ts { function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) { return types.length && every(types, isEvolvingArrayType) ? getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : - getUnionType(map(types, finalizeEvolvingArrayType), subtypeReduction); + getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); } // Return true if the given node is 'x' in an 'x.push(value)' operation. @@ -8754,7 +8760,7 @@ namespace ts { // junction is always the non-looping control flow path that leads to the top. for (let i = flowLoopStart; i < flowLoopCount; i++) { if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { - return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], false), /*incomplete*/ true); + return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } // Add the flow loop junction and reference to the in-process stack and analyze @@ -10728,7 +10734,7 @@ namespace ts { } } - return getUnionType(signatures.map(getReturnTypeOfSignature), /*subtypeReduction*/ true); + return getUnionType(map(signatures, getReturnTypeOfSignature), /*subtypeReduction*/ true); } /// e.g. "props" for React.d.ts, @@ -10778,7 +10784,7 @@ namespace ts { } if (elemType.flags & TypeFlags.Union) { const types = (elemType).types; - return getUnionType(types.map(type => { + return getUnionType(map(types, type => { return getResolvedJsxType(node, type, elemClassType); }), /*subtypeReduction*/ true); } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 72d05e1cfd7..bb3aaf23259 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -257,13 +257,33 @@ namespace ts { if (array) { result = []; for (let i = 0; i < array.length; i++) { - const v = array[i]; - result.push(f(v, i)); + result.push(f(array[i], i)); } } return result; } + // Maps from T to T and avoids allocation of all elements map to themselves + export function sameMap(array: T[], f: (x: T, i: number) => T): T[] { + let result: T[]; + if (array) { + for (let i = 0; i < array.length; i++) { + if (result) { + result.push(f(array[i], i)); + } + else { + const item = array[i]; + const mapped = f(item, i); + if (item !== mapped) { + result = array.slice(0, i); + result.push(mapped); + } + } + } + } + return result || array; + } + /** * Flattens an array containing a mix of array or non-array elements. * From 144f4ffc7c836834947ecb6541225a47aa8e1af8 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 13:33:13 -0700 Subject: [PATCH 06/74] Accept new baselines --- tests/baselines/reference/arrayLiterals2ES5.types | 8 ++++---- .../reference/genericTypeParameterEquivalence2.types | 2 +- tests/baselines/reference/globalThisCapture.types | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/baselines/reference/arrayLiterals2ES5.types b/tests/baselines/reference/arrayLiterals2ES5.types index 4c5f895114d..833966a6e48 100644 --- a/tests/baselines/reference/arrayLiterals2ES5.types +++ b/tests/baselines/reference/arrayLiterals2ES5.types @@ -193,10 +193,10 @@ var d5 = [...temp3]; >temp3 : any[] var d6 = [...temp4]; ->d6 : never[] ->[...temp4] : never[] ->...temp4 : never ->temp4 : never[] +>d6 : any[] +>[...temp4] : undefined[] +>...temp4 : undefined +>temp4 : undefined[] var d7 = [...[...temp1]]; >d7 : number[] diff --git a/tests/baselines/reference/genericTypeParameterEquivalence2.types b/tests/baselines/reference/genericTypeParameterEquivalence2.types index 095ce27c752..51253764578 100644 --- a/tests/baselines/reference/genericTypeParameterEquivalence2.types +++ b/tests/baselines/reference/genericTypeParameterEquivalence2.types @@ -105,7 +105,7 @@ function filter(f: (a: A) => boolean, ar: A[]): A[] { } ); return ret; ->ret : never[] +>ret : undefined[] } // length :: [a] -> Num diff --git a/tests/baselines/reference/globalThisCapture.types b/tests/baselines/reference/globalThisCapture.types index 92a20ff930e..d17c899d1ed 100644 --- a/tests/baselines/reference/globalThisCapture.types +++ b/tests/baselines/reference/globalThisCapture.types @@ -13,7 +13,7 @@ var parts = []; // Ensure that the generated code is correct parts[0]; ->parts[0] : never ->parts : never[] +>parts[0] : undefined +>parts : undefined[] >0 : 0 From a9c2b23df52a2abaffae4ba1470ee87e05aae731 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 13:33:28 -0700 Subject: [PATCH 07/74] Add tests --- .../cases/compiler/controlFlowArrayErrors.ts | 59 ++++++++ tests/cases/compiler/controlFlowArrays.ts | 141 ++++++++++++++++++ 2 files changed, 200 insertions(+) create mode 100644 tests/cases/compiler/controlFlowArrayErrors.ts create mode 100644 tests/cases/compiler/controlFlowArrays.ts diff --git a/tests/cases/compiler/controlFlowArrayErrors.ts b/tests/cases/compiler/controlFlowArrayErrors.ts new file mode 100644 index 00000000000..84da65c41dc --- /dev/null +++ b/tests/cases/compiler/controlFlowArrayErrors.ts @@ -0,0 +1,59 @@ +// @noImplicitAny: true + +declare function cond(): boolean; + +function f1() { + let x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f2() { + let x; + x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f3() { + let x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} + +function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} + +function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} \ No newline at end of file diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts new file mode 100644 index 00000000000..d5eaa9c4320 --- /dev/null +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -0,0 +1,141 @@ +// @strictNullChecks: true +// @noImplicitAny: true + +declare function cond(): boolean; + +function f1() { + let x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} + +function f2() { + let x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f3() { + let x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} + +function f4() { + let x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} + +function f5() { + let x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} + +function f6() { + let x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} + +function f7() { + let x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} + +function f8() { + let x = []; + x.push(5); + if (cond()) return x; // number[] + x.push("hello"); + if (cond()) return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} + +function f9() { + let x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} + +function f10() { + let x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} + +function f11() { + let x = []; + return x; // never[] +} + +function f12() { + let x; + x = []; + return x; // never[] +} + +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f14() { + const x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} \ No newline at end of file From c0c2271d31a361528deebe88e91539c2635ccbf9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 13:35:02 -0700 Subject: [PATCH 08/74] Accept new baselines --- .../controlFlowArrayErrors.errors.txt | 85 ++++ .../reference/controlFlowArrayErrors.js | 110 +++++ .../baselines/reference/controlFlowArrays.js | 267 +++++++++++ .../reference/controlFlowArrays.symbols | 350 ++++++++++++++ .../reference/controlFlowArrays.types | 447 ++++++++++++++++++ 5 files changed, 1259 insertions(+) create mode 100644 tests/baselines/reference/controlFlowArrayErrors.errors.txt create mode 100644 tests/baselines/reference/controlFlowArrayErrors.js create mode 100644 tests/baselines/reference/controlFlowArrays.js create mode 100644 tests/baselines/reference/controlFlowArrays.symbols create mode 100644 tests/baselines/reference/controlFlowArrays.types diff --git a/tests/baselines/reference/controlFlowArrayErrors.errors.txt b/tests/baselines/reference/controlFlowArrayErrors.errors.txt new file mode 100644 index 00000000000..7475c273243 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrayErrors.errors.txt @@ -0,0 +1,85 @@ +tests/cases/compiler/controlFlowArrayErrors.ts(6,9): error TS7005: Variable 'y' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(14,9): error TS7005: Variable 'y' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(20,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(23,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(30,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. +tests/cases/compiler/controlFlowArrayErrors.ts(35,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. +tests/cases/compiler/controlFlowArrayErrors.ts(49,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: (string | number)[]) => number) | ((...items: boolean[]) => number)' has no compatible call signatures. +tests/cases/compiler/controlFlowArrayErrors.ts(57,12): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. + + +==== tests/cases/compiler/controlFlowArrayErrors.ts (8 errors) ==== + + declare function cond(): boolean; + + function f1() { + let x = []; + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'y' implicitly has an 'any[]' type. + x.push(5); + let z = x; + } + + function f2() { + let x; + x = []; + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'y' implicitly has an 'any[]' type. + x.push(5); + let z = x; + } + + function f3() { + let x = []; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x.push(5); + function g() { + x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + } + } + + function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error + ~~~~ +!!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. + } + + function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error + ~~~~ +!!! error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. + } + + function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error + ~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: (string | number)[]) => number) | ((...items: boolean[]) => number)' has no compatible call signatures. + } + + function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error + ~~~~~~~ +!!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. + } \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowArrayErrors.js b/tests/baselines/reference/controlFlowArrayErrors.js new file mode 100644 index 00000000000..c1589449334 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrayErrors.js @@ -0,0 +1,110 @@ +//// [controlFlowArrayErrors.ts] + +declare function cond(): boolean; + +function f1() { + let x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f2() { + let x; + x = []; + let y = x; // Implicit any[] error + x.push(5); + let z = x; +} + +function f3() { + let x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} + +function f4() { + let x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f5() { + let x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} + +function f6() { + let x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} + +function f7() { + let x = []; // x has evolving array value + x.push(5); + let y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} + +//// [controlFlowArrayErrors.js] +function f1() { + var x = []; + var y = x; // Implicit any[] error + x.push(5); + var z = x; +} +function f2() { + var x; + x = []; + var y = x; // Implicit any[] error + x.push(5); + var z = x; +} +function f3() { + var x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} +function f4() { + var x; + x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} +function f5() { + var x = [5, "hello"]; // Non-evolving array + x.push(true); // Error +} +function f6() { + var x; + if (cond()) { + x = []; + x.push(5); + x.push("hello"); + } + else { + x = [true]; // Non-evolving array + } + x; // boolean[] | (string | number)[] + x.push(99); // Error +} +function f7() { + var x = []; // x has evolving array value + x.push(5); + var y = x; // y has non-evolving array value + x.push("hello"); // Ok + y.push("hello"); // Error +} diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js new file mode 100644 index 00000000000..26885aecd8b --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.js @@ -0,0 +1,267 @@ +//// [controlFlowArrays.ts] + +declare function cond(): boolean; + +function f1() { + let x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} + +function f2() { + let x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f3() { + let x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} + +function f4() { + let x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} + +function f5() { + let x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} + +function f6() { + let x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} + +function f7() { + let x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} + +function f8() { + let x = []; + x.push(5); + if (cond()) return x; // number[] + x.push("hello"); + if (cond()) return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} + +function f9() { + let x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} + +function f10() { + let x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} + +function f11() { + let x = []; + return x; // never[] +} + +function f12() { + let x; + x = []; + return x; // never[] +} + +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +function f14() { + const x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} + +//// [controlFlowArrays.js] +function f1() { + var x = []; + x[0] = 5; + x[1] = "hello"; + x[2] = true; + return x; // (string | number | boolean)[] +} +function f2() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} +function f3() { + var x; + x = []; + x.push(5, "hello"); + return x; // (string | number)[] +} +function f4() { + var x = []; + if (cond()) { + x.push(5); + } + else { + x.push("hello"); + } + return x; // (string | number)[] +} +function f5() { + var x; + if (cond()) { + x = []; + x.push(5); + } + else { + x = []; + x.push("hello"); + } + return x; // (string | number)[] +} +function f6() { + var x; + if (cond()) { + x = 5; + } + else { + x = []; + x.push("hello"); + } + return x; // number | string[] +} +function f7() { + var x = null; + if (cond()) { + x = []; + while (cond()) { + x.push("hello"); + } + } + return x; // string[] | null +} +function f8() { + var x = []; + x.push(5); + if (cond()) + return x; // number[] + x.push("hello"); + if (cond()) + return x; // (string | number)[] + x.push(true); + return x; // (string | number | boolean)[] +} +function f9() { + var x = []; + if (cond()) { + x.push(5); + return x; // number[] + } + else { + x.push("hello"); + return x; // string[] + } +} +function f10() { + var x = []; + if (cond()) { + x.push(true); + x; // boolean[] + } + else { + x.push(5); + x; // number[] + while (cond()) { + x.push("hello"); + } + x; // (string | number)[] + } + x.push(99); + return x; // (string | number | boolean)[] +} +function f11() { + var x = []; + return x; // never[] +} +function f12() { + var x; + x = []; + return x; // never[] +} +function f13() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} +function f14() { + var x = []; + x.push(5); + x.push("hello"); + x.push(true); + return x; // (string | number | boolean)[] +} diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols new file mode 100644 index 00000000000..5b5ef7f8506 --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -0,0 +1,350 @@ +=== tests/cases/compiler/controlFlowArrays.ts === + +declare function cond(): boolean; +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + +function f1() { +>f1 : Symbol(f1, Decl(controlFlowArrays.ts, 1, 33)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[0] = 5; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[1] = "hello"; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + x[2] = true; +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 4, 7)) +} + +function f2() { +>f2 : Symbol(f2, Decl(controlFlowArrays.ts, 9, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 12, 7)) +} + +function f3() { +>f3 : Symbol(f3, Decl(controlFlowArrays.ts, 17, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) + + x.push(5, "hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 20, 7)) +} + +function f4() { +>f4 : Symbol(f4, Decl(controlFlowArrays.ts, 24, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + else { + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 27, 7)) +} + +function f5() { +>f5 : Symbol(f5, Decl(controlFlowArrays.ts, 35, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + else { + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 38, 7)) +} + +function f6() { +>f6 : Symbol(f6, Decl(controlFlowArrays.ts, 48, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = 5; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + } + else { + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // number | string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 51, 7)) +} + +function f7() { +>f7 : Symbol(f7, Decl(controlFlowArrays.ts, 60, 1)) + + let x = null; +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + } + return x; // string[] | null +>x : Symbol(x, Decl(controlFlowArrays.ts, 63, 7)) +} + +function f8() { +>f8 : Symbol(f8, Decl(controlFlowArrays.ts, 71, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + if (cond()) return x; // number[] +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + if (cond()) return x; // (string | number)[] +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 74, 7)) +} + +function f9() { +>f9 : Symbol(f9, Decl(controlFlowArrays.ts, 81, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // number[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + } + else { + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 84, 7)) + } +} + +function f10() { +>f10 : Symbol(f10, Decl(controlFlowArrays.ts, 93, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + + if (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x; // boolean[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + } + else { + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x; // number[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + x; // (string | number)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) + } + x.push(99); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 96, 7)) +} + +function f11() { +>f11 : Symbol(f11, Decl(controlFlowArrays.ts, 111, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) + + return x; // never[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +} + +function f12() { +>f12 : Symbol(f12, Decl(controlFlowArrays.ts, 116, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) + + x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) + + return x; // never[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) +} + +function f13() { +>f13 : Symbol(f13, Decl(controlFlowArrays.ts, 122, 1)) + + var x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +} + +function f14() { +>f14 : Symbol(f14, Decl(controlFlowArrays.ts, 130, 1)) + + const x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.push(true); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +} diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types new file mode 100644 index 00000000000..7b36e4067fa --- /dev/null +++ b/tests/baselines/reference/controlFlowArrays.types @@ -0,0 +1,447 @@ +=== tests/cases/compiler/controlFlowArrays.ts === + +declare function cond(): boolean; +>cond : () => boolean + +function f1() { +>f1 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x[0] = 5; +>x[0] = 5 : 5 +>x[0] : any +>x : any[] +>0 : 0 +>5 : 5 + + x[1] = "hello"; +>x[1] = "hello" : "hello" +>x[1] : any +>x : any[] +>1 : 1 +>"hello" : "hello" + + x[2] = true; +>x[2] = true : true +>x[2] : any +>x : any[] +>2 : 2 +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f2() { +>f2 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f3() { +>f3 : () => (string | number)[] + + let x; +>x : any + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push(5, "hello"); +>x.push(5, "hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 +>"hello" : "hello" + + return x; // (string | number)[] +>x : (string | number)[] +} + +function f4() { +>f4 : () => (string | number)[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + } + else { + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // (string | number)[] +>x : (string | number)[] +} + +function f5() { +>f5 : () => (string | number)[] + + let x; +>x : any + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + } + else { + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // (string | number)[] +>x : (string | number)[] +} + +function f6() { +>f6 : () => number | string[] + + let x; +>x : any + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = 5; +>x = 5 : 5 +>x : any +>5 : 5 + } + else { + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // number | string[] +>x : number | string[] +} + +function f7() { +>f7 : () => string[] | null + + let x = null; +>x : any +>null : null + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + } + return x; // string[] | null +>x : string[] | null +} + +function f8() { +>f8 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + if (cond()) return x; // number[] +>cond() : boolean +>cond : () => boolean +>x : number[] + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + if (cond()) return x; // (string | number)[] +>cond() : boolean +>cond : () => boolean +>x : (string | number)[] + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f9() { +>f9 : () => string[] | number[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + return x; // number[] +>x : number[] + } + else { + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + return x; // string[] +>x : string[] + } +} + +function f10() { +>f10 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + if (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + x; // boolean[] +>x : boolean[] + } + else { + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x; // number[] +>x : number[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + x; // (string | number)[] +>x : (string | number)[] + } + x.push(99); +>x.push(99) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>99 : 99 + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f11() { +>f11 : () => never[] + + let x = []; +>x : any[] +>[] : never[] + + return x; // never[] +>x : never[] +} + +function f12() { +>f12 : () => never[] + + let x; +>x : any + + x = []; +>x = [] : never[] +>x : any +>[] : never[] + + return x; // never[] +>x : never[] +} + +function f13() { +>f13 : () => (string | number | boolean)[] + + var x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f14() { +>f14 : () => (string | number | boolean)[] + + const x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + + x.push(true); +>x.push(true) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} From 12906a74dec4337b55a8be37dc8b29cdd84fea2a Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 16:55:08 -0700 Subject: [PATCH 09/74] Fix some minor issues --- src/compiler/checker.ts | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f95ff1ccfec..0a606afe69f 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8510,12 +8510,12 @@ namespace ts { } function isEvolvingArrayType(type: Type) { - return type.flags & TypeFlags.Anonymous && !!(type).elementType; + return !!(type.flags & TypeFlags.Anonymous && (type).elementType); } function createFinalArrayType(elementType: Type) { return createArrayType(elementType !== neverType ? - getUnionType([elementType], /*subtypeReduction*/ true) : + elementType.flags & TypeFlags.Union ? getUnionType((elementType).types, /*subtypeReduction*/ true) : elementType : strictNullChecks ? neverType : undefinedWideningType); } @@ -8528,16 +8528,29 @@ namespace ts { return isEvolvingArrayType(type) ? getFinalArrayType(type) : type; } - function getElementTypeOfEvolvingArrayType(evolvingArrayType: AnonymousType) { - return evolvingArrayType.elementType; + function getElementTypeOfEvolvingArrayType(type: Type) { + return isEvolvingArrayType(type) ? (type).elementType : neverType; + } + + function isEvolvingArrayTypeList(types: Type[]) { + let hasEvolvingArrayType = false; + for (const t of types) { + if (!(t.flags & TypeFlags.Never)) { + if (!isEvolvingArrayType(t)) { + return false; + } + hasEvolvingArrayType = true; + } + } + return hasEvolvingArrayType; } // At flow control branch or loop junctions, if the type along every antecedent code path // is an evolving array type, we construct a combined evolving array type. Otherwise we // finalize all evolving array types. function getUnionOrEvolvingArrayType(types: Type[], subtypeReduction: boolean) { - return types.length && every(types, isEvolvingArrayType) ? - getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : + return isEvolvingArrayTypeList(types) ? + getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType))) : getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); } @@ -9211,6 +9224,10 @@ namespace ts { } } + function isConstVariable(symbol: Symbol) { + return symbol.flags & SymbolFlags.Variable && (getDeclarationNodeFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType; + } + function checkIdentifier(node: Identifier): Type { const symbol = getResolvedSymbol(node); @@ -9303,7 +9320,7 @@ namespace ts { // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && (flowContainer.kind === SyntaxKind.FunctionExpression || flowContainer.kind === SyntaxKind.ArrowFunction) && - (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { + (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze From 2f5af2e04b995873b89fb3cc8744fbdfa36a1a8f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 6 Oct 2016 17:02:33 -0700 Subject: [PATCH 10/74] Add additional test --- .../reference/controlFlowArrayErrors.errors.txt | 16 +++++++++++++++- .../reference/controlFlowArrayErrors.js | 15 +++++++++++++++ tests/cases/compiler/controlFlowArrayErrors.ts | 8 ++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/tests/baselines/reference/controlFlowArrayErrors.errors.txt b/tests/baselines/reference/controlFlowArrayErrors.errors.txt index 7475c273243..bc13de261e2 100644 --- a/tests/baselines/reference/controlFlowArrayErrors.errors.txt +++ b/tests/baselines/reference/controlFlowArrayErrors.errors.txt @@ -6,9 +6,11 @@ tests/cases/compiler/controlFlowArrayErrors.ts(30,12): error TS2345: Argument of tests/cases/compiler/controlFlowArrayErrors.ts(35,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. tests/cases/compiler/controlFlowArrayErrors.ts(49,5): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((...items: (string | number)[]) => number) | ((...items: boolean[]) => number)' has no compatible call signatures. tests/cases/compiler/controlFlowArrayErrors.ts(57,12): error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. +tests/cases/compiler/controlFlowArrayErrors.ts(61,11): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(64,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. -==== tests/cases/compiler/controlFlowArrayErrors.ts (8 errors) ==== +==== tests/cases/compiler/controlFlowArrayErrors.ts (10 errors) ==== declare function cond(): boolean; @@ -82,4 +84,16 @@ tests/cases/compiler/controlFlowArrayErrors.ts(57,12): error TS2345: Argument of y.push("hello"); // Error ~~~~~~~ !!! error TS2345: Argument of type '"hello"' is not assignable to parameter of type 'number'. + } + + function f8() { + const x = []; // Implicit any[] error in some locations + ~ +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x.push(5); + function g() { + x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. + } } \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowArrayErrors.js b/tests/baselines/reference/controlFlowArrayErrors.js index c1589449334..538addc31c0 100644 --- a/tests/baselines/reference/controlFlowArrayErrors.js +++ b/tests/baselines/reference/controlFlowArrayErrors.js @@ -56,6 +56,14 @@ function f7() { let y = x; // y has non-evolving array value x.push("hello"); // Ok y.push("hello"); // Error +} + +function f8() { + const x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } } //// [controlFlowArrayErrors.js] @@ -108,3 +116,10 @@ function f7() { x.push("hello"); // Ok y.push("hello"); // Error } +function f8() { + var x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } +} diff --git a/tests/cases/compiler/controlFlowArrayErrors.ts b/tests/cases/compiler/controlFlowArrayErrors.ts index 84da65c41dc..aab3a974cd8 100644 --- a/tests/cases/compiler/controlFlowArrayErrors.ts +++ b/tests/cases/compiler/controlFlowArrayErrors.ts @@ -56,4 +56,12 @@ function f7() { let y = x; // y has non-evolving array value x.push("hello"); // Ok y.push("hello"); // Error +} + +function f8() { + const x = []; // Implicit any[] error in some locations + x.push(5); + function g() { + x; // Implicit any[] error + } } \ No newline at end of file From d543028226e0e8442fd01153f4393b10f829c3b0 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 6 Oct 2016 13:27:18 -0700 Subject: [PATCH 11/74] Add test case for narrowed const in object literal and class expression method --- .../narrowedConstInMethod.errors.txt | 27 +++++++++++++ .../reference/narrowedConstInMethod.js | 40 +++++++++++++++++++ tests/cases/compiler/narrowedConstInMethod.ts | 19 +++++++++ 3 files changed, 86 insertions(+) create mode 100644 tests/baselines/reference/narrowedConstInMethod.errors.txt create mode 100644 tests/baselines/reference/narrowedConstInMethod.js create mode 100644 tests/cases/compiler/narrowedConstInMethod.ts diff --git a/tests/baselines/reference/narrowedConstInMethod.errors.txt b/tests/baselines/reference/narrowedConstInMethod.errors.txt new file mode 100644 index 00000000000..ebb85218a5b --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.errors.txt @@ -0,0 +1,27 @@ +tests/cases/compiler/narrowedConstInMethod.ts(6,28): error TS2531: Object is possibly 'null'. +tests/cases/compiler/narrowedConstInMethod.ts(15,28): error TS2531: Object is possibly 'null'. + + +==== tests/cases/compiler/narrowedConstInMethod.ts (2 errors) ==== + + function f() { + const x: string | null = {}; + if (x !== null) { + return { + bar() { return x.length; } // Error: possibly null x + ~ +!!! error TS2531: Object is possibly 'null'. + }; + } + } + + function f2() { + const x: string | null = {}; + if (x !== null) { + return class { + bar() { return x.length; } // Error: possibly null x + ~ +!!! error TS2531: Object is possibly 'null'. + }; + } + } \ No newline at end of file diff --git a/tests/baselines/reference/narrowedConstInMethod.js b/tests/baselines/reference/narrowedConstInMethod.js new file mode 100644 index 00000000000..f4cdc3def91 --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.js @@ -0,0 +1,40 @@ +//// [narrowedConstInMethod.ts] + +function f() { + const x: string | null = {}; + if (x !== null) { + return { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +function f2() { + const x: string | null = {}; + if (x !== null) { + return class { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +//// [narrowedConstInMethod.js] +function f() { + var x = {}; + if (x !== null) { + return { + bar: function () { return x.length; } // Error: possibly null x + }; + } +} +function f2() { + var x = {}; + if (x !== null) { + return (function () { + function class_1() { + } + class_1.prototype.bar = function () { return x.length; }; // Error: possibly null x + return class_1; + }()); + } +} diff --git a/tests/cases/compiler/narrowedConstInMethod.ts b/tests/cases/compiler/narrowedConstInMethod.ts new file mode 100644 index 00000000000..3ddf97a8df3 --- /dev/null +++ b/tests/cases/compiler/narrowedConstInMethod.ts @@ -0,0 +1,19 @@ +// @strictNullChecks: true + +function f() { + const x: string | null = {}; + if (x !== null) { + return { + bar() { return x.length; } // Error: possibly null x + }; + } +} + +function f2() { + const x: string | null = {}; + if (x !== null) { + return class { + bar() { return x.length; } // Error: possibly null x + }; + } +} \ No newline at end of file From 402f1f6bf8af963d4cf127b6c123b5b1be1a50bf Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Fri, 7 Oct 2016 17:45:15 -0700 Subject: [PATCH 12/74] Narrowed consts flow through object literal or class expression method Fixes #10501 --- src/compiler/binder.ts | 14 ++++- src/compiler/checker.ts | 4 +- src/compiler/types.ts | 2 +- src/compiler/utilities.ts | 6 ++ .../narrowedConstInMethod.errors.txt | 27 --------- .../reference/narrowedConstInMethod.symbols | 41 ++++++++++++++ .../reference/narrowedConstInMethod.types | 55 +++++++++++++++++++ 7 files changed, 117 insertions(+), 32 deletions(-) delete mode 100644 tests/baselines/reference/narrowedConstInMethod.errors.txt create mode 100644 tests/baselines/reference/narrowedConstInMethod.symbols create mode 100644 tests/baselines/reference/narrowedConstInMethod.types diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 27803b43526..9906bfdc661 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -84,6 +84,7 @@ namespace ts { IsFunctionExpression = 1 << 4, HasLocals = 1 << 5, IsInterface = 1 << 6, + IsObjectLiteralOrClassExpressionMethod = 1 << 7, } const binder = createBinder(); @@ -486,8 +487,8 @@ namespace ts { } else { currentFlow = { flags: FlowFlags.Start }; - if (containerFlags & ContainerFlags.IsFunctionExpression) { - (currentFlow).container = node; + if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { + (currentFlow).container = node; } currentReturnTarget = undefined; } @@ -1237,9 +1238,12 @@ namespace ts { case SyntaxKind.SourceFile: return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals; + case SyntaxKind.MethodDeclaration: + if (isObjectLiteralOrClassExpressionMethod(node)) { + return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod; + } case SyntaxKind.Constructor: case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: @@ -2238,6 +2242,10 @@ namespace ts { } } + if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } + return hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dfe6317e250..20e20e0eea9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9163,7 +9163,9 @@ namespace ts { // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && - (flowContainer.kind === SyntaxKind.FunctionExpression || flowContainer.kind === SyntaxKind.ArrowFunction) && + (flowContainer.kind === SyntaxKind.FunctionExpression || + flowContainer.kind === SyntaxKind.ArrowFunction || + isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 638504e613f..5c4ffedb33c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1922,7 +1922,7 @@ namespace ts { // function, the container property references the function (which in turn has a flowNode // property for the containing control flow). export interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } // FlowLabel represents a junction with multiple possible preceding control flows. diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 558015bb0e3..498c195ea3a 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -895,6 +895,12 @@ namespace ts { return node && node.kind === SyntaxKind.MethodDeclaration && node.parent.kind === SyntaxKind.ObjectLiteralExpression; } + export function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration { + return node.kind === SyntaxKind.MethodDeclaration && + (node.parent.kind === SyntaxKind.ObjectLiteralExpression || + node.parent.kind === SyntaxKind.ClassExpression); + } + export function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate { return predicate && predicate.kind === TypePredicateKind.Identifier; } diff --git a/tests/baselines/reference/narrowedConstInMethod.errors.txt b/tests/baselines/reference/narrowedConstInMethod.errors.txt deleted file mode 100644 index ebb85218a5b..00000000000 --- a/tests/baselines/reference/narrowedConstInMethod.errors.txt +++ /dev/null @@ -1,27 +0,0 @@ -tests/cases/compiler/narrowedConstInMethod.ts(6,28): error TS2531: Object is possibly 'null'. -tests/cases/compiler/narrowedConstInMethod.ts(15,28): error TS2531: Object is possibly 'null'. - - -==== tests/cases/compiler/narrowedConstInMethod.ts (2 errors) ==== - - function f() { - const x: string | null = {}; - if (x !== null) { - return { - bar() { return x.length; } // Error: possibly null x - ~ -!!! error TS2531: Object is possibly 'null'. - }; - } - } - - function f2() { - const x: string | null = {}; - if (x !== null) { - return class { - bar() { return x.length; } // Error: possibly null x - ~ -!!! error TS2531: Object is possibly 'null'. - }; - } - } \ No newline at end of file diff --git a/tests/baselines/reference/narrowedConstInMethod.symbols b/tests/baselines/reference/narrowedConstInMethod.symbols new file mode 100644 index 00000000000..1fd05dcea5e --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.symbols @@ -0,0 +1,41 @@ +=== tests/cases/compiler/narrowedConstInMethod.ts === + +function f() { +>f : Symbol(f, Decl(narrowedConstInMethod.ts, 0, 0)) + + const x: string | null = {}; +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) + + if (x !== null) { +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) + + return { + bar() { return x.length; } // Error: possibly null x +>bar : Symbol(bar, Decl(narrowedConstInMethod.ts, 4, 16)) +>x.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 2, 9)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + }; + } +} + +function f2() { +>f2 : Symbol(f2, Decl(narrowedConstInMethod.ts, 8, 1)) + + const x: string | null = {}; +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) + + if (x !== null) { +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) + + return class { + bar() { return x.length; } // Error: possibly null x +>bar : Symbol((Anonymous class).bar, Decl(narrowedConstInMethod.ts, 13, 22)) +>x.length : Symbol(String.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(narrowedConstInMethod.ts, 11, 9)) +>length : Symbol(String.length, Decl(lib.d.ts, --, --)) + + }; + } +} diff --git a/tests/baselines/reference/narrowedConstInMethod.types b/tests/baselines/reference/narrowedConstInMethod.types new file mode 100644 index 00000000000..a73f2edfccb --- /dev/null +++ b/tests/baselines/reference/narrowedConstInMethod.types @@ -0,0 +1,55 @@ +=== tests/cases/compiler/narrowedConstInMethod.ts === + +function f() { +>f : () => { bar(): number; } | undefined + + const x: string | null = {}; +>x : string | null +>null : null +>{} : any +>{} : {} + + if (x !== null) { +>x !== null : boolean +>x : string | null +>null : null + + return { +>{ bar() { return x.length; } // Error: possibly null x } : { bar(): number; } + + bar() { return x.length; } // Error: possibly null x +>bar : () => number +>x.length : number +>x : string +>length : number + + }; + } +} + +function f2() { +>f2 : () => typeof (Anonymous class) | undefined + + const x: string | null = {}; +>x : string | null +>null : null +>{} : any +>{} : {} + + if (x !== null) { +>x !== null : boolean +>x : string | null +>null : null + + return class { +>class { bar() { return x.length; } // Error: possibly null x } : typeof (Anonymous class) + + bar() { return x.length; } // Error: possibly null x +>bar : () => number +>x.length : number +>x : string +>length : number + + }; + } +} From 71b9b3351755e3e6978cec656c91032c0bfb0ab1 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 8 Oct 2016 15:26:17 -0700 Subject: [PATCH 13/74] Fix issue in control flow analysis of nested loops --- src/compiler/checker.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0a606afe69f..2ff5700082a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8797,10 +8797,14 @@ namespace ts { } // If this flow loop junction and reference are already being processed, return // the union of the types computed for each branch so far, marked as incomplete. - // We should never see an empty array here because the first antecedent of a loop - // junction is always the non-looping control flow path that leads to the top. + // It is possible to see an empty array in cases where loops are nested and the + // back edge of the outer loop reaches an inner loop that is already being analyzed. + // In such cases we restart the analysis of the inner loop, which will then see + // a non-empty in-process array for the outer loop and eventually terminate because + // the first antecedent of a loop junction is always the non-looping control flow + // path that leads to the top. for (let i = flowLoopStart; i < flowLoopCount; i++) { - if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key) { + if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) { return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], /*subtypeReduction*/ false), /*incomplete*/ true); } } From d202b1c037634939003b88fec921465969dec028 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 8 Oct 2016 15:27:49 -0700 Subject: [PATCH 14/74] Add test --- tests/cases/compiler/controlFlowArrays.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts index d5eaa9c4320..781b8c09d12 100644 --- a/tests/cases/compiler/controlFlowArrays.ts +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -138,4 +138,13 @@ function f14() { x.push("hello"); x.push(true); return x; // (string | number | boolean)[] +} + +function f15() { + let x = []; + while (cond()) { + while (cond()) {} + x.push("hello"); + } + return x; // string[] } \ No newline at end of file From 89826a52ad09a5c854670caff7960e83a71fae43 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 8 Oct 2016 15:27:57 -0700 Subject: [PATCH 15/74] Accept new baselines --- .../baselines/reference/controlFlowArrays.js | 17 ++++++++++++ .../reference/controlFlowArrays.symbols | 21 +++++++++++++++ .../reference/controlFlowArrays.types | 26 +++++++++++++++++++ 3 files changed, 64 insertions(+) diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js index 26885aecd8b..c5ec1a7642c 100644 --- a/tests/baselines/reference/controlFlowArrays.js +++ b/tests/baselines/reference/controlFlowArrays.js @@ -137,6 +137,15 @@ function f14() { x.push("hello"); x.push(true); return x; // (string | number | boolean)[] +} + +function f15() { + let x = []; + while (cond()) { + while (cond()) {} + x.push("hello"); + } + return x; // string[] } //// [controlFlowArrays.js] @@ -265,3 +274,11 @@ function f14() { x.push(true); return x; // (string | number | boolean)[] } +function f15() { + var x = []; + while (cond()) { + while (cond()) { } + x.push("hello"); + } + return x; // string[] +} diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols index 5b5ef7f8506..fd7c6ba89b7 100644 --- a/tests/baselines/reference/controlFlowArrays.symbols +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -348,3 +348,24 @@ function f14() { return x; // (string | number | boolean)[] >x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) } + +function f15() { +>f15 : Symbol(f15, Decl(controlFlowArrays.ts, 138, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) + + while (cond()) { +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + while (cond()) {} +>cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; // string[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) +} diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types index 7b36e4067fa..3fb84215ed7 100644 --- a/tests/baselines/reference/controlFlowArrays.types +++ b/tests/baselines/reference/controlFlowArrays.types @@ -445,3 +445,29 @@ function f14() { return x; // (string | number | boolean)[] >x : (string | number | boolean)[] } + +function f15() { +>f15 : () => string[] + + let x = []; +>x : any[] +>[] : never[] + + while (cond()) { +>cond() : boolean +>cond : () => boolean + + while (cond()) {} +>cond() : boolean +>cond : () => boolean + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; // string[] +>x : string[] +} From 29a85e02ab4d43cf67d013aaac158c6a32108d20 Mon Sep 17 00:00:00 2001 From: Slawomir Sadziak Date: Sun, 9 Oct 2016 00:49:51 +0200 Subject: [PATCH 16/74] Fix #10758 Add compiler option to parse in strict mode * add compiler option alwaysStrict * compile in strict mode when option is set * emit "use strict" --- src/compiler/binder.ts | 15 +++++++++++++-- src/compiler/commandLineParser.ts | 5 +++++ src/compiler/diagnosticMessages.json | 4 ++++ src/compiler/transformers/ts.ts | 12 ++++++++++++ src/compiler/types.ts | 1 + src/harness/unittests/transpile.ts | 4 ++++ .../baselines/reference/alwaysStrict.errors.txt | 10 ++++++++++ tests/baselines/reference/alwaysStrict.js | 11 +++++++++++ .../reference/alwaysStrictES6.errors.txt | 10 ++++++++++ tests/baselines/reference/alwaysStrictES6.js | 11 +++++++++++ .../reference/alwaysStrictModule.errors.txt | 12 ++++++++++++ tests/baselines/reference/alwaysStrictModule.js | 17 +++++++++++++++++ .../alwaysStrictNoImplicitUseStrict.errors.txt | 12 ++++++++++++ .../alwaysStrictNoImplicitUseStrict.js | 17 +++++++++++++++++ .../transpile/Supports setting alwaysStrict.js | 3 +++ tests/cases/compiler/alwaysStrict.ts | 5 +++++ tests/cases/compiler/alwaysStrictES6.ts | 6 ++++++ tests/cases/compiler/alwaysStrictModule.ts | 8 ++++++++ .../compiler/alwaysStrictNoImplicitUseStrict.ts | 9 +++++++++ 19 files changed, 170 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/alwaysStrict.errors.txt create mode 100644 tests/baselines/reference/alwaysStrict.js create mode 100644 tests/baselines/reference/alwaysStrictES6.errors.txt create mode 100644 tests/baselines/reference/alwaysStrictES6.js create mode 100644 tests/baselines/reference/alwaysStrictModule.errors.txt create mode 100644 tests/baselines/reference/alwaysStrictModule.js create mode 100644 tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt create mode 100644 tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js create mode 100644 tests/baselines/reference/transpile/Supports setting alwaysStrict.js create mode 100644 tests/cases/compiler/alwaysStrict.ts create mode 100644 tests/cases/compiler/alwaysStrictES6.ts create mode 100644 tests/cases/compiler/alwaysStrictModule.ts create mode 100644 tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 27803b43526..13da6520408 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -121,7 +121,8 @@ namespace ts { // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. let inStrictMode: boolean; let symbolCount = 0; @@ -139,7 +140,7 @@ namespace ts { file = f; options = opts; languageVersion = getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = createMap(); symbolCount = 0; skipTransformFlagAggregation = isDeclarationFile(file); @@ -174,6 +175,16 @@ namespace ts { return bindSourceFile; + function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean { + if (opts.alwaysStrict && !isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } + function createSymbol(flags: SymbolFlags, name: string): Symbol { symbolCount++; return new Symbol(flags, name); diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 648447ac26a..2d657307ec7 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -444,6 +444,11 @@ namespace ts { name: "importHelpers", type: "boolean", description: Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 58c0e6ee3f2..70fc7c43d8d 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2861,6 +2861,10 @@ "category": "Error", "code": 6140 }, + "Parse in strict mode and emit \"use strict\" for each source file": { + "category": "Message", + "code": 6141 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", "code": 7005 diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 41f03d20f2e..7b6c28a8f41 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -436,6 +436,11 @@ namespace ts { function visitSourceFile(node: SourceFile) { currentSourceFile = node; + // ensure "use strict"" is emitted in all scenarios in alwaysStrict mode + if (compilerOptions.alwaysStrict) { + node = emitUseStrict(node); + } + // If the source file requires any helpers and is an external module, and // the importHelpers compiler option is enabled, emit a synthesized import // statement for the helpers library. @@ -472,6 +477,13 @@ namespace ts { return node; } + function emitUseStrict(node: SourceFile): SourceFile { + const statements: Statement[] = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + /** * Tests whether we should emit a __decorate call for a class declaration. */ diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 638504e613f..171d7c40e7e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2929,6 +2929,7 @@ namespace ts { allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; /* @internal */ configFilePath?: string; diff --git a/src/harness/unittests/transpile.ts b/src/harness/unittests/transpile.ts index 808a5df37c1..35b4f808350 100644 --- a/src/harness/unittests/transpile.ts +++ b/src/harness/unittests/transpile.ts @@ -253,6 +253,10 @@ var x = 0;`, { options: { compilerOptions: { allowUnusedLabels: true }, fileName: "input.js", reportDiagnostics: true } }); + transpilesCorrectly("Supports setting 'alwaysStrict'", "x;", { + options: { compilerOptions: { alwaysStrict: true }, fileName: "input.js", reportDiagnostics: true } + }); + transpilesCorrectly("Supports setting 'baseUrl'", "x;", { options: { compilerOptions: { baseUrl: "./folder/baseUrl" }, fileName: "input.js", reportDiagnostics: true } }); diff --git a/tests/baselines/reference/alwaysStrict.errors.txt b/tests/baselines/reference/alwaysStrict.errors.txt new file mode 100644 index 00000000000..d7fcfb45801 --- /dev/null +++ b/tests/baselines/reference/alwaysStrict.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/alwaysStrict.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrict.ts (1 errors) ==== + + function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrict.js b/tests/baselines/reference/alwaysStrict.js new file mode 100644 index 00000000000..bc5f9a29912 --- /dev/null +++ b/tests/baselines/reference/alwaysStrict.js @@ -0,0 +1,11 @@ +//// [alwaysStrict.ts] + +function f() { + var arguments = []; +} + +//// [alwaysStrict.js] +"use strict"; +function f() { + var arguments = []; +} diff --git a/tests/baselines/reference/alwaysStrictES6.errors.txt b/tests/baselines/reference/alwaysStrictES6.errors.txt new file mode 100644 index 00000000000..b775a6e4755 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictES6.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/alwaysStrictES6.ts(3,9): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrictES6.ts (1 errors) ==== + + function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictES6.js b/tests/baselines/reference/alwaysStrictES6.js new file mode 100644 index 00000000000..2c7ad36bce2 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictES6.js @@ -0,0 +1,11 @@ +//// [alwaysStrictES6.ts] + +function f() { + var arguments = []; +} + +//// [alwaysStrictES6.js] +"use strict"; +function f() { + var arguments = []; +} diff --git a/tests/baselines/reference/alwaysStrictModule.errors.txt b/tests/baselines/reference/alwaysStrictModule.errors.txt new file mode 100644 index 00000000000..90c1a0b930a --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/alwaysStrictModule.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrictModule.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictModule.js b/tests/baselines/reference/alwaysStrictModule.js new file mode 100644 index 00000000000..f39c87ed96c --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule.js @@ -0,0 +1,17 @@ +//// [alwaysStrictModule.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [alwaysStrictModule.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); diff --git a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt new file mode 100644 index 00000000000..d677ec9b4cb --- /dev/null +++ b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt @@ -0,0 +1,12 @@ +tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js new file mode 100644 index 00000000000..cfa7f69629f --- /dev/null +++ b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.js @@ -0,0 +1,17 @@ +//// [alwaysStrictNoImplicitUseStrict.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [alwaysStrictNoImplicitUseStrict.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); diff --git a/tests/baselines/reference/transpile/Supports setting alwaysStrict.js b/tests/baselines/reference/transpile/Supports setting alwaysStrict.js new file mode 100644 index 00000000000..8d91090453b --- /dev/null +++ b/tests/baselines/reference/transpile/Supports setting alwaysStrict.js @@ -0,0 +1,3 @@ +"use strict"; +x; +//# sourceMappingURL=input.js.map \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrict.ts b/tests/cases/compiler/alwaysStrict.ts new file mode 100644 index 00000000000..22ec09c6e38 --- /dev/null +++ b/tests/cases/compiler/alwaysStrict.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true + +function f() { + var arguments = []; +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictES6.ts b/tests/cases/compiler/alwaysStrictES6.ts new file mode 100644 index 00000000000..edb542fa86a --- /dev/null +++ b/tests/cases/compiler/alwaysStrictES6.ts @@ -0,0 +1,6 @@ +// @target: ES6 +// @alwaysStrict: true + +function f() { + var arguments = []; +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictModule.ts b/tests/cases/compiler/alwaysStrictModule.ts new file mode 100644 index 00000000000..b706f5869a6 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule.ts @@ -0,0 +1,8 @@ +// @module: commonjs +// @alwaysStrict: true + +module M { + export function f() { + var arguments = []; + } +} \ No newline at end of file diff --git a/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts b/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts new file mode 100644 index 00000000000..d3173df8ab5 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts @@ -0,0 +1,9 @@ +// @module: commonjs +// @alwaysStrict: true +// @noImplicitUseStrict: true + +module M { + export function f() { + var arguments = []; + } +} \ No newline at end of file From ea808f52fe3dd70dedc6294ebda26a4100767ad1 Mon Sep 17 00:00:00 2001 From: Slawomir Sadziak Date: Mon, 10 Oct 2016 12:15:34 +0200 Subject: [PATCH 17/74] Fix #10758 Add compiler option to parse in strict mode * add unit test to ensure "use strict" is not added twice * fix code --- src/compiler/factory.ts | 30 +++++++++++++++++++ src/compiler/transformers/ts.ts | 9 +----- .../reference/alwaysStrictAlreadyUseStrict.js | 11 +++++++ .../alwaysStrictAlreadyUseStrict.symbols | 8 +++++ .../alwaysStrictAlreadyUseStrict.types | 11 +++++++ .../compiler/alwaysStrictAlreadyUseStrict.ts | 5 ++++ 6 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 tests/baselines/reference/alwaysStrictAlreadyUseStrict.js create mode 100644 tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols create mode 100644 tests/baselines/reference/alwaysStrictAlreadyUseStrict.types create mode 100644 tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 97a36f46b13..6bf6259c364 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2235,6 +2235,36 @@ namespace ts { return statementOffset; } + /** + * Ensures "use strict" directive is added + * + * @param node source file + */ + export function ensureUseStrict(node: SourceFile): SourceFile { + let foundUseStrict = false; + let statementOffset = 0; + const numStatements = node.statements.length; + while (statementOffset < numStatements) { + const statement = node.statements[statementOffset]; + if (isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement as ExpressionStatement)) { + foundUseStrict = true; + } + } + else { + break; + } + statementOffset++; + } + if (!foundUseStrict) { + const statements: Statement[] = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 7b6c28a8f41..112f838a370 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -438,7 +438,7 @@ namespace ts { // ensure "use strict"" is emitted in all scenarios in alwaysStrict mode if (compilerOptions.alwaysStrict) { - node = emitUseStrict(node); + node = ensureUseStrict(node); } // If the source file requires any helpers and is an external module, and @@ -477,13 +477,6 @@ namespace ts { return node; } - function emitUseStrict(node: SourceFile): SourceFile { - const statements: Statement[] = []; - statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); - // add "use strict" as the first statement - return updateSourceFileNode(node, statements.concat(node.statements)); - } - /** * Tests whether we should emit a __decorate call for a class declaration. */ diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js new file mode 100644 index 00000000000..cc3be45dedc --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.js @@ -0,0 +1,11 @@ +//// [alwaysStrictAlreadyUseStrict.ts] +"use strict" +function f() { + var a = []; +} + +//// [alwaysStrictAlreadyUseStrict.js] +"use strict"; +function f() { + var a = []; +} diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols new file mode 100644 index 00000000000..143f579b94d --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.symbols @@ -0,0 +1,8 @@ +=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts === +"use strict" +function f() { +>f : Symbol(f, Decl(alwaysStrictAlreadyUseStrict.ts, 0, 12)) + + var a = []; +>a : Symbol(a, Decl(alwaysStrictAlreadyUseStrict.ts, 2, 7)) +} diff --git a/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types new file mode 100644 index 00000000000..0181b40de27 --- /dev/null +++ b/tests/baselines/reference/alwaysStrictAlreadyUseStrict.types @@ -0,0 +1,11 @@ +=== tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts === +"use strict" +>"use strict" : "use strict" + +function f() { +>f : () => void + + var a = []; +>a : any[] +>[] : undefined[] +} diff --git a/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts b/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts new file mode 100644 index 00000000000..1d804a6cf90 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictAlreadyUseStrict.ts @@ -0,0 +1,5 @@ +// @alwaysStrict: true +"use strict" +function f() { + var a = []; +} \ No newline at end of file From 8210634e8dbc9a1bc41c108b21c19b4cfac4d91c Mon Sep 17 00:00:00 2001 From: Slawomir Sadziak Date: Mon, 10 Oct 2016 23:03:07 +0200 Subject: [PATCH 18/74] Fix #10758 Add compiler option to parse in strict mode * fix comment * optimize loop --- src/compiler/factory.ts | 7 ++----- src/compiler/transformers/ts.ts | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 6bf6259c364..5a95600d089 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2242,19 +2242,16 @@ namespace ts { */ export function ensureUseStrict(node: SourceFile): SourceFile { let foundUseStrict = false; - let statementOffset = 0; - const numStatements = node.statements.length; - while (statementOffset < numStatements) { - const statement = node.statements[statementOffset]; + for (const statement of node.statements) { if (isPrologueDirective(statement)) { if (isUseStrictPrologue(statement as ExpressionStatement)) { foundUseStrict = true; + break; } } else { break; } - statementOffset++; } if (!foundUseStrict) { const statements: Statement[] = []; diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 112f838a370..2c146c91bc3 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -436,7 +436,7 @@ namespace ts { function visitSourceFile(node: SourceFile) { currentSourceFile = node; - // ensure "use strict"" is emitted in all scenarios in alwaysStrict mode + // ensure "use strict" is emitted in all scenarios in alwaysStrict mode if (compilerOptions.alwaysStrict) { node = ensureUseStrict(node); } From 49fd35da33cf3de26199c8183581124974423f50 Mon Sep 17 00:00:00 2001 From: Bill Ticehurst Date: Mon, 10 Oct 2016 22:40:03 -0700 Subject: [PATCH 19/74] Resolve export= module members --- src/compiler/checker.ts | 4 + .../reference/bluebirdStaticThis.errors.txt | 188 +++++++++++++++++- 2 files changed, 191 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dfe6317e250..b5fe19b0a80 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1465,6 +1465,10 @@ namespace ts { function getExportsForModule(moduleSymbol: Symbol): SymbolTable { const visitedSymbols: Symbol[] = []; + + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); + return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, diff --git a/tests/baselines/reference/bluebirdStaticThis.errors.txt b/tests/baselines/reference/bluebirdStaticThis.errors.txt index 1c22a12c341..a20c7ace880 100644 --- a/tests/baselines/reference/bluebirdStaticThis.errors.txt +++ b/tests/baselines/reference/bluebirdStaticThis.errors.txt @@ -1,13 +1,75 @@ tests/cases/compiler/bluebirdStaticThis.ts(5,15): error TS2420: Class 'Promise' incorrectly implements interface 'Thenable'. Property 'then' is missing in type 'Promise'. +tests/cases/compiler/bluebirdStaticThis.ts(7,12): error TS2323: Cannot redeclare exported variable 'try'. +tests/cases/compiler/bluebirdStaticThis.ts(8,12): error TS2323: Cannot redeclare exported variable 'try'. +tests/cases/compiler/bluebirdStaticThis.ts(10,12): error TS2323: Cannot redeclare exported variable 'attempt'. +tests/cases/compiler/bluebirdStaticThis.ts(11,12): error TS2323: Cannot redeclare exported variable 'attempt'. +tests/cases/compiler/bluebirdStaticThis.ts(15,12): error TS2323: Cannot redeclare exported variable 'resolve'. +tests/cases/compiler/bluebirdStaticThis.ts(16,12): error TS2323: Cannot redeclare exported variable 'resolve'. +tests/cases/compiler/bluebirdStaticThis.ts(17,12): error TS2323: Cannot redeclare exported variable 'resolve'. +tests/cases/compiler/bluebirdStaticThis.ts(19,12): error TS2323: Cannot redeclare exported variable 'reject'. +tests/cases/compiler/bluebirdStaticThis.ts(20,12): error TS2323: Cannot redeclare exported variable 'reject'. tests/cases/compiler/bluebirdStaticThis.ts(22,51): error TS2694: Namespace 'Promise' has no exported member 'Resolver'. +tests/cases/compiler/bluebirdStaticThis.ts(24,12): error TS2323: Cannot redeclare exported variable 'cast'. +tests/cases/compiler/bluebirdStaticThis.ts(25,12): error TS2323: Cannot redeclare exported variable 'cast'. +tests/cases/compiler/bluebirdStaticThis.ts(33,12): error TS2323: Cannot redeclare exported variable 'delay'. +tests/cases/compiler/bluebirdStaticThis.ts(34,12): error TS2323: Cannot redeclare exported variable 'delay'. +tests/cases/compiler/bluebirdStaticThis.ts(35,12): error TS2323: Cannot redeclare exported variable 'delay'. +tests/cases/compiler/bluebirdStaticThis.ts(49,12): error TS2323: Cannot redeclare exported variable 'all'. +tests/cases/compiler/bluebirdStaticThis.ts(50,12): error TS2323: Cannot redeclare exported variable 'all'. +tests/cases/compiler/bluebirdStaticThis.ts(51,12): error TS2323: Cannot redeclare exported variable 'all'. +tests/cases/compiler/bluebirdStaticThis.ts(52,12): error TS2323: Cannot redeclare exported variable 'all'. +tests/cases/compiler/bluebirdStaticThis.ts(54,12): error TS2323: Cannot redeclare exported variable 'props'. +tests/cases/compiler/bluebirdStaticThis.ts(55,12): error TS2323: Cannot redeclare exported variable 'props'. +tests/cases/compiler/bluebirdStaticThis.ts(57,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(57,109): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. +tests/cases/compiler/bluebirdStaticThis.ts(58,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(58,91): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. +tests/cases/compiler/bluebirdStaticThis.ts(59,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(59,91): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. +tests/cases/compiler/bluebirdStaticThis.ts(60,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. +tests/cases/compiler/bluebirdStaticThis.ts(62,12): error TS2323: Cannot redeclare exported variable 'any'. +tests/cases/compiler/bluebirdStaticThis.ts(63,12): error TS2323: Cannot redeclare exported variable 'any'. +tests/cases/compiler/bluebirdStaticThis.ts(64,12): error TS2323: Cannot redeclare exported variable 'any'. +tests/cases/compiler/bluebirdStaticThis.ts(65,12): error TS2323: Cannot redeclare exported variable 'any'. +tests/cases/compiler/bluebirdStaticThis.ts(67,12): error TS2323: Cannot redeclare exported variable 'race'. +tests/cases/compiler/bluebirdStaticThis.ts(68,12): error TS2323: Cannot redeclare exported variable 'race'. +tests/cases/compiler/bluebirdStaticThis.ts(69,12): error TS2323: Cannot redeclare exported variable 'race'. +tests/cases/compiler/bluebirdStaticThis.ts(70,12): error TS2323: Cannot redeclare exported variable 'race'. +tests/cases/compiler/bluebirdStaticThis.ts(72,12): error TS2323: Cannot redeclare exported variable 'some'. +tests/cases/compiler/bluebirdStaticThis.ts(73,12): error TS2323: Cannot redeclare exported variable 'some'. +tests/cases/compiler/bluebirdStaticThis.ts(74,12): error TS2323: Cannot redeclare exported variable 'some'. +tests/cases/compiler/bluebirdStaticThis.ts(75,12): error TS2323: Cannot redeclare exported variable 'some'. +tests/cases/compiler/bluebirdStaticThis.ts(77,12): error TS2323: Cannot redeclare exported variable 'join'. +tests/cases/compiler/bluebirdStaticThis.ts(78,12): error TS2323: Cannot redeclare exported variable 'join'. +tests/cases/compiler/bluebirdStaticThis.ts(80,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(81,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(82,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(83,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(84,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(85,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(86,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(87,12): error TS2323: Cannot redeclare exported variable 'map'. +tests/cases/compiler/bluebirdStaticThis.ts(89,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(90,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(92,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(93,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(95,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(96,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(98,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(99,12): error TS2323: Cannot redeclare exported variable 'reduce'. +tests/cases/compiler/bluebirdStaticThis.ts(101,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(102,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(103,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(104,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(105,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(106,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(107,12): error TS2323: Cannot redeclare exported variable 'filter'. +tests/cases/compiler/bluebirdStaticThis.ts(108,12): error TS2323: Cannot redeclare exported variable 'filter'. -==== tests/cases/compiler/bluebirdStaticThis.ts (6 errors) ==== +==== tests/cases/compiler/bluebirdStaticThis.ts (68 errors) ==== // This version is reduced from the full d.ts by removing almost all the tests // and all the comments. // Then it adds explicit `this` arguments to the static members. @@ -18,26 +80,48 @@ tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace 'Prom !!! error TS2420: Property 'then' is missing in type 'Promise'. constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable) => void, reject: (error: any) => void) => void); static try(dit: typeof Promise, fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'try'. static try(dit: typeof Promise, fn: () => R, args?: any[], ctx?: any): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'try'. static attempt(dit: typeof Promise, fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; + ~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'attempt'. static attempt(dit: typeof Promise, fn: () => R, args?: any[], ctx?: any): Promise; + ~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'attempt'. static method(dit: typeof Promise, fn: Function): Function; static resolve(dit: typeof Promise): Promise; + ~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'resolve'. static resolve(dit: typeof Promise, value: Promise.Thenable): Promise; + ~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'resolve'. static resolve(dit: typeof Promise, value: R): Promise; + ~~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'resolve'. static reject(dit: typeof Promise, reason: any): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reject'. static reject(dit: typeof Promise, reason: any): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reject'. static defer(dit: typeof Promise): Promise.Resolver; ~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Resolver'. static cast(dit: typeof Promise, value: Promise.Thenable): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'cast'. static cast(dit: typeof Promise, value: R): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'cast'. static bind(dit: typeof Promise, thisArg: any): Promise; @@ -46,8 +130,14 @@ tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace 'Prom static longStackTraces(dit: typeof Promise): void; static delay(dit: typeof Promise, value: Promise.Thenable, ms: number): Promise; + ~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'delay'. static delay(dit: typeof Promise, value: R, ms: number): Promise; + ~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'delay'. static delay(dit: typeof Promise, ms: number): Promise; + ~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'delay'. static promisify(dit: typeof Promise, nodeFunction: Function, receiver?: any): Function; @@ -62,73 +152,169 @@ tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace 'Prom static onPossiblyUnhandledRejection(dit: typeof Promise, handler: (reason: any) => any): void; static all(dit: typeof Promise, values: Promise.Thenable[]>): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: Promise.Thenable[]): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: R[]): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'all'. static props(dit: typeof Promise, object: Promise): Promise; + ~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'props'. static props(dit: typeof Promise, object: Object): Promise; + ~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'props'. static settle(dit: typeof Promise, values: Promise.Thenable[]>): Promise[]>; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: Promise.Thenable): Promise[]>; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: Promise.Thenable[]): Promise[]>; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: R[]): Promise[]>; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static any(dit: typeof Promise, values: Promise.Thenable[]>): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: Promise.Thenable[]): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: R[]): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'any'. static race(dit: typeof Promise, values: Promise.Thenable[]>): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: Promise.Thenable): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: Promise.Thenable[]): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: R[]): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'race'. static some(dit: typeof Promise, values: Promise.Thenable[]>, count: number): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: Promise.Thenable, count: number): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: Promise.Thenable[], count: number): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: R[], count: number): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'some'. static join(dit: typeof Promise, ...values: Promise.Thenable[]): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'join'. static join(dit: typeof Promise, ...values: R[]): Promise; + ~~~~ +!!! error TS2323: Cannot redeclare exported variable 'join'. static map(dit: typeof Promise, values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + ~~~ +!!! error TS2323: Cannot redeclare exported variable 'map'. static reduce(dit: typeof Promise, values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'reduce'. static filter(dit: typeof Promise, values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + ~~~~~~ +!!! error TS2323: Cannot redeclare exported variable 'filter'. } declare module Promise { From e6b588a956d5046469dbfa240d35ab1cc09c0046 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 11 Oct 2016 10:14:06 -0700 Subject: [PATCH 20/74] Support parentheses and comma operator with evolving arrays --- src/compiler/binder.ts | 10 +++++----- src/compiler/checker.ts | 34 ++++++++++++++++++++++++---------- src/compiler/types.ts | 2 +- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 1b121394a8c..6926403d9bb 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -760,7 +760,7 @@ namespace ts { }; } - function createFlowArrayMutation(antecedent: FlowNode, node: Expression): FlowNode { + function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode { setFlowNodeReferenced(antecedent); return { flags: FlowFlags.ArrayMutation, @@ -1151,8 +1151,8 @@ namespace ts { bindAssignmentTargetFlow(node.left); if (node.left.kind === SyntaxKind.ElementAccessExpression) { const elementAccess = node.left; - if (isNarrowableReference(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, elementAccess.expression); + if (isNarrowableOperand(elementAccess.expression)) { + currentFlow = createFlowArrayMutation(currentFlow, node); } } } @@ -1217,8 +1217,8 @@ namespace ts { } if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { const propertyAccess = node.expression; - if (isNarrowableReference(propertyAccess.expression) && propertyAccess.name.text === "push") { - currentFlow = createFlowArrayMutation(currentFlow, propertyAccess.expression); + if (isNarrowableOperand(propertyAccess.expression) && propertyAccess.name.text === "push") { + currentFlow = createFlowArrayMutation(currentFlow, node); } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2ff5700082a..379d61850e4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8424,6 +8424,14 @@ namespace ts { return node; } + function getReferenceParent(node: Node): Node { + const parent = node.parent; + return parent.kind === SyntaxKind.ParenthesizedExpression || + parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node || + parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.CommaToken && (parent).right === node ? + getReferenceParent(parent) : parent; + } + function getTypeOfSwitchClause(clause: CaseClause | DefaultClause) { if (clause.kind === SyntaxKind.CaseClause) { const caseType = getRegularTypeOfLiteralType(checkExpression((clause).expression)); @@ -8556,15 +8564,16 @@ namespace ts { // Return true if the given node is 'x' in an 'x.push(value)' operation. function isPushCallTarget(node: Node) { - return node.parent.kind === SyntaxKind.PropertyAccessExpression && - (node.parent).name.text === "push" && - node.parent.parent.kind === SyntaxKind.CallExpression; + const parent = getReferenceParent(node); + return parent.kind === SyntaxKind.PropertyAccessExpression && + (parent).name.text === "push" && + parent.parent.kind === SyntaxKind.CallExpression; } // Return true if the given node is 'x' in an 'x[n] = value' operation, where 'n' is an // expression of type any, undefined, or a number-like type. function isElementAssignmentTarget(node: Node) { - const parent = node.parent; + const parent = getReferenceParent(node); return parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === node && parent.parent.kind === SyntaxKind.BinaryExpression && @@ -8696,19 +8705,24 @@ namespace ts { function getTypeAtFlowArrayMutation(flow: FlowArrayMutation): FlowType { const node = flow.node; - if (isMatchingReference(reference, node)) { + const expr = node.kind === SyntaxKind.CallExpression ? + ((node).expression).expression : + ((node).left).expression; + if (isMatchingReference(reference, getReferenceCandidate(expr))) { const flowType = getTypeAtFlowNode(flow.antecedent); const type = getTypeFromFlowType(flowType); if (isEvolvingArrayType(type)) { - const parent = node.parent; let evolvedType = type; - if (parent.kind === SyntaxKind.PropertyAccessExpression) { - for (const arg of (parent.parent).arguments) { + if (node.kind === SyntaxKind.CallExpression) { + for (const arg of (node).arguments) { evolvedType = addEvolvingArrayElementType(evolvedType, arg); } } - else if (isTypeAnyOrAllConstituentTypesHaveKind(checkExpression((parent).argumentExpression), TypeFlags.NumberLike)) { - evolvedType = addEvolvingArrayElementType(evolvedType, (parent.parent).right); + else { + const indexType = checkExpression(((node).left).argumentExpression); + if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike | TypeFlags.Undefined)) { + evolvedType = addEvolvingArrayElementType(evolvedType, (node).right); + } } return evolvedType === type ? flowType : createFlowType(evolvedType, isIncomplete(flowType)); } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 9759c2ab540..5c32649d97c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1955,7 +1955,7 @@ namespace ts { // FlowArrayMutation represents a node potentially mutates an array, i.e. an // operation of the form 'x.push(value)' or 'x[n] = value'. export interface FlowArrayMutation extends FlowNode { - node: Expression; + node: CallExpression | BinaryExpression; antecedent: FlowNode; } From 612ed1e24a0932b005a57d27092e39711046be10 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 11 Oct 2016 10:27:40 -0700 Subject: [PATCH 21/74] Fix minor issue --- src/compiler/checker.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 379d61850e4..9e2b7a31748 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8424,12 +8424,12 @@ namespace ts { return node; } - function getReferenceParent(node: Node): Node { + function getReferenceRoot(node: Node): Node { const parent = node.parent; return parent.kind === SyntaxKind.ParenthesizedExpression || parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node || parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.CommaToken && (parent).right === node ? - getReferenceParent(parent) : parent; + getReferenceRoot(parent) : node; } function getTypeOfSwitchClause(clause: CaseClause | DefaultClause) { @@ -8564,7 +8564,7 @@ namespace ts { // Return true if the given node is 'x' in an 'x.push(value)' operation. function isPushCallTarget(node: Node) { - const parent = getReferenceParent(node); + const parent = getReferenceRoot(node).parent; return parent.kind === SyntaxKind.PropertyAccessExpression && (parent).name.text === "push" && parent.parent.kind === SyntaxKind.CallExpression; @@ -8573,9 +8573,10 @@ namespace ts { // Return true if the given node is 'x' in an 'x[n] = value' operation, where 'n' is an // expression of type any, undefined, or a number-like type. function isElementAssignmentTarget(node: Node) { - const parent = getReferenceParent(node); + const root = getReferenceRoot(node); + const parent = root.parent; return parent.kind === SyntaxKind.ElementAccessExpression && - (parent).expression === node && + (parent).expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && (parent.parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent.parent).left === parent && From e9858de363e22b0f0318ef8b2848306e944aff50 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 11 Oct 2016 10:28:13 -0700 Subject: [PATCH 22/74] Add test --- tests/cases/compiler/controlFlowArrays.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts index 781b8c09d12..e89a2443753 100644 --- a/tests/cases/compiler/controlFlowArrays.ts +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -147,4 +147,13 @@ function f15() { x.push("hello"); } return x; // string[] +} + +function f16() { + let x; + let y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] } \ No newline at end of file From c9e2f959184beda9e25ee97d186a5dea0f44bb88 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 11 Oct 2016 10:32:00 -0700 Subject: [PATCH 23/74] Accept new baselines --- .../baselines/reference/controlFlowArrays.js | 17 +++++++ .../reference/controlFlowArrays.symbols | 31 ++++++++++++ .../reference/controlFlowArrays.types | 50 +++++++++++++++++++ 3 files changed, 98 insertions(+) diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js index c5ec1a7642c..d6f387ab981 100644 --- a/tests/baselines/reference/controlFlowArrays.js +++ b/tests/baselines/reference/controlFlowArrays.js @@ -146,6 +146,15 @@ function f15() { x.push("hello"); } return x; // string[] +} + +function f16() { + let x; + let y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] } //// [controlFlowArrays.js] @@ -282,3 +291,11 @@ function f15() { } return x; // string[] } +function f16() { + var x; + var y; + (x = [], x).push(5); + (x.push("hello"), x).push(true); + ((x))[3] = { a: 1 }; + return x; // (string | number | boolean | { a: number })[] +} diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols index fd7c6ba89b7..204a2171992 100644 --- a/tests/baselines/reference/controlFlowArrays.symbols +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -369,3 +369,34 @@ function f15() { return x; // string[] >x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) } + +function f16() { +>f16 : Symbol(f16, Decl(controlFlowArrays.ts, 147, 1)) + + let x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) + + let y; +>y : Symbol(y, Decl(controlFlowArrays.ts, 151, 7)) + + (x = [], x).push(5); +>(x = [], x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + (x.push("hello"), x).push(true); +>(x.push("hello"), x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + ((x))[3] = { a: 1 }; +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>a : Symbol(a, Decl(controlFlowArrays.ts, 154, 16)) + + return x; // (string | number | boolean | { a: number })[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +} diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types index 3fb84215ed7..3a91ce7e197 100644 --- a/tests/baselines/reference/controlFlowArrays.types +++ b/tests/baselines/reference/controlFlowArrays.types @@ -471,3 +471,53 @@ function f15() { return x; // string[] >x : string[] } + +function f16() { +>f16 : () => (string | number | boolean | { a: number; })[] + + let x; +>x : any + + let y; +>y : any + + (x = [], x).push(5); +>(x = [], x).push(5) : number +>(x = [], x).push : (...items: any[]) => number +>(x = [], x) : any[] +>x = [], x : any[] +>x = [] : never[] +>x : any +>[] : never[] +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + (x.push("hello"), x).push(true); +>(x.push("hello"), x).push(true) : number +>(x.push("hello"), x).push : (...items: any[]) => number +>(x.push("hello"), x) : any[] +>x.push("hello"), x : any[] +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" +>x : any[] +>push : (...items: any[]) => number +>true : true + + ((x))[3] = { a: 1 }; +>((x))[3] = { a: 1 } : { a: number; } +>((x))[3] : any +>((x)) : any[] +>(x) : any[] +>x : any[] +>3 : 3 +>{ a: 1 } : { a: number; } +>a : number +>1 : 1 + + return x; // (string | number | boolean | { a: number })[] +>x : (string | number | boolean | { a: number; })[] +} From d7e33c90a2fb6748c39630fc2a9f5d8e8272e9a7 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Tue, 11 Oct 2016 13:51:53 -0700 Subject: [PATCH 24/74] Guard localeCompare function --- src/compiler/core.ts | 22 ++++++++++++++++++++-- src/harness/harness.ts | 2 +- src/server/session.ts | 2 +- src/services/navigateTo.ts | 4 ++-- src/services/navigationBar.ts | 6 ++---- 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7c68306211a..5ad9fa2c199 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -20,6 +20,24 @@ namespace ts { const createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; + + /** + * Use this function instead of calling "String.prototype.localeCompre". This function will preform appropriate check to make sure that + * "typeof Intl" is correct as there are reported issues #11110 nad #11339. + * @param a reference string to compare + * @param b string to compare against + * @param locales string of BCP 47 language tag or an array of string of BCP 47 language tag + * @param options an object of Intl.CollatorOptions to specify localeCompare properties + */ + export function localeCompare(a: string, b: string, locales?: string | string[], options?: Intl.CollatorOptions): number | undefined { + if (collator && String.prototype.localeCompare) { + return a.localeCompare(b, locales, options); + } + return undefined; + } + export function createMap(template?: MapLike): Map { const map: Map = createObject(null); // tslint:disable-line:no-null-keyword @@ -1016,8 +1034,8 @@ namespace ts { if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; if (ignoreCase) { - if (String.prototype.localeCompare) { - const result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); + const result = localeCompare(a, b, /*locales*/ undefined, /*options*/ { usage: "sort", sensitivity: "accent" }); + if (result) { return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo; } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 7c82aeece78..f26a9dd062b 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1634,7 +1634,7 @@ namespace Harness { export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string { // Collect, test, and sort the fileNames - outputFiles.sort((a, b) => cleanName(a.fileName).localeCompare(cleanName(b.fileName))); + outputFiles.sort((a, b) => ts.localeCompare(cleanName(a.fileName), cleanName(b.fileName))); // Emit them let result = ""; diff --git a/src/server/session.ts b/src/server/session.ts index 3b95bdd6fb9..d4633f119e3 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -959,7 +959,7 @@ namespace ts.server { result.push({ name, kind, kindModifiers, sortText, replacementSpan: convertedSpan }); } return result; - }, []).sort((a, b) => a.name.localeCompare(b.name)); + }, []).sort((a, b) => localeCompare(a.name, b.name)); } else { return completions; diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 44aa25f5005..8c968db7ebb 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -188,8 +188,8 @@ namespace ts.NavigateTo { // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.localeCompare(i1.name, i2.name, /*locales*/ undefined, /*options*/ baseSensitivity) || + ts.localeCompare(i1.name, i2.name); } function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 0397ae73229..f981ad6016d 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -323,10 +323,8 @@ namespace ts.NavigationBar { } } - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - const localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; + const localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; const localeCompareFix: (a: string, b: string) => number = localeCompareIsCorrect ? collator.compare : function(a, b) { // This isn't perfect, but it passes all of our tests. for (let i = 0; i < Math.min(a.length, b.length); i++) { @@ -337,7 +335,7 @@ namespace ts.NavigationBar { if (chA === "'" && chB === "\"") { return -1; } - const cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + const cmp = ts.localeCompare(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } From a4e7bff759b7d23cca787ff205b4119b950e7fe5 Mon Sep 17 00:00:00 2001 From: Bill Ticehurst Date: Tue, 11 Oct 2016 17:51:53 -0700 Subject: [PATCH 25/74] Fixed errors with overloaded method exports --- src/compiler/checker.ts | 3 ++- .../completionListInImportClause04.ts | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/completionListInImportClause04.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index b5fe19b0a80..273b5e06134 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -17893,7 +17893,8 @@ namespace ts { } function isNotOverload(declaration: Declaration): boolean { - return declaration.kind !== SyntaxKind.FunctionDeclaration || !!(declaration as FunctionDeclaration).body; + return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) || + !!(declaration as FunctionDeclaration).body; } } diff --git a/tests/cases/fourslash/completionListInImportClause04.ts b/tests/cases/fourslash/completionListInImportClause04.ts new file mode 100644 index 00000000000..672c754e807 --- /dev/null +++ b/tests/cases/fourslash/completionListInImportClause04.ts @@ -0,0 +1,20 @@ +/// + +// @Filename: foo.d.ts +//// declare class Foo { +//// static prop1(x: number): number; +//// static prop1(x: string): string; +//// static prop2(x: boolean): boolean; +//// } +//// export = Foo; /*2*/ + +// @Filename: app.ts +////import {/*1*/} from './foo'; + +goTo.marker('1'); +verify.completionListContains('prop1'); +verify.completionListContains('prop2'); +verify.not.completionListContains('Foo'); +verify.numberOfErrorsInCurrentFile(0); +goTo.marker('2'); +verify.numberOfErrorsInCurrentFile(0); From db5da0b85f7803f8f6bc17b2f8e2a2105a4ccc5b Mon Sep 17 00:00:00 2001 From: Bill Ticehurst Date: Tue, 11 Oct 2016 18:08:54 -0700 Subject: [PATCH 26/74] Reverted test change --- src/compiler/checker.ts | 2 +- .../reference/bluebirdStaticThis.errors.txt | 188 +----------------- 2 files changed, 2 insertions(+), 188 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 273b5e06134..a1a8ae0da5c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -17893,7 +17893,7 @@ namespace ts { } function isNotOverload(declaration: Declaration): boolean { - return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) || + return (declaration.kind !== SyntaxKind.FunctionDeclaration && declaration.kind !== SyntaxKind.MethodDeclaration) || !!(declaration as FunctionDeclaration).body; } } diff --git a/tests/baselines/reference/bluebirdStaticThis.errors.txt b/tests/baselines/reference/bluebirdStaticThis.errors.txt index a20c7ace880..1c22a12c341 100644 --- a/tests/baselines/reference/bluebirdStaticThis.errors.txt +++ b/tests/baselines/reference/bluebirdStaticThis.errors.txt @@ -1,75 +1,13 @@ tests/cases/compiler/bluebirdStaticThis.ts(5,15): error TS2420: Class 'Promise' incorrectly implements interface 'Thenable'. Property 'then' is missing in type 'Promise'. -tests/cases/compiler/bluebirdStaticThis.ts(7,12): error TS2323: Cannot redeclare exported variable 'try'. -tests/cases/compiler/bluebirdStaticThis.ts(8,12): error TS2323: Cannot redeclare exported variable 'try'. -tests/cases/compiler/bluebirdStaticThis.ts(10,12): error TS2323: Cannot redeclare exported variable 'attempt'. -tests/cases/compiler/bluebirdStaticThis.ts(11,12): error TS2323: Cannot redeclare exported variable 'attempt'. -tests/cases/compiler/bluebirdStaticThis.ts(15,12): error TS2323: Cannot redeclare exported variable 'resolve'. -tests/cases/compiler/bluebirdStaticThis.ts(16,12): error TS2323: Cannot redeclare exported variable 'resolve'. -tests/cases/compiler/bluebirdStaticThis.ts(17,12): error TS2323: Cannot redeclare exported variable 'resolve'. -tests/cases/compiler/bluebirdStaticThis.ts(19,12): error TS2323: Cannot redeclare exported variable 'reject'. -tests/cases/compiler/bluebirdStaticThis.ts(20,12): error TS2323: Cannot redeclare exported variable 'reject'. tests/cases/compiler/bluebirdStaticThis.ts(22,51): error TS2694: Namespace 'Promise' has no exported member 'Resolver'. -tests/cases/compiler/bluebirdStaticThis.ts(24,12): error TS2323: Cannot redeclare exported variable 'cast'. -tests/cases/compiler/bluebirdStaticThis.ts(25,12): error TS2323: Cannot redeclare exported variable 'cast'. -tests/cases/compiler/bluebirdStaticThis.ts(33,12): error TS2323: Cannot redeclare exported variable 'delay'. -tests/cases/compiler/bluebirdStaticThis.ts(34,12): error TS2323: Cannot redeclare exported variable 'delay'. -tests/cases/compiler/bluebirdStaticThis.ts(35,12): error TS2323: Cannot redeclare exported variable 'delay'. -tests/cases/compiler/bluebirdStaticThis.ts(49,12): error TS2323: Cannot redeclare exported variable 'all'. -tests/cases/compiler/bluebirdStaticThis.ts(50,12): error TS2323: Cannot redeclare exported variable 'all'. -tests/cases/compiler/bluebirdStaticThis.ts(51,12): error TS2323: Cannot redeclare exported variable 'all'. -tests/cases/compiler/bluebirdStaticThis.ts(52,12): error TS2323: Cannot redeclare exported variable 'all'. -tests/cases/compiler/bluebirdStaticThis.ts(54,12): error TS2323: Cannot redeclare exported variable 'props'. -tests/cases/compiler/bluebirdStaticThis.ts(55,12): error TS2323: Cannot redeclare exported variable 'props'. -tests/cases/compiler/bluebirdStaticThis.ts(57,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(57,109): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. -tests/cases/compiler/bluebirdStaticThis.ts(58,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(58,91): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. -tests/cases/compiler/bluebirdStaticThis.ts(59,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(59,91): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. -tests/cases/compiler/bluebirdStaticThis.ts(60,12): error TS2323: Cannot redeclare exported variable 'settle'. tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace 'Promise' has no exported member 'Inspection'. -tests/cases/compiler/bluebirdStaticThis.ts(62,12): error TS2323: Cannot redeclare exported variable 'any'. -tests/cases/compiler/bluebirdStaticThis.ts(63,12): error TS2323: Cannot redeclare exported variable 'any'. -tests/cases/compiler/bluebirdStaticThis.ts(64,12): error TS2323: Cannot redeclare exported variable 'any'. -tests/cases/compiler/bluebirdStaticThis.ts(65,12): error TS2323: Cannot redeclare exported variable 'any'. -tests/cases/compiler/bluebirdStaticThis.ts(67,12): error TS2323: Cannot redeclare exported variable 'race'. -tests/cases/compiler/bluebirdStaticThis.ts(68,12): error TS2323: Cannot redeclare exported variable 'race'. -tests/cases/compiler/bluebirdStaticThis.ts(69,12): error TS2323: Cannot redeclare exported variable 'race'. -tests/cases/compiler/bluebirdStaticThis.ts(70,12): error TS2323: Cannot redeclare exported variable 'race'. -tests/cases/compiler/bluebirdStaticThis.ts(72,12): error TS2323: Cannot redeclare exported variable 'some'. -tests/cases/compiler/bluebirdStaticThis.ts(73,12): error TS2323: Cannot redeclare exported variable 'some'. -tests/cases/compiler/bluebirdStaticThis.ts(74,12): error TS2323: Cannot redeclare exported variable 'some'. -tests/cases/compiler/bluebirdStaticThis.ts(75,12): error TS2323: Cannot redeclare exported variable 'some'. -tests/cases/compiler/bluebirdStaticThis.ts(77,12): error TS2323: Cannot redeclare exported variable 'join'. -tests/cases/compiler/bluebirdStaticThis.ts(78,12): error TS2323: Cannot redeclare exported variable 'join'. -tests/cases/compiler/bluebirdStaticThis.ts(80,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(81,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(82,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(83,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(84,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(85,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(86,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(87,12): error TS2323: Cannot redeclare exported variable 'map'. -tests/cases/compiler/bluebirdStaticThis.ts(89,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(90,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(92,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(93,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(95,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(96,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(98,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(99,12): error TS2323: Cannot redeclare exported variable 'reduce'. -tests/cases/compiler/bluebirdStaticThis.ts(101,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(102,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(103,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(104,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(105,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(106,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(107,12): error TS2323: Cannot redeclare exported variable 'filter'. -tests/cases/compiler/bluebirdStaticThis.ts(108,12): error TS2323: Cannot redeclare exported variable 'filter'. -==== tests/cases/compiler/bluebirdStaticThis.ts (68 errors) ==== +==== tests/cases/compiler/bluebirdStaticThis.ts (6 errors) ==== // This version is reduced from the full d.ts by removing almost all the tests // and all the comments. // Then it adds explicit `this` arguments to the static members. @@ -80,48 +18,26 @@ tests/cases/compiler/bluebirdStaticThis.ts(108,12): error TS2323: Cannot redecla !!! error TS2420: Property 'then' is missing in type 'Promise'. constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable) => void, reject: (error: any) => void) => void); static try(dit: typeof Promise, fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'try'. static try(dit: typeof Promise, fn: () => R, args?: any[], ctx?: any): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'try'. static attempt(dit: typeof Promise, fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - ~~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'attempt'. static attempt(dit: typeof Promise, fn: () => R, args?: any[], ctx?: any): Promise; - ~~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'attempt'. static method(dit: typeof Promise, fn: Function): Function; static resolve(dit: typeof Promise): Promise; - ~~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'resolve'. static resolve(dit: typeof Promise, value: Promise.Thenable): Promise; - ~~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'resolve'. static resolve(dit: typeof Promise, value: R): Promise; - ~~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'resolve'. static reject(dit: typeof Promise, reason: any): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reject'. static reject(dit: typeof Promise, reason: any): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reject'. static defer(dit: typeof Promise): Promise.Resolver; ~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Resolver'. static cast(dit: typeof Promise, value: Promise.Thenable): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'cast'. static cast(dit: typeof Promise, value: R): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'cast'. static bind(dit: typeof Promise, thisArg: any): Promise; @@ -130,14 +46,8 @@ tests/cases/compiler/bluebirdStaticThis.ts(108,12): error TS2323: Cannot redecla static longStackTraces(dit: typeof Promise): void; static delay(dit: typeof Promise, value: Promise.Thenable, ms: number): Promise; - ~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'delay'. static delay(dit: typeof Promise, value: R, ms: number): Promise; - ~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'delay'. static delay(dit: typeof Promise, ms: number): Promise; - ~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'delay'. static promisify(dit: typeof Promise, nodeFunction: Function, receiver?: any): Function; @@ -152,169 +62,73 @@ tests/cases/compiler/bluebirdStaticThis.ts(108,12): error TS2323: Cannot redecla static onPossiblyUnhandledRejection(dit: typeof Promise, handler: (reason: any) => any): void; static all(dit: typeof Promise, values: Promise.Thenable[]>): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: Promise.Thenable[]): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'all'. static all(dit: typeof Promise, values: R[]): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'all'. static props(dit: typeof Promise, object: Promise): Promise; - ~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'props'. static props(dit: typeof Promise, object: Object): Promise; - ~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'props'. static settle(dit: typeof Promise, values: Promise.Thenable[]>): Promise[]>; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: Promise.Thenable): Promise[]>; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: Promise.Thenable[]): Promise[]>; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static settle(dit: typeof Promise, values: R[]): Promise[]>; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'settle'. ~~~~~~~~~~ !!! error TS2694: Namespace 'Promise' has no exported member 'Inspection'. static any(dit: typeof Promise, values: Promise.Thenable[]>): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: Promise.Thenable[]): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'any'. static any(dit: typeof Promise, values: R[]): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'any'. static race(dit: typeof Promise, values: Promise.Thenable[]>): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: Promise.Thenable): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: Promise.Thenable[]): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'race'. static race(dit: typeof Promise, values: R[]): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'race'. static some(dit: typeof Promise, values: Promise.Thenable[]>, count: number): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: Promise.Thenable, count: number): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: Promise.Thenable[], count: number): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'some'. static some(dit: typeof Promise, values: R[], count: number): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'some'. static join(dit: typeof Promise, ...values: Promise.Thenable[]): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'join'. static join(dit: typeof Promise, ...values: R[]): Promise; - ~~~~ -!!! error TS2323: Cannot redeclare exported variable 'join'. static map(dit: typeof Promise, values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static map(dit: typeof Promise, values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; - ~~~ -!!! error TS2323: Cannot redeclare exported variable 'map'. static reduce(dit: typeof Promise, values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static reduce(dit: typeof Promise, values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'reduce'. static filter(dit: typeof Promise, values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. static filter(dit: typeof Promise, values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; - ~~~~~~ -!!! error TS2323: Cannot redeclare exported variable 'filter'. } declare module Promise { From 38278ee0788bb8dc26b5052f103591b8fd0be0ab Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 11 Oct 2016 18:28:19 -0700 Subject: [PATCH 27/74] Fix typo --- src/compiler/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 36548334a62..47e533c9a6b 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -271,7 +271,7 @@ namespace ts { return result; } - // Maps from T to T and avoids allocation of all elements map to themselves + // Maps from T to T and avoids allocation if all elements map to themselves export function sameMap(array: T[], f: (x: T, i: number) => T): T[] { let result: T[]; if (array) { From f42c79150253b003f6f7e38011d57cf0af77df10 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Wed, 12 Oct 2016 21:28:11 +0200 Subject: [PATCH 28/74] Don't use es8. Add es2016 target. Rename es7 to es2016. Update getDefaultLibFileName for new targets. --- Jakefile.js | 4 +- src/compiler/binder.ts | 4 +- src/compiler/commandLineParser.ts | 2 +- src/compiler/emitter.ts | 4 +- src/compiler/transformer.ts | 7 +-- .../transformers/{es7.ts => es2016.ts} | 10 ++-- src/compiler/transformers/ts.ts | 3 +- src/compiler/tsconfig.json | 2 +- src/compiler/types.ts | 53 ++++++++++--------- src/compiler/utilities.ts | 10 +++- src/harness/harness.ts | 10 +++- src/harness/tsconfig.json | 2 +- src/harness/unittests/commandLineParsing.ts | 2 +- .../convertCompilerOptionsFromJson.ts | 2 +- src/services/tsconfig.json | 2 +- .../{es8-async.ts => es2017basicAsync.ts} | 2 +- 16 files changed, 69 insertions(+), 50 deletions(-) rename src/compiler/transformers/{es7.ts => es2016.ts} (91%) rename tests/cases/compiler/{es8-async.ts => es2017basicAsync.ts} (97%) diff --git a/Jakefile.js b/Jakefile.js index 64a8553ef39..ecbd0ae2be2 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -74,7 +74,7 @@ var compilerSources = [ "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", - "transformers/es7.ts", + "transformers/es2016.ts", "transformers/generators.ts", "transformers/es6.ts", "transformer.ts", @@ -108,7 +108,7 @@ var servicesSources = [ "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", - "transformers/es7.ts", + "transformers/es2016.ts", "transformers/generators.ts", "transformers/es6.ts", "transformer.ts", diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 2fe7d30ab56..ce482dcdfd9 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2411,8 +2411,8 @@ namespace ts { } else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken || operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) { - // Exponentiation is ES7 syntax. - transformFlags |= TransformFlags.AssertES7; + // Exponentiation is ES2016 syntax. + transformFlags |= TransformFlags.AssertES2016; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 16d338cac6a..b77f6898b3c 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -262,8 +262,8 @@ namespace ts { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, "es6": ScriptTarget.ES6, - "es8": ScriptTarget.ES8, "es2015": ScriptTarget.ES2015, + "es2016": ScriptTarget.ES2016, "es2017": ScriptTarget.ES2017, }), description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES2015, diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index b0e31278ff0..a3f69e2fd4b 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2194,8 +2194,8 @@ const _super = (function (geti, seti) { // Only emit __awaiter function when target ES5/ES6. // Only emit __generator function when target ES5. - // For target ES8 and above, we can emit async/await as is. - if ((languageVersion < ScriptTarget.ES8) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) { + // For target ES2017 and above, we can emit async/await as is. + if ((languageVersion < ScriptTarget.ES2017) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) { writeLines(awaiterHelper); if (languageVersion < ScriptTarget.ES6) { writeLines(generatorHelper); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 415a9ecd1d7..9e548268052 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -1,7 +1,7 @@ /// /// /// -/// +/// /// /// /// @@ -115,8 +115,9 @@ namespace ts { transformers.push(transformJsx); } - if (languageVersion < ScriptTarget.ES8) { - transformers.push(transformES7); + + if (languageVersion < ScriptTarget.ES2016) { + transformers.push(transformES2016); } if (languageVersion < ScriptTarget.ES6) { diff --git a/src/compiler/transformers/es7.ts b/src/compiler/transformers/es2016.ts similarity index 91% rename from src/compiler/transformers/es7.ts rename to src/compiler/transformers/es2016.ts index 4d5e96134c4..fba1d300903 100644 --- a/src/compiler/transformers/es7.ts +++ b/src/compiler/transformers/es2016.ts @@ -3,7 +3,7 @@ /*@internal*/ namespace ts { - export function transformES7(context: TransformationContext) { + export function transformES2016(context: TransformationContext) { const { hoistVariableDeclaration } = context; return transformSourceFile; @@ -17,10 +17,10 @@ namespace ts { } function visitor(node: Node): VisitResult { - if (node.transformFlags & TransformFlags.ES7) { + if (node.transformFlags & TransformFlags.ES2016) { return visitorWorker(node); } - else if (node.transformFlags & TransformFlags.ContainsES7) { + else if (node.transformFlags & TransformFlags.ContainsES2016) { return visitEachChild(node, visitor, context); } else { @@ -40,7 +40,7 @@ namespace ts { } function visitBinaryExpression(node: BinaryExpression): Expression { - // We are here because ES7 adds support for the exponentiation operator. + // We are here because ES2016 adds support for the exponentiation operator. const left = visitNode(node.left, visitor, isExpression); const right = visitNode(node.right, visitor, isExpression); if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) { @@ -98,4 +98,4 @@ namespace ts { } } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 40b9e7f64e1..c98fbfc26cc 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -241,8 +241,7 @@ namespace ts { return currentNamespace ? undefined : node; case SyntaxKind.AsyncKeyword: - // Async keyword is not elided for target ES8 - return languageVersion < ScriptTarget.ES8 ? undefined : node; + return node; case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index f128c994af1..fc0f016f664 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -24,7 +24,7 @@ "visitor.ts", "transformers/ts.ts", "transformers/jsx.ts", - "transformers/es7.ts", + "transformers/es2016.ts", "transformers/es6.ts", "transformers/generators.ts", "transformers/destructuring.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5b193beb155..b89887cafa0 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2831,10 +2831,10 @@ namespace ts { ES3 = 0, ES5 = 1, ES6 = 2, - ES8 = 3, ES2015 = ES6, - ES2017 = ES8, - Latest = ES8, + ES2016 = 3, + ES2017 = 4, + Latest = ES2017, } export const enum LanguageVariant { @@ -3119,29 +3119,31 @@ namespace ts { ContainsTypeScript = 1 << 1, Jsx = 1 << 2, ContainsJsx = 1 << 3, - ES7 = 1 << 4, - ContainsES7 = 1 << 5, - ES6 = 1 << 6, - ContainsES6 = 1 << 7, - DestructuringAssignment = 1 << 8, - Generator = 1 << 9, - ContainsGenerator = 1 << 10, + ES2017 = 1 << 4, + ContainsES2017 = 1 << 5, + ES2016 = 1 << 6, + ContainsES2016 = 1 << 7, + ES6 = 1 << 8, + ContainsES6 = 1 << 9, + DestructuringAssignment = 1 << 10, + Generator = 1 << 11, + ContainsGenerator = 1 << 12, // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsDecorators = 1 << 11, - ContainsPropertyInitializer = 1 << 12, - ContainsLexicalThis = 1 << 13, - ContainsCapturedLexicalThis = 1 << 14, - ContainsLexicalThisInComputedPropertyName = 1 << 15, - ContainsDefaultValueAssignments = 1 << 16, - ContainsParameterPropertyAssignments = 1 << 17, - ContainsSpreadElementExpression = 1 << 18, - ContainsComputedPropertyName = 1 << 19, - ContainsBlockScopedBinding = 1 << 20, - ContainsBindingPattern = 1 << 21, - ContainsYield = 1 << 22, - ContainsHoistedDeclarationOrCompletion = 1 << 23, + ContainsDecorators = 1 << 13, + ContainsPropertyInitializer = 1 << 14, + ContainsLexicalThis = 1 << 15, + ContainsCapturedLexicalThis = 1 << 16, + ContainsLexicalThisInComputedPropertyName = 1 << 17, + ContainsDefaultValueAssignments = 1 << 18, + ContainsParameterPropertyAssignments = 1 << 19, + ContainsSpreadElementExpression = 1 << 20, + ContainsComputedPropertyName = 1 << 21, + ContainsBlockScopedBinding = 1 << 22, + ContainsBindingPattern = 1 << 23, + ContainsYield = 1 << 24, + ContainsHoistedDeclarationOrCompletion = 1 << 25, HasComputedFlags = 1 << 29, // Transform flags have been computed. @@ -3149,14 +3151,15 @@ namespace ts { // - Bitmasks that are used to assert facts about the syntax of a node and its subtree. AssertTypeScript = TypeScript | ContainsTypeScript, AssertJsx = Jsx | ContainsJsx, - AssertES7 = ES7 | ContainsES7, + AssertES2017 = ES2017 | ContainsES2017, + AssertES2016 = ES2016 | ContainsES2016, AssertES6 = ES6 | ContainsES6, AssertGenerator = Generator | ContainsGenerator, // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - NodeExcludes = TypeScript | Jsx | ES7 | ES6 | DestructuringAssignment | Generator | HasComputedFlags, + NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES6 | DestructuringAssignment | Generator | HasComputedFlags, ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1a4d95feca5..b661cefb5a6 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4141,7 +4141,15 @@ namespace ts { namespace ts { export function getDefaultLibFileName(options: CompilerOptions): string { - return options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"; + switch (options.target) { + case ScriptTarget.ES2016: + return "lib.es2016.d.ts"; + case ScriptTarget.ES6: + return "lib.es2015.d.ts"; + + default: + return "lib.d.ts"; + } } export function textSpanEnd(span: TextSpan) { diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 7c82aeece78..b8703ebc8f2 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -941,7 +941,15 @@ namespace Harness { } export function getDefaultLibFileName(options: ts.CompilerOptions): string { - return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName; + switch (options.target) { + case ts.ScriptTarget.ES2016: + return "lib.es2016.d.ts"; + case ts.ScriptTarget.ES6: + return es2015DefaultLibFileName; + + default: + return defaultLibFileName; + } } // Cache these between executions so we don't have to re-parse them for every test diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index f9d302ace81..aa46c8ee8d0 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -26,7 +26,7 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", - "../compiler/transformers/es7.ts", + "../compiler/transformers/es2016.ts", "../compiler/transformers/es6.ts", "../compiler/transformers/generators.ts", "../compiler/transformers/destructuring.ts", diff --git a/src/harness/unittests/commandLineParsing.ts b/src/harness/unittests/commandLineParsing.ts index 42fc242f08e..cd9bf88df60 100644 --- a/src/harness/unittests/commandLineParsing.ts +++ b/src/harness/unittests/commandLineParsing.ts @@ -165,7 +165,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es8', 'es2015', 'es2017'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'", category: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: ts.Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/harness/unittests/convertCompilerOptionsFromJson.ts b/src/harness/unittests/convertCompilerOptionsFromJson.ts index db3d6cfc102..13f54e369ed 100644 --- a/src/harness/unittests/convertCompilerOptionsFromJson.ts +++ b/src/harness/unittests/convertCompilerOptionsFromJson.ts @@ -176,7 +176,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es8', 'es2015', 'es2017'", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017'", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 58312c6f38f..e759ab35b48 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -25,7 +25,7 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", - "../compiler/transformers/es7.ts", + "../compiler/transformers/es2016.ts", "../compiler/transformers/es6.ts", "../compiler/transformers/generators.ts", "../compiler/transformers/destructuring.ts", diff --git a/tests/cases/compiler/es8-async.ts b/tests/cases/compiler/es2017basicAsync.ts similarity index 97% rename from tests/cases/compiler/es8-async.ts rename to tests/cases/compiler/es2017basicAsync.ts index 0ceb6e397e5..b13a5d29bc0 100644 --- a/tests/cases/compiler/es8-async.ts +++ b/tests/cases/compiler/es2017basicAsync.ts @@ -1,4 +1,4 @@ -// @target: es8 +// @target: es2017 // @lib: es2017 // @noEmitHelpers: true From 994dae70f065edd683b1c943fbd3c911c83dad57 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 12 Oct 2016 12:28:15 -0700 Subject: [PATCH 29/74] Move import/export elision to ts transform --- src/compiler/core.ts | 13 +- src/compiler/factory.ts | 26 +-- src/compiler/transformers/module/es6.ts | 115 +----------- src/compiler/transformers/module/module.ts | 43 +++-- src/compiler/transformers/module/system.ts | 31 ++-- src/compiler/transformers/ts.ts | 165 +++++++++++++++++- src/compiler/utilities.ts | 29 ++- .../reference/declareModifierOnImport1.js | 1 + ...ndingFollowedWithNamespaceBinding1InEs5.js | 2 +- ...FollowedWithNamespaceBinding1WithExport.js | 1 - ...tBindingFollowedWithNamespaceBindingDts.js | 2 +- ...BindingFollowedWithNamespaceBindingDts1.js | 1 - ...indingFollowedWithNamespaceBindingInEs5.js | 2 +- ...gFollowedWithNamespaceBindingWithExport.js | 2 +- .../importDeclWithDeclareModifier.js | 1 + ...ler-options module-kind is out-of-range.js | 1 + ...r-options target-script is out-of-range.js | 1 + .../reference/typeAliasDeclarationEmit.js | 1 + .../reference/typeAliasDeclarationEmit2.js | 1 + 19 files changed, 251 insertions(+), 187 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 7c68306211a..4fb0b4d651d 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -399,6 +399,17 @@ namespace ts { return result; } + export function some(array: T[], predicate?: (value: T) => boolean): boolean { + if (array) { + for (const v of array) { + if (!predicate || predicate(v)) { + return true; + } + } + } + return false; + } + export function concatenate(array1: T[], array2: T[]): T[] { if (!array2 || !array2.length) return array1; if (!array1 || !array1.length) return array2; @@ -1177,7 +1188,7 @@ namespace ts { /** * Returns the path except for its basename. Eg: - * + * * /path/to/file.ext -> /path/to */ export function getDirectoryPath(path: Path): Path; diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 97a36f46b13..582f82315d2 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -2206,7 +2206,7 @@ namespace ts { * @param visitor: Optional callback used to visit any custom prologue directives. */ export function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number { - Debug.assert(target.length === 0, "PrologueDirectives should be at the first statement in the target statements array"); + Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array"); let foundUseStrict = false; let statementOffset = 0; const numStatements = source.length; @@ -2219,16 +2219,20 @@ namespace ts { target.push(statement); } else { - if (ensureUseStrict && !foundUseStrict) { - target.push(startOnNewLine(createStatement(createLiteral("use strict")))); - foundUseStrict = true; - } - if (getEmitFlags(statement) & EmitFlags.CustomPrologue) { - target.push(visitor ? visitNode(statement, visitor, isStatement) : statement); - } - else { - break; - } + break; + } + statementOffset++; + } + if (ensureUseStrict && !foundUseStrict) { + target.push(startOnNewLine(createStatement(createLiteral("use strict")))); + } + while (statementOffset < numStatements) { + const statement = source[statementOffset]; + if (getEmitFlags(statement) & EmitFlags.CustomPrologue) { + target.push(visitor ? visitNode(statement, visitor, isStatement) : statement); + } + else { + break; } statementOffset++; } diff --git a/src/compiler/transformers/module/es6.ts b/src/compiler/transformers/module/es6.ts index 09a2890727c..9eac37bee27 100644 --- a/src/compiler/transformers/module/es6.ts +++ b/src/compiler/transformers/module/es6.ts @@ -5,10 +5,6 @@ namespace ts { export function transformES6Module(context: TransformationContext) { const compilerOptions = context.getCompilerOptions(); - const resolver = context.getEmitResolver(); - - let currentSourceFile: SourceFile; - return transformSourceFile; function transformSourceFile(node: SourceFile) { @@ -17,128 +13,31 @@ namespace ts { } if (isExternalModule(node) || compilerOptions.isolatedModules) { - currentSourceFile = node; return visitEachChild(node, visitor, context); } + return node; } function visitor(node: Node): VisitResult { switch (node.kind) { - case SyntaxKind.ImportDeclaration: - return visitImportDeclaration(node); case SyntaxKind.ImportEqualsDeclaration: return visitImportEqualsDeclaration(node); - case SyntaxKind.ImportClause: - return visitImportClause(node); - case SyntaxKind.NamedImports: - case SyntaxKind.NamespaceImport: - return visitNamedBindings(node); - case SyntaxKind.ImportSpecifier: - return visitImportSpecifier(node); case SyntaxKind.ExportAssignment: return visitExportAssignment(node); - case SyntaxKind.ExportDeclaration: - return visitExportDeclaration(node); - case SyntaxKind.NamedExports: - return visitNamedExports(node); - case SyntaxKind.ExportSpecifier: - return visitExportSpecifier(node); } return node; } - function visitExportAssignment(node: ExportAssignment): ExportAssignment { - if (node.isExportEquals) { - return undefined; // do not emit export equals for ES6 - } - const original = getOriginalNode(node); - return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; + function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { + // Elide `import=` as it is not legal with --module ES6 + return undefined; } - function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration { - if (!node.exportClause) { - return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; - } - if (!resolver.isValueAliasDeclaration(node)) { - return undefined; - } - const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true); - if (node.exportClause === newExportClause) { - return node; - } - return newExportClause - ? createExportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - newExportClause, - node.moduleSpecifier) - : undefined; - } - - function visitNamedExports(node: NamedExports): NamedExports { - const newExports = visitNodes(node.elements, visitor, isExportSpecifier); - if (node.elements === newExports) { - return node; - } - return newExports.length ? createNamedExports(newExports) : undefined; - } - - function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier { - return resolver.isValueAliasDeclaration(node) ? node : undefined; - } - - function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration { - return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - - function visitImportDeclaration(node: ImportDeclaration) { - if (node.importClause) { - const newImportClause = visitNode(node.importClause, visitor, isImportClause); - if (!newImportClause.name && !newImportClause.namedBindings) { - return undefined; - } - else if (newImportClause !== node.importClause) { - return createImportDeclaration( - /*decorators*/ undefined, - /*modifiers*/ undefined, - newImportClause, - node.moduleSpecifier); - } - } - return node; - } - - function visitImportClause(node: ImportClause): ImportClause { - let newDefaultImport = node.name; - if (!resolver.isReferencedAliasDeclaration(node)) { - newDefaultImport = undefined; - } - const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true); - return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings - ? createImportClause(newDefaultImport, newNamedBindings) - : node; - } - - function visitNamedBindings(node: NamedImportBindings): VisitResult { - if (node.kind === SyntaxKind.NamespaceImport) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; - } - else { - const newNamedImportElements = visitNodes((node).elements, visitor, isImportSpecifier); - if (!newNamedImportElements || newNamedImportElements.length == 0) { - return undefined; - } - if (newNamedImportElements === (node).elements) { - return node; - } - return createNamedImports(newNamedImportElements); - } - } - - function visitImportSpecifier(node: ImportSpecifier) { - return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + function visitExportAssignment(node: ExportAssignment): VisitResult { + // Elide `export=` as it is not legal with --module ES6 + return node.isExportEquals ? undefined : node; } } } \ No newline at end of file diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 516ed5433b8..94852616037 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -59,7 +59,7 @@ namespace ts { currentSourceFile = node; // Collect information about the external module. - ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver)); + ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node)); // Perform the transformation. const transformModule = transformModuleDelegates[moduleKind] || transformModuleDelegates[ModuleKind.None]; @@ -228,7 +228,7 @@ namespace ts { } function addExportEqualsIfNeeded(statements: Statement[], emitAsReturn: boolean) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { + if (exportEquals) { if (emitAsReturn) { const statement = createReturn( exportEquals.expression, @@ -461,23 +461,21 @@ namespace ts { ); } for (const specifier of node.exportClause.elements) { - if (resolver.isValueAliasDeclaration(specifier)) { - const exportedValue = createPropertyAccess( - generatedName, - specifier.propertyName || specifier.name - ); - statements.push( - createStatement( - createExportAssignment(specifier.name, exportedValue), - /*location*/ specifier - ) - ); - } + const exportedValue = createPropertyAccess( + generatedName, + specifier.propertyName || specifier.name + ); + statements.push( + createStatement( + createExportAssignment(specifier.name, exportedValue), + /*location*/ specifier + ) + ); } return singleOrMany(statements); } - else if (resolver.moduleExportsSomeValue(node.moduleSpecifier)) { + else { // export * from "mod"; return createStatement( createCall( @@ -495,15 +493,14 @@ namespace ts { } function visitExportAssignment(node: ExportAssignment): VisitResult { - if (!node.isExportEquals) { - if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - const statements: Statement[] = []; - addExportDefault(statements, node.expression, /*location*/ node); - return statements; - } + if (node.isExportEquals) { + // Elide as `export=` is handled in addExportEqualsIfNeeded + return undefined; } - return undefined; + const statements: Statement[] = []; + addExportDefault(statements, node.expression, /*location*/ node); + return statements; } function addExportDefault(statements: Statement[], expression: Expression, location: TextRange): void { @@ -568,7 +565,7 @@ namespace ts { } function collectExportMembers(names: Identifier[], node: Node): Identifier[] { - if (isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && isDeclaration(node)) { + if (isAliasSymbolDeclaration(node) && isDeclaration(node)) { const name = node.name; if (isIdentifier(name)) { names.push(name); diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 303c0e1bb96..0bb188eb390 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -91,7 +91,7 @@ namespace ts { Debug.assert(!exportFunctionForFile); // Collect information about the external module and dependency groups. - ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node, resolver)); + ({ externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues } = collectExternalModuleInfo(node)); // Make sure that the name of the 'exports' function does not conflict with // existing identifiers. @@ -573,28 +573,23 @@ namespace ts { } function visitExportSpecifier(specifier: ExportSpecifier): Statement { - if (resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) - || resolver.isValueAliasDeclaration(specifier)) { - recordExportName(specifier.name); - return createExportStatement( - specifier.name, - specifier.propertyName || specifier.name - ); - } - return undefined; + recordExportName(specifier.name); + return createExportStatement( + specifier.name, + specifier.propertyName || specifier.name + ); } function visitExportAssignment(node: ExportAssignment): Statement { - if (!node.isExportEquals) { - if (nodeIsSynthesized(node) || resolver.isValueAliasDeclaration(node)) { - return createExportStatement( - createLiteral("default"), - node.expression - ); - } + if (node.isExportEquals) { + // Elide `export=` as it is illegal in a SystemJS module. + return undefined; } - return undefined; + return createExportStatement( + createLiteral("default"), + node.expression + ); } /** diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 41f03d20f2e..3c87036621b 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -147,6 +147,35 @@ namespace ts { return node; } + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitor(node: Node): VisitResult { + return saveStateAndInvoke(node, sourceElementVisitorWorker); + } + + /** + * Specialized visitor that visits the immediate children of a SourceFile. + * + * @param node The node to visit. + */ + function sourceElementVisitorWorker(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: + return visitImportDeclaration(node); + case SyntaxKind.ImportEqualsDeclaration: + return visitImportEqualsDeclaration(node); + case SyntaxKind.ExportAssignment: + return visitExportAssignment(node); + case SyntaxKind.ExportDeclaration: + return visitExportDeclaration(node); + default: + return visitorWorker(node); + } + } + /** * Specialized visitor that visits the immediate children of a namespace. * @@ -457,7 +486,7 @@ namespace ts { statements.push(externalHelpersModuleImport); currentSourceFileExternalHelpersModuleName = externalHelpersModuleName; - addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); + addRange(statements, visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset)); addRange(statements, endLexicalEnvironment()); currentSourceFileExternalHelpersModuleName = undefined; @@ -465,7 +494,7 @@ namespace ts { node.externalHelpersModuleName = externalHelpersModuleName; } else { - node = visitEachChild(node, visitor, context); + node = visitEachChild(node, sourceElementVisitor, context); } setEmitFlags(node, EmitFlags.EmitEmitHelpers | getEmitFlags(node)); @@ -2993,6 +3022,133 @@ namespace ts { } } + /** + * Visits an import declaration, eliding it if it is not referenced. + * + * @param node The import declaration node. + */ + function visitImportDeclaration(node: ImportDeclaration): VisitResult { + if (!node.importClause) { + // Do not elide a side-effect only import declaration. + // import "foo"; + return node; + } + + // Elide the declaration if the import clause was elided. + const importClause = visitNode(node.importClause, visitImportClause, isImportClause, /*optional*/ true); + return importClause + ? updateImportDeclaration( + node, + /*decorators*/ undefined, + /*modifiers*/ undefined, + importClause, + node.moduleSpecifier) + : undefined; + } + + /** + * Visits an import clause, eliding it if it is not referenced. + * + * @param node The import clause node. + */ + function visitImportClause(node: ImportClause): VisitResult { + // Elide the import clause if we elide both its name and its named bindings. + const name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined; + const namedBindings = visitNode(node.namedBindings, visitNamedImportBindings, isNamedImportBindings, /*optional*/ true); + return (name || namedBindings) ? updateImportClause(node, name, namedBindings) : undefined; + } + + /** + * Visits named import bindings, eliding it if it is not referenced. + * + * @param node The named import bindings node. + */ + function visitNamedImportBindings(node: NamedImportBindings): VisitResult { + if (node.kind === SyntaxKind.NamespaceImport) { + // Elide a namespace import if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + else { + // Elide named imports if all of its import specifiers are elided. + const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier); + return some(elements) ? updateNamedImports(node, elements) : undefined; + } + } + + /** + * Visits an import specifier, eliding it if it is not referenced. + * + * @param node The import specifier node. + */ + function visitImportSpecifier(node: ImportSpecifier): VisitResult { + // Elide an import specifier if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) ? node : undefined; + } + + /** + * Visits an export assignment, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export assignment node. + */ + function visitExportAssignment(node: ExportAssignment): VisitResult { + // Elide the export assignment if it does not reference a value. + return resolver.isValueAliasDeclaration(node) + ? visitEachChild(node, visitor, context) + : undefined; + } + + /** + * Visits an export declaration, eliding it if it does not contain a clause that resolves + * to a value. + * + * @param node The export declaration node. + */ + function visitExportDeclaration(node: ExportDeclaration): VisitResult { + if (!node.exportClause) { + // Elide a star export if the module it references does not export a value. + return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; + } + + if (!resolver.isValueAliasDeclaration(node)) { + // Elide the export declaration if it does not export a value. + return undefined; + } + + // Elide the export declaration if all of its named exports are elided. + const exportClause = visitNode(node.exportClause, visitNamedExports, isNamedExports, /*optional*/ true); + return exportClause + ? updateExportDeclaration( + node, + /*decorators*/ undefined, + /*modifiers*/ undefined, + exportClause, + node.moduleSpecifier) + : undefined; + } + + /** + * Visits named exports, eliding it if it does not contain an export specifier that + * resolves to a value. + * + * @param node The named exports node. + */ + function visitNamedExports(node: NamedExports): VisitResult { + // Elide the named exports if all of its export specifiers were elided. + const elements = visitNodes(node.elements, visitExportSpecifier, isExportSpecifier); + return some(elements) ? updateNamedExports(node, elements) : undefined; + } + + /** + * Visits an export specifier, eliding it if it does not resolve to a value. + * + * @param node The export specifier node. + */ + function visitExportSpecifier(node: ExportSpecifier): VisitResult { + // Elide an export specifier if it does not reference a value. + return resolver.isValueAliasDeclaration(node) ? node : undefined; + } + /** * Determines whether to emit an import equals declaration. * @@ -3014,7 +3170,10 @@ namespace ts { */ function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult { if (isExternalModuleImportEqualsDeclaration(node)) { - return visitEachChild(node, visitor, context); + // Elide external module `import=` if it is not referenced. + return resolver.isReferencedAliasDeclaration(node) + ? visitEachChild(node, visitor, context) + : undefined; } if (!shouldEmitImportEqualsDeclaration(node)) { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 558015bb0e3..eee79894a02 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -3496,7 +3496,7 @@ namespace ts { return positionIsSynthesized(range.pos) ? -1 : skipTrivia(sourceFile.text, range.pos); } - export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver) { + export function collectExternalModuleInfo(sourceFile: SourceFile) { const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; const exportSpecifiers = createMap(); let exportEquals: ExportAssignment = undefined; @@ -3504,19 +3504,16 @@ namespace ts { for (const node of sourceFile.statements) { switch (node.kind) { case SyntaxKind.ImportDeclaration: - if (!(node).importClause || - resolver.isReferencedAliasDeclaration((node).importClause, /*checkChildren*/ true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } + // import "mod" + // import x from "mod" + // import * as x from "mod" + // import { x, y } from "mod" + externalImports.push(node); break; case SyntaxKind.ImportEqualsDeclaration: - if ((node).moduleReference.kind === SyntaxKind.ExternalModuleReference && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced + if ((node).moduleReference.kind === SyntaxKind.ExternalModuleReference) { + // import x = require("mod") externalImports.push(node); } break; @@ -3525,13 +3522,11 @@ namespace ts { if ((node).moduleSpecifier) { if (!(node).exportClause) { // export * from "mod" - if (resolver.moduleExportsSomeValue((node).moduleSpecifier)) { - externalImports.push(node); - hasExportStarsToExportValues = true; - } + externalImports.push(node); + hasExportStarsToExportValues = true; } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol + else { + // export { x, y } from "mod" externalImports.push(node); } } diff --git a/tests/baselines/reference/declareModifierOnImport1.js b/tests/baselines/reference/declareModifierOnImport1.js index 510407b4deb..3dc3601d470 100644 --- a/tests/baselines/reference/declareModifierOnImport1.js +++ b/tests/baselines/reference/declareModifierOnImport1.js @@ -2,3 +2,4 @@ declare import a = b; //// [declareModifierOnImport1.js] +var a = b; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js index d62cfbc2872..0a0e028b696 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1InEs5.js @@ -16,7 +16,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.default = a; //// [es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_1.js] "use strict"; -var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"), nameSpaceBinding = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1; +var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"); var x = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1.default; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js index c19f68463fa..5f2cb4e97e0 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBinding1WithExport.js @@ -19,7 +19,6 @@ define(["require", "exports"], function (require, exports) { //// [client.js] define(["require", "exports", "server"], function (require, exports, server_1) { "use strict"; - var nameSpaceBinding = server_1; exports.x = server_1.default; }); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js index 20abd2e6132..60bdc654842 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts.js @@ -18,7 +18,7 @@ var a = (function () { exports.a = a; //// [client.js] "use strict"; -var server_1 = require("./server"), nameSpaceBinding = server_1; +var nameSpaceBinding = require("./server"); exports.x = new nameSpaceBinding.a(); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js index 5a2f1f35290..8752157eddd 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingDts1.js @@ -23,7 +23,6 @@ define(["require", "exports"], function (require, exports) { //// [client.js] define(["require", "exports", "server"], function (require, exports, server_1) { "use strict"; - var nameSpaceBinding = server_1; exports.x = new server_1.default(); }); diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js index 2639291d854..9d11e154755 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5.js @@ -13,7 +13,7 @@ var x: number = nameSpaceBinding.a; exports.a = 10; //// [es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_1.js] "use strict"; -var es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1 = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"), nameSpaceBinding = es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0_1; +var nameSpaceBinding = require("./es6ImportDefaultBindingFollowedWithNamespaceBindingInEs5_0"); var x = nameSpaceBinding.a; diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js index f417a086df7..e16ebf99957 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamespaceBindingWithExport.js @@ -13,7 +13,7 @@ export var x: number = nameSpaceBinding.a; exports.a = 10; //// [client.js] "use strict"; -var server_1 = require("./server"), nameSpaceBinding = server_1; +var nameSpaceBinding = require("./server"); exports.x = nameSpaceBinding.a; diff --git a/tests/baselines/reference/importDeclWithDeclareModifier.js b/tests/baselines/reference/importDeclWithDeclareModifier.js index e5267678a49..7c3d3782934 100644 --- a/tests/baselines/reference/importDeclWithDeclareModifier.js +++ b/tests/baselines/reference/importDeclWithDeclareModifier.js @@ -9,4 +9,5 @@ var b: a; //// [importDeclWithDeclareModifier.js] "use strict"; +exports.a = x.c; var b; diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js index c7570e81192..1ceb1bcd146 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js +++ b/tests/baselines/reference/transpile/Report an error when compiler-options module-kind is out-of-range.js @@ -1 +1,2 @@ +"use strict"; //# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js index c7570e81192..1ceb1bcd146 100644 --- a/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js +++ b/tests/baselines/reference/transpile/Report an error when compiler-options target-script is out-of-range.js @@ -1 +1,2 @@ +"use strict"; //# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/tests/baselines/reference/typeAliasDeclarationEmit.js b/tests/baselines/reference/typeAliasDeclarationEmit.js index 6e82fe4b07d..1f72e1d1b00 100644 --- a/tests/baselines/reference/typeAliasDeclarationEmit.js +++ b/tests/baselines/reference/typeAliasDeclarationEmit.js @@ -6,6 +6,7 @@ export type CallbackArray = () => T; //// [typeAliasDeclarationEmit.js] define(["require", "exports"], function (require, exports) { + "use strict"; }); diff --git a/tests/baselines/reference/typeAliasDeclarationEmit2.js b/tests/baselines/reference/typeAliasDeclarationEmit2.js index 4bb1bd3efd9..b94eb56a2a2 100644 --- a/tests/baselines/reference/typeAliasDeclarationEmit2.js +++ b/tests/baselines/reference/typeAliasDeclarationEmit2.js @@ -4,6 +4,7 @@ export type A = { value: a }; //// [typeAliasDeclarationEmit2.js] define(["require", "exports"], function (require, exports) { + "use strict"; }); From 5d52c9fd3b28b25d2752b5157bc51453187065c9 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Wed, 12 Oct 2016 21:34:00 +0200 Subject: [PATCH 30/74] Move async/await into separate es2017 transformer --- Jakefile.js | 2 + src/compiler/binder.ts | 24 +- src/compiler/transformer.ts | 4 + src/compiler/transformers/es2017.ts | 544 ++++++++++++++++++ src/compiler/transformers/module/module.ts | 4 +- src/compiler/transformers/module/system.ts | 6 +- src/compiler/transformers/ts.ts | 238 +------- src/compiler/tsconfig.json | 1 + src/compiler/utilities.ts | 2 + src/harness/harness.ts | 2 + src/harness/tsconfig.json | 1 + src/services/tsconfig.json | 1 + .../{es8-async.js => es2017basicAsync.js} | 4 +- ...async.symbols => es2017basicAsync.symbols} | 22 +- ...es8-async.types => es2017basicAsync.types} | 2 +- 15 files changed, 614 insertions(+), 243 deletions(-) create mode 100644 src/compiler/transformers/es2017.ts rename tests/baselines/reference/{es8-async.js => es2017basicAsync.js} (94%) rename tests/baselines/reference/{es8-async.symbols => es2017basicAsync.symbols} (78%) rename tests/baselines/reference/{es8-async.types => es2017basicAsync.types} (94%) diff --git a/Jakefile.js b/Jakefile.js index ecbd0ae2be2..8d46368653c 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -74,6 +74,7 @@ var compilerSources = [ "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", + "transformers/es2017.ts", "transformers/es2016.ts", "transformers/generators.ts", "transformers/es6.ts", @@ -108,6 +109,7 @@ var servicesSources = [ "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", + "transformers/es2017.ts", "transformers/es2016.ts", "transformers/generators.ts", "transformers/es6.ts", diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index ce482dcdfd9..4edbb5d9e1a 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2555,6 +2555,11 @@ namespace ts { // extends clause of a class. let transformFlags = subtreeFlags | TransformFlags.AssertES6; + // propagate ES2017 + if (node.expression.transformFlags & TransformFlags.ContainsES2017) { + transformFlags |= TransformFlags.ContainsES2017; + } + // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { @@ -2595,6 +2600,11 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript; } + // Async MethodDeclaration is ES2017 + if (modifierFlags & ModifierFlags.Async) { + transformFlags |= TransformFlags.AssertES2017; + } + // Currently, we only support generators that were originally async function bodies. if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; @@ -2656,7 +2666,7 @@ namespace ts { // If a FunctionDeclaration is async, then it is TypeScript syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the @@ -2687,7 +2697,7 @@ namespace ts { // An async function expression is TypeScript syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; } // If a FunctionExpression's subtree has marked the container as needing to capture the @@ -2717,7 +2727,7 @@ namespace ts { // An async arrow function is TypeScript syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. @@ -2856,14 +2866,18 @@ namespace ts { let excludeFlags = TransformFlags.NodeExcludes; switch (kind) { + case SyntaxKind.AsyncKeyword: + case SyntaxKind.AwaitExpression: + // Typescript async/await are ES2017 features + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; + break; + case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.DeclareKeyword: - case SyntaxKind.AsyncKeyword: case SyntaxKind.ConstKeyword: - case SyntaxKind.AwaitExpression: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMember: case SyntaxKind.TypeAssertionExpression: diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 9e548268052..55b83ea669d 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -1,6 +1,7 @@ /// /// /// +/// /// /// /// @@ -115,6 +116,9 @@ namespace ts { transformers.push(transformJsx); } + if (languageVersion < ScriptTarget.ES2017) { + transformers.push(transformES2017); + } if (languageVersion < ScriptTarget.ES2016) { transformers.push(transformES2016); diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts new file mode 100644 index 00000000000..33376bbceb1 --- /dev/null +++ b/src/compiler/transformers/es2017.ts @@ -0,0 +1,544 @@ +/// +/// + +/*@internal*/ +namespace ts { + type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration; + + export function transformES2017(context: TransformationContext) { + + const enum ES2017SubstitutionFlags { + /** Enables substitutions for async methods with `super` calls. */ + AsyncMethodsWithSuper = 1 << 0 + } + + const { + startLexicalEnvironment, + endLexicalEnvironment, + } = context; + + const resolver = context.getEmitResolver(); + const compilerOptions = context.getCompilerOptions(); + const languageVersion = getEmitScriptTarget(compilerOptions); + + // These variables contain state that changes as we descend into the tree. + let currentSourceFileExternalHelpersModuleName: Identifier; + /** + * Keeps track of whether expression substitution has been enabled for specific edge cases. + * They are persisted between each SourceFile transformation and should not be reset. + */ + let enabledSubstitutions: ES2017SubstitutionFlags; + + /** + * Keeps track of whether we are within any containing namespaces when performing + * just-in-time substitution while printing an expression identifier. + */ + let applicableSubstitutions: ES2017SubstitutionFlags; + + /** + * This keeps track of containers where `super` is valid, for use with + * just-in-time substitution for `super` expressions inside of async methods. + */ + let currentSuperContainer: SuperContainer; + + // Save the previous transformation hooks. + const previousOnEmitNode = context.onEmitNode; + const previousOnSubstituteNode = context.onSubstituteNode; + + // Set new transformation hooks. + context.onEmitNode = onEmitNode; + context.onSubstituteNode = onSubstituteNode; + + let currentScope: SourceFile | Block | ModuleBlock | CaseBlock; + + return transformSourceFile; + + function transformSourceFile(node: SourceFile) { + if (isDeclarationFile(node)) { + return node; + } + + currentSourceFileExternalHelpersModuleName = node.externalHelpersModuleName; + + return visitEachChild(node, visitor, context); + } + + function visitor(node: Node): VisitResult { + if (node.transformFlags & TransformFlags.ES2017) { + return visitorWorker(node); + } + else if (node.transformFlags & TransformFlags.ContainsES2017) { + return visitEachChild(node, visitor, context); + } + + // node = visitEachChild(node, visitor, context); + // return visitEachChild(node, visitor, context); + return node; + } + + function visitorWorker(node: Node): VisitResult { + switch (node.kind) { + case SyntaxKind.AsyncKeyword: + return undefined; + + case SyntaxKind.AwaitExpression: + // Typescript 'await' expressions must be transformed for targets < ES2017. + return visitAwaitExpression(node); + + case SyntaxKind.MethodDeclaration: + // TypeScript method declarations may be 'async' + return visitMethodDeclaration(node); + + case SyntaxKind.FunctionDeclaration: + // TypeScript function declarations may be 'async' + return visitFunctionDeclaration(node); + + case SyntaxKind.FunctionExpression: + // TypeScript function expressions may be 'async' + return visitFunctionExpression(node); + + case SyntaxKind.ArrowFunction: + // TypeScript arrow functions may be 'async' + return visitArrowFunction(node); + + default: + Debug.failBadSyntaxKind(node); + return node; + } + } + + /** + * Visits an await expression. + * + * This function will be called any time a ES2017 await expression is encountered. + * + * @param node The await expression node. + */ + function visitAwaitExpression(node: AwaitExpression): Expression { + return setOriginalNode( + createYield( + /*asteriskToken*/ undefined, + visitNode(node.expression, visitor, isExpression), + /*location*/ node + ), + node + ); + } + + /** + * Visits a method declaration of a class. + * + * This function will be called when one of the following conditions are met: + * - The node is marked as async + * + * @param node The method node. + */ + function visitMethodDeclaration(node: MethodDeclaration) { + if (!isAsyncFunctionLike(node)) { + return node; + } + const method = createMethod( + /*decorators*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), + node.asteriskToken, + node.name, + /*typeParameters*/ undefined, + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + transformFunctionBody(node), + /*location*/ node + ); + + // While we emit the source map for the node after skipping decorators and modifiers, + // we need to emit the comments for the original range. + setCommentRange(method, node); + setSourceMapRange(method, moveRangePastDecorators(node)); + setOriginalNode(method, node); + + return method; + } + + /** + * Visits a function declaration. + * + * This function will be called when one of the following conditions are met: + * - The node is an overload + * - The node is marked async + * - The node is exported from a TypeScript namespace + * + * @param node The function node. + */ + function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult { + if (!isAsyncFunctionLike(node)) { + return node; + } + const func = createFunctionDeclaration( + /*decorators*/ undefined, + visitNodes(node.modifiers, visitor, isModifier), + node.asteriskToken, + node.name, + /*typeParameters*/ undefined, + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + transformFunctionBody(node), + /*location*/ node + ); + setOriginalNode(func, node); + + return func; + } + + /** + * Visits a function expression node. + * + * This function will be called when one of the following conditions are met: + * - The node is marked async + * + * @param node The function expression node. + */ + function visitFunctionExpression(node: FunctionExpression): Expression { + if (!isAsyncFunctionLike(node)) { + return node; + } + if (nodeIsMissing(node.body)) { + return createOmittedExpression(); + } + + const func = createFunctionExpression( + node.asteriskToken, + node.name, + /*typeParameters*/ undefined, + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + transformFunctionBody(node), + /*location*/ node + ); + + node.modifiers = visitNodes(node.modifiers, visitor, isModifier); + + setOriginalNode(func, node); + + return func; + } + + /** + * @remarks + * This function will be called when one of the following conditions are met: + * - The node is marked async + */ + function visitArrowFunction(node: ArrowFunction) { + if (!isAsyncFunctionLike(node)) { + return node; + } + const func = createArrowFunction( + visitNodes(node.modifiers, visitor, isModifier), + /*typeParameters*/ undefined, + visitNodes(node.parameters, visitor, isParameter), + /*type*/ undefined, + node.equalsGreaterThanToken, + transformConciseBody(node), + /*location*/ node + ); + + setOriginalNode(func, node); + + return func; + } + + function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { + return transformAsyncFunctionBody(node); + } + + function transformConciseBody(node: ArrowFunction): ConciseBody { + return transformAsyncFunctionBody(node); + } + + function transformFunctionBodyWorker(body: Block, start = 0) { + const savedCurrentScope = currentScope; + currentScope = body; + startLexicalEnvironment(); + + const statements = visitNodes(body.statements, visitor, isStatement, start); + const visited = updateBlock(body, statements); + const declarations = endLexicalEnvironment(); + currentScope = savedCurrentScope; + return mergeFunctionBodyLexicalEnvironment(visited, declarations); + } + + function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody { + const nodeType = node.original ? (node.original).type : node.type; + const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(nodeType) : undefined; + const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; + const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; + + // An async function is emit as an outer function that calls an inner + // generator function. To preserve lexical bindings, we pass the current + // `this` and `arguments` objects to `__awaiter`. The generator function + // passed to `__awaiter` is executed inside of the callback to the + // promise constructor. + + + if (!isArrowFunction) { + const statements: Statement[] = []; + const statementOffset = addPrologueDirectives(statements, (node.body).statements, /*ensureUseStrict*/ false, visitor); + statements.push( + createReturn( + createAwaiterHelper( + currentSourceFileExternalHelpersModuleName, + hasLexicalArguments, + promiseConstructor, + transformFunctionBodyWorker(node.body, statementOffset) + ) + ) + ); + + const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true); + + // Minor optimization, emit `_super` helper to capture `super` access in an arrow. + // This step isn't needed if we eventually transform this to ES5. + if (languageVersion >= ScriptTarget.ES6) { + if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { + enableSubstitutionForAsyncMethodsWithSuper(); + setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper); + } + else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { + enableSubstitutionForAsyncMethodsWithSuper(); + setEmitFlags(block, EmitFlags.EmitSuperHelper); + } + } + + return block; + } + else { + return createAwaiterHelper( + currentSourceFileExternalHelpersModuleName, + hasLexicalArguments, + promiseConstructor, + transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true) + ); + } + } + + function transformConciseBodyWorker(body: Block | Expression, forceBlockFunctionBody: boolean) { + if (isBlock(body)) { + return transformFunctionBodyWorker(body); + } + else { + startLexicalEnvironment(); + const visited: Expression | Block = visitNode(body, visitor, isConciseBody); + const declarations = endLexicalEnvironment(); + const merged = mergeFunctionBodyLexicalEnvironment(visited, declarations); + if (forceBlockFunctionBody && !isBlock(merged)) { + return createBlock([ + createReturn(merged) + ]); + } + else { + return merged; + } + } + } + + function getPromiseConstructor(type: TypeNode) { + const typeName = getEntityNameFromTypeNode(type); + if (typeName && isEntityName(typeName)) { + const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); + if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue + || serializationKind === TypeReferenceSerializationKind.Unknown) { + return typeName; + } + } + + return undefined; + } + + function enableSubstitutionForAsyncMethodsWithSuper() { + if ((enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) === 0) { + enabledSubstitutions |= ES2017SubstitutionFlags.AsyncMethodsWithSuper; + + // We need to enable substitutions for call, property access, and element access + // if we need to rewrite super calls. + context.enableSubstitution(SyntaxKind.CallExpression); + context.enableSubstitution(SyntaxKind.PropertyAccessExpression); + context.enableSubstitution(SyntaxKind.ElementAccessExpression); + + // We need to be notified when entering and exiting declarations that bind super. + context.enableEmitNotification(SyntaxKind.ClassDeclaration); + context.enableEmitNotification(SyntaxKind.MethodDeclaration); + context.enableEmitNotification(SyntaxKind.GetAccessor); + context.enableEmitNotification(SyntaxKind.SetAccessor); + context.enableEmitNotification(SyntaxKind.Constructor); + } + } + + function substituteExpression(node: Expression) { + switch (node.kind) { + case SyntaxKind.PropertyAccessExpression: + return substitutePropertyAccessExpression(node); + case SyntaxKind.ElementAccessExpression: + return substituteElementAccessExpression(node); + case SyntaxKind.CallExpression: + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper) { + return substituteCallExpression(node); + } + break; + } + + return node; + } + + function substitutePropertyAccessExpression(node: PropertyAccessExpression) { + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod( + createLiteral(node.name.text), + flags, + node + ); + } + } + + return substituteConstantValue(node); + } + + function substituteElementAccessExpression(node: ElementAccessExpression) { + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + return createSuperAccessInAsyncMethod( + node.argumentExpression, + flags, + node + ); + } + } + + return substituteConstantValue(node); + } + + function substituteConstantValue(node: PropertyAccessExpression | ElementAccessExpression): LeftHandSideExpression { + const constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + const substitute = createLiteral(constantValue); + setSourceMapRange(substitute, node); + setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + const propertyName = isPropertyAccessExpression(node) + ? declarationNameToString(node.name) + : getTextOfNode(node.argumentExpression); + substitute.trailingComment = ` ${propertyName} `; + } + + setConstantValue(node, constantValue); + return substitute; + } + + return node; + } + + function tryGetConstEnumValue(node: Node): number { + if (compilerOptions.isolatedModules) { + return undefined; + } + + return isPropertyAccessExpression(node) || isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } + + function substituteCallExpression(node: CallExpression): Expression { + const expression = node.expression; + if (isSuperProperty(expression)) { + const flags = getSuperContainerAsyncMethodFlags(); + if (flags) { + const argumentExpression = isPropertyAccessExpression(expression) + ? substitutePropertyAccessExpression(expression) + : substituteElementAccessExpression(expression); + return createCall( + createPropertyAccess(argumentExpression, "call"), + /*typeArguments*/ undefined, + [ + createThis(), + ...node.arguments + ] + ); + } + } + return node; + } + + function isSuperContainer(node: Node): node is SuperContainer { + const kind = node.kind; + return kind === SyntaxKind.ClassDeclaration + || kind === SyntaxKind.Constructor + || kind === SyntaxKind.MethodDeclaration + || kind === SyntaxKind.GetAccessor + || kind === SyntaxKind.SetAccessor; + } + + /** + * Hook for node emit. + * + * @param node The node to emit. + * @param emit A callback used to emit the node in the printer. + */ + function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { + const savedApplicableSubstitutions = applicableSubstitutions; + const savedCurrentSuperContainer = currentSuperContainer; + // If we need to support substitutions for `super` in an async method, + // we should track it here. + if (enabledSubstitutions & ES2017SubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { + currentSuperContainer = node; + } + + previousOnEmitNode(emitContext, node, emitCallback); + + applicableSubstitutions = savedApplicableSubstitutions; + currentSuperContainer = savedCurrentSuperContainer; + } + + /** + * Hooks node substitutions. + * + * @param node The node to substitute. + * @param isExpression A value indicating whether the node is to be used in an expression + * position. + */ + function onSubstituteNode(emitContext: EmitContext, node: Node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === EmitContext.Expression) { + return substituteExpression(node); + } + + return node; + } + + function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression { + if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) { + return createPropertyAccess( + createCall( + createIdentifier("_super"), + /*typeArguments*/ undefined, + [argumentExpression] + ), + "value", + location + ); + } + else { + return createCall( + createIdentifier("_super"), + /*typeArguments*/ undefined, + [argumentExpression], + location + ); + } + } + + function getSuperContainerAsyncMethodFlags() { + return currentSuperContainer !== undefined + && resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding); + } + } +} diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index c4e9b4c31c8..3877169e6c3 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -701,11 +701,13 @@ namespace ts { const statements: Statement[] = []; const name = node.name || getGeneratedNameForNode(node); if (hasModifier(node, ModifierFlags.Export)) { + // Keep async modifier for ES2017 transformer + const isAsync = hasModifier(node, ModifierFlags.Async); statements.push( setOriginalNode( createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, + isAsync ? [createNode(SyntaxKind.AsyncKeyword)] : undefined, node.asteriskToken, name, /*typeParameters*/ undefined, diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index 4a137c89a93..d4ee4f36b87 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -662,9 +662,11 @@ namespace ts { if (hasModifier(node, ModifierFlags.Export)) { // If the function is exported, ensure it has a name and rewrite the function without any export flags. const name = node.name || getGeneratedNameForNode(node); + // Keep async modifier for ES2017 transformer + const isAsync = hasModifier(node, ModifierFlags.Async); const newNode = createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, + isAsync ? [createNode(SyntaxKind.AsyncKeyword)] : undefined, node.asteriskToken, name, /*typeParameters*/ undefined, @@ -1402,4 +1404,4 @@ namespace ts { return updated; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index c98fbfc26cc..30276deff92 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -4,8 +4,6 @@ /*@internal*/ namespace ts { - type SuperContainer = ClassDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration; - /** * Indicates whether to emit type metadata in the new format. */ @@ -16,8 +14,6 @@ namespace ts { ClassAliases = 1 << 0, /** Enables substitutions for namespace exports. */ NamespaceExports = 1 << 1, - /** Enables substitutions for async methods with `super` calls. */ - AsyncMethodsWithSuper = 1 << 2, /* Enables substitutions for unqualified enum members */ NonQualifiedEnumMembers = 1 << 3 } @@ -72,12 +68,6 @@ namespace ts { */ let applicableSubstitutions: TypeScriptSubstitutionFlags; - /** - * This keeps track of containers where `super` is valid, for use with - * just-in-time substitution for `super` expressions inside of async methods. - */ - let currentSuperContainer: SuperContainer; - return transformSourceFile; /** @@ -240,6 +230,7 @@ namespace ts { // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; + // Typescript ES2017 async/await are handled by ES2017 transformer case SyntaxKind.AsyncKeyword: return node; @@ -388,7 +379,7 @@ namespace ts { return visitEnumDeclaration(node); case SyntaxKind.AwaitExpression: - // TypeScript 'await' expressions must be transformed. + // Typescript ES2017 async/await are handled by ES2017 transformer return visitAwaitExpression(node); case SyntaxKind.VariableStatement: @@ -2225,13 +2216,9 @@ namespace ts { /*location*/ node ); - // Add ES8 async function expression modifier - // Not sure this is the right place? Might be better to move this - // into createFunctionExpression itself. - if ((languageVersion >= ScriptTarget.ES8) && isAsyncFunctionLike(node)) { - const funcModifiers = visitNodes(node.modifiers, visitor, isModifier); - func.modifiers = createNodeArray(funcModifiers); - } + // Keep modifiers in case of async functions + const funcModifiers = visitNodes(node.modifiers, visitor, isModifier); + func.modifiers = createNodeArray(funcModifiers); setOriginalNode(func, node); @@ -2260,9 +2247,9 @@ namespace ts { } function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { - if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES8) { - return transformAsyncFunctionBody(node); - } + // if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES2017) { + // return transformAsyncFunctionBody(node); + // } return transformFunctionBodyWorker(node.body); } @@ -2280,9 +2267,9 @@ namespace ts { } function transformConciseBody(node: ArrowFunction): ConciseBody { - if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES8) { - return transformAsyncFunctionBody(node); - } + // if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES2017) { + // return transformAsyncFunctionBody(node); + // } return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); } @@ -2307,72 +2294,6 @@ namespace ts { } } - function getPromiseConstructor(type: TypeNode) { - const typeName = getEntityNameFromTypeNode(type); - if (typeName && isEntityName(typeName)) { - const serializationKind = resolver.getTypeReferenceSerializationKind(typeName); - if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue - || serializationKind === TypeReferenceSerializationKind.Unknown) { - return typeName; - } - } - - return undefined; - } - - function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody { - const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(node.type) : undefined; - const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; - const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; - - // An async function is emit as an outer function that calls an inner - // generator function. To preserve lexical bindings, we pass the current - // `this` and `arguments` objects to `__awaiter`. The generator function - // passed to `__awaiter` is executed inside of the callback to the - // promise constructor. - - - if (!isArrowFunction) { - const statements: Statement[] = []; - const statementOffset = addPrologueDirectives(statements, (node.body).statements, /*ensureUseStrict*/ false, visitor); - statements.push( - createReturn( - createAwaiterHelper( - currentSourceFileExternalHelpersModuleName, - hasLexicalArguments, - promiseConstructor, - transformFunctionBodyWorker(node.body, statementOffset) - ) - ) - ); - - const block = createBlock(statements, /*location*/ node.body, /*multiLine*/ true); - - // Minor optimization, emit `_super` helper to capture `super` access in an arrow. - // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES6) { - if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { - enableSubstitutionForAsyncMethodsWithSuper(); - setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper); - } - else if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuper) { - enableSubstitutionForAsyncMethodsWithSuper(); - setEmitFlags(block, EmitFlags.EmitSuperHelper); - } - } - - return block; - } - else { - return createAwaiterHelper( - currentSourceFileExternalHelpersModuleName, - hasLexicalArguments, - promiseConstructor, - transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ true) - ); - } - } - /** * Visits a parameter declaration node. * @@ -2458,33 +2379,18 @@ namespace ts { /** * Visits an await expression. * - * This function will be called any time a TypeScript await expression is encountered. + * This function will be called any time a ES2017 await expression is encountered. * * @param node The await expression node. */ function visitAwaitExpression(node: AwaitExpression): Expression { - const targetAtLeastES8 = languageVersion >= ScriptTarget.ES8; - return setOriginalNode( - targetAtLeastES8 ? createAwaitExpression() : createYieldExpression(), + return updateNode( + createAwait( + visitNode(node.expression, visitor, isExpression), + /*location*/ node + ), node ); - - function createAwaitExpression() { - const awaitExpression = createAwait( - visitNode(node.expression, visitor, isExpression), - /*location*/ node - ); - return awaitExpression; - } - - function createYieldExpression() { - const yieldExpression = createYield( - /*asteriskToken*/ undefined, - visitNode(node.expression, visitor, isExpression), - /*location*/ node - ); - return yieldExpression; - } } /** @@ -3241,25 +3147,6 @@ namespace ts { } } - function enableSubstitutionForAsyncMethodsWithSuper() { - if ((enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) === 0) { - enabledSubstitutions |= TypeScriptSubstitutionFlags.AsyncMethodsWithSuper; - - // We need to enable substitutions for call, property access, and element access - // if we need to rewrite super calls. - context.enableSubstitution(SyntaxKind.CallExpression); - context.enableSubstitution(SyntaxKind.PropertyAccessExpression); - context.enableSubstitution(SyntaxKind.ElementAccessExpression); - - // We need to be notified when entering and exiting declarations that bind super. - context.enableEmitNotification(SyntaxKind.ClassDeclaration); - context.enableEmitNotification(SyntaxKind.MethodDeclaration); - context.enableEmitNotification(SyntaxKind.GetAccessor); - context.enableEmitNotification(SyntaxKind.SetAccessor); - context.enableEmitNotification(SyntaxKind.Constructor); - } - } - function enableSubstitutionForClassAliases() { if ((enabledSubstitutions & TypeScriptSubstitutionFlags.ClassAliases) === 0) { enabledSubstitutions |= TypeScriptSubstitutionFlags.ClassAliases; @@ -3287,15 +3174,6 @@ namespace ts { } } - function isSuperContainer(node: Node): node is SuperContainer { - const kind = node.kind; - return kind === SyntaxKind.ClassDeclaration - || kind === SyntaxKind.Constructor - || kind === SyntaxKind.MethodDeclaration - || kind === SyntaxKind.GetAccessor - || kind === SyntaxKind.SetAccessor; - } - function isTransformedModuleDeclaration(node: Node): boolean { return getOriginalNode(node).kind === SyntaxKind.ModuleDeclaration; } @@ -3312,12 +3190,6 @@ namespace ts { */ function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void { const savedApplicableSubstitutions = applicableSubstitutions; - const savedCurrentSuperContainer = currentSuperContainer; - // If we need to support substitutions for `super` in an async method, - // we should track it here. - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && isSuperContainer(node)) { - currentSuperContainer = node; - } if (enabledSubstitutions & TypeScriptSubstitutionFlags.NamespaceExports && isTransformedModuleDeclaration(node)) { applicableSubstitutions |= TypeScriptSubstitutionFlags.NamespaceExports; @@ -3330,7 +3202,6 @@ namespace ts { previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; - currentSuperContainer = savedCurrentSuperContainer; } /** @@ -3377,11 +3248,6 @@ namespace ts { return substitutePropertyAccessExpression(node); case SyntaxKind.ElementAccessExpression: return substituteElementAccessExpression(node); - case SyntaxKind.CallExpression: - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper) { - return substituteCallExpression(node); - } - break; } return node; @@ -3436,54 +3302,11 @@ namespace ts { return undefined; } - function substituteCallExpression(node: CallExpression): Expression { - const expression = node.expression; - if (isSuperProperty(expression)) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - const argumentExpression = isPropertyAccessExpression(expression) - ? substitutePropertyAccessExpression(expression) - : substituteElementAccessExpression(expression); - return createCall( - createPropertyAccess(argumentExpression, "call"), - /*typeArguments*/ undefined, - [ - createThis(), - ...node.arguments - ] - ); - } - } - return node; - } - function substitutePropertyAccessExpression(node: PropertyAccessExpression) { - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod( - createLiteral(node.name.text), - flags, - node - ); - } - } - return substituteConstantValue(node); } function substituteElementAccessExpression(node: ElementAccessExpression) { - if (enabledSubstitutions & TypeScriptSubstitutionFlags.AsyncMethodsWithSuper && node.expression.kind === SyntaxKind.SuperKeyword) { - const flags = getSuperContainerAsyncMethodFlags(); - if (flags) { - return createSuperAccessInAsyncMethod( - node.argumentExpression, - flags, - node - ); - } - } - return substituteConstantValue(node); } @@ -3516,32 +3339,5 @@ namespace ts { ? resolver.getConstantValue(node) : undefined; } - - function createSuperAccessInAsyncMethod(argumentExpression: Expression, flags: NodeCheckFlags, location: TextRange): LeftHandSideExpression { - if (flags & NodeCheckFlags.AsyncMethodWithSuperBinding) { - return createPropertyAccess( - createCall( - createIdentifier("_super"), - /*typeArguments*/ undefined, - [argumentExpression] - ), - "value", - location - ); - } - else { - return createCall( - createIdentifier("_super"), - /*typeArguments*/ undefined, - [argumentExpression], - location - ); - } - } - - function getSuperContainerAsyncMethodFlags() { - return currentSuperContainer !== undefined - && resolver.getNodeCheckFlags(currentSuperContainer) & (NodeCheckFlags.AsyncMethodWithSuper | NodeCheckFlags.AsyncMethodWithSuperBinding); - } } } diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index fc0f016f664..de710e74a46 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -24,6 +24,7 @@ "visitor.ts", "transformers/ts.ts", "transformers/jsx.ts", + "transformers/es2017.ts", "transformers/es2016.ts", "transformers/es6.ts", "transformers/generators.ts", diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index b661cefb5a6..92ce6ecc6a4 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4142,6 +4142,8 @@ namespace ts { namespace ts { export function getDefaultLibFileName(options: CompilerOptions): string { switch (options.target) { + case ScriptTarget.ES2017: + return "lib.es2017.d.ts"; case ScriptTarget.ES2016: return "lib.es2016.d.ts"; case ScriptTarget.ES6: diff --git a/src/harness/harness.ts b/src/harness/harness.ts index b8703ebc8f2..c50f33a74c3 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -942,6 +942,8 @@ namespace Harness { export function getDefaultLibFileName(options: ts.CompilerOptions): string { switch (options.target) { + case ts.ScriptTarget.ES2017: + return "lib.es2017.d.ts"; case ts.ScriptTarget.ES2016: return "lib.es2016.d.ts"; case ts.ScriptTarget.ES6: diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index aa46c8ee8d0..c8b90645ce2 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -26,6 +26,7 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", + "../compiler/transformers/es2017.ts", "../compiler/transformers/es2016.ts", "../compiler/transformers/es6.ts", "../compiler/transformers/generators.ts", diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index e759ab35b48..45e3c9036e0 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -25,6 +25,7 @@ "../compiler/visitor.ts", "../compiler/transformers/ts.ts", "../compiler/transformers/jsx.ts", + "../compiler/transformers/es2017.ts", "../compiler/transformers/es2016.ts", "../compiler/transformers/es6.ts", "../compiler/transformers/generators.ts", diff --git a/tests/baselines/reference/es8-async.js b/tests/baselines/reference/es2017basicAsync.js similarity index 94% rename from tests/baselines/reference/es8-async.js rename to tests/baselines/reference/es2017basicAsync.js index 3338b1f88a6..da219f4614c 100644 --- a/tests/baselines/reference/es8-async.js +++ b/tests/baselines/reference/es2017basicAsync.js @@ -1,4 +1,4 @@ -//// [es8-async.ts] +//// [es2017-async.ts] async (): Promise => { await 0; @@ -47,7 +47,7 @@ class AsyncClass { } -//// [es8-async.js] +//// [es2017-async.js] async () => { await 0; }; diff --git a/tests/baselines/reference/es8-async.symbols b/tests/baselines/reference/es2017basicAsync.symbols similarity index 78% rename from tests/baselines/reference/es8-async.symbols rename to tests/baselines/reference/es2017basicAsync.symbols index 25a77351aef..be3b2e723f4 100644 --- a/tests/baselines/reference/es8-async.symbols +++ b/tests/baselines/reference/es2017basicAsync.symbols @@ -1,4 +1,4 @@ -=== tests/cases/compiler/es8-async.ts === +=== tests/cases/compiler/es2017-async.ts === async (): Promise => { >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) @@ -7,20 +7,20 @@ async (): Promise => { } async function asyncFunc() { ->asyncFunc : Symbol(asyncFunc, Decl(es8-async.ts, 3, 1)) +>asyncFunc : Symbol(asyncFunc, Decl(es2017-async.ts, 3, 1)) await 0; } const asycnArrowFunc = async (): Promise => { ->asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es8-async.ts, 9, 5)) +>asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es2017-async.ts, 9, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 0; } async function asyncIIFE() { ->asyncIIFE : Symbol(asyncIIFE, Decl(es8-async.ts, 11, 1)) +>asyncIIFE : Symbol(asyncIIFE, Decl(es2017-async.ts, 11, 1)) await 0; @@ -31,7 +31,7 @@ async function asyncIIFE() { })(); await (async function asyncNamedFunc(): Promise { ->asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es8-async.ts, 20, 11)) +>asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es2017-async.ts, 20, 11)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 1; @@ -45,32 +45,32 @@ async function asyncIIFE() { } class AsyncClass { ->AsyncClass : Symbol(AsyncClass, Decl(es8-async.ts, 27, 1)) +>AsyncClass : Symbol(AsyncClass, Decl(es2017-async.ts, 27, 1)) asyncPropFunc = async function(): Promise { ->asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es8-async.ts, 29, 18)) +>asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es2017-async.ts, 29, 18)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } asyncPropNamedFunc = async function namedFunc(): Promise { ->asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es8-async.ts, 32, 5)) ->namedFunc : Symbol(namedFunc, Decl(es8-async.ts, 34, 24)) +>asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es2017-async.ts, 32, 5)) +>namedFunc : Symbol(namedFunc, Decl(es2017-async.ts, 34, 24)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } asyncPropArrowFunc = async (): Promise => { ->asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es8-async.ts, 36, 5)) +>asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es2017-async.ts, 36, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } async asyncMethod(): Promise { ->asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es8-async.ts, 40, 5)) +>asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es2017-async.ts, 40, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; diff --git a/tests/baselines/reference/es8-async.types b/tests/baselines/reference/es2017basicAsync.types similarity index 94% rename from tests/baselines/reference/es8-async.types rename to tests/baselines/reference/es2017basicAsync.types index da0ca063777..79f3a005e6e 100644 --- a/tests/baselines/reference/es8-async.types +++ b/tests/baselines/reference/es2017basicAsync.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/es8-async.ts === +=== tests/cases/compiler/es2017-async.ts === async (): Promise => { >async (): Promise => { await 0;} : () => Promise From 1b4c0e331e5aa11133f0a36e1ba24d7ee748a58a Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Wed, 12 Oct 2016 21:34:55 +0200 Subject: [PATCH 31/74] Add es2017 async conformance --- ...owFunctionWithParameterNameAsync_es2017.js | 6 + ...ctionWithParameterNameAsync_es2017.symbols | 7 + ...unctionWithParameterNameAsync_es2017.types | 8 ++ .../reference/asyncAliasReturnType_es2017.js | 9 ++ .../asyncAliasReturnType_es2017.symbols | 11 ++ .../asyncAliasReturnType_es2017.types | 11 ++ .../asyncArrowFunction10_es2017.errors.txt | 12 ++ .../reference/asyncArrowFunction10_es2017.js | 13 ++ .../reference/asyncArrowFunction1_es2017.js | 8 ++ .../asyncArrowFunction1_es2017.symbols | 7 + .../asyncArrowFunction1_es2017.types | 8 ++ .../reference/asyncArrowFunction2_es2017.js | 7 + .../asyncArrowFunction2_es2017.symbols | 5 + .../asyncArrowFunction2_es2017.types | 6 + .../asyncArrowFunction3_es2017.errors.txt | 8 ++ .../reference/asyncArrowFunction3_es2017.js | 7 + .../reference/asyncArrowFunction4_es2017.js | 7 + .../asyncArrowFunction4_es2017.symbols | 4 + .../asyncArrowFunction4_es2017.types | 5 + .../asyncArrowFunction5_es2017.errors.txt | 24 ++++ .../reference/asyncArrowFunction5_es2017.js | 9 ++ .../asyncArrowFunction6_es2017.errors.txt | 12 ++ .../reference/asyncArrowFunction6_es2017.js | 8 ++ .../asyncArrowFunction7_es2017.errors.txt | 15 ++ .../reference/asyncArrowFunction7_es2017.js | 14 ++ .../asyncArrowFunction8_es2017.errors.txt | 10 ++ .../reference/asyncArrowFunction8_es2017.js | 10 ++ .../asyncArrowFunction9_es2017.errors.txt | 23 ++++ .../reference/asyncArrowFunction9_es2017.js | 8 ++ ...ncArrowFunctionCapturesArguments_es2017.js | 16 +++ ...owFunctionCapturesArguments_es2017.symbols | 20 +++ ...rrowFunctionCapturesArguments_es2017.types | 23 ++++ .../asyncArrowFunctionCapturesThis_es2017.js | 14 ++ ...ncArrowFunctionCapturesThis_es2017.symbols | 13 ++ ...syncArrowFunctionCapturesThis_es2017.types | 15 ++ ...syncAwaitIsolatedModules_es2017.errors.txt | 45 ++++++ .../asyncAwaitIsolatedModules_es2017.js | 73 ++++++++++ .../baselines/reference/asyncAwait_es2017.js | 73 ++++++++++ .../reference/asyncAwait_es2017.symbols | 118 ++++++++++++++++ .../reference/asyncAwait_es2017.types | 129 ++++++++++++++++++ .../reference/asyncClass_es2017.errors.txt | 8 ++ .../baselines/reference/asyncClass_es2017.js | 7 + .../asyncConstructor_es2017.errors.txt | 10 ++ .../reference/asyncConstructor_es2017.js | 11 ++ .../reference/asyncDeclare_es2017.errors.txt | 7 + .../reference/asyncDeclare_es2017.js | 4 + .../reference/asyncEnum_es2017.errors.txt | 9 ++ tests/baselines/reference/asyncEnum_es2017.js | 10 ++ ...yncFunctionDeclaration10_es2017.errors.txt | 26 ++++ .../asyncFunctionDeclaration10_es2017.js | 7 + .../asyncFunctionDeclaration11_es2017.js | 7 + .../asyncFunctionDeclaration11_es2017.symbols | 5 + .../asyncFunctionDeclaration11_es2017.types | 5 + ...yncFunctionDeclaration12_es2017.errors.txt | 16 +++ .../asyncFunctionDeclaration12_es2017.js | 5 + ...yncFunctionDeclaration13_es2017.errors.txt | 11 ++ .../asyncFunctionDeclaration13_es2017.js | 12 ++ .../asyncFunctionDeclaration14_es2017.js | 9 ++ .../asyncFunctionDeclaration14_es2017.symbols | 7 + .../asyncFunctionDeclaration14_es2017.types | 7 + ...yncFunctionDeclaration15_es2017.errors.txt | 48 +++++++ .../asyncFunctionDeclaration15_es2017.js | 64 +++++++++ .../asyncFunctionDeclaration1_es2017.js | 7 + .../asyncFunctionDeclaration1_es2017.symbols | 5 + .../asyncFunctionDeclaration1_es2017.types | 5 + .../asyncFunctionDeclaration2_es2017.js | 7 + .../asyncFunctionDeclaration2_es2017.symbols | 5 + .../asyncFunctionDeclaration2_es2017.types | 5 + ...syncFunctionDeclaration3_es2017.errors.txt | 8 ++ .../asyncFunctionDeclaration3_es2017.js | 7 + .../asyncFunctionDeclaration4_es2017.js | 7 + .../asyncFunctionDeclaration4_es2017.symbols | 4 + .../asyncFunctionDeclaration4_es2017.types | 4 + ...syncFunctionDeclaration5_es2017.errors.txt | 20 +++ .../asyncFunctionDeclaration5_es2017.js | 7 + ...syncFunctionDeclaration6_es2017.errors.txt | 11 ++ .../asyncFunctionDeclaration6_es2017.js | 7 + ...syncFunctionDeclaration7_es2017.errors.txt | 14 ++ .../asyncFunctionDeclaration7_es2017.js | 13 ++ ...syncFunctionDeclaration8_es2017.errors.txt | 10 ++ .../asyncFunctionDeclaration8_es2017.js | 5 + ...syncFunctionDeclaration9_es2017.errors.txt | 9 ++ .../asyncFunctionDeclaration9_es2017.js | 9 ++ .../reference/asyncGetter_es2017.errors.txt | 13 ++ .../baselines/reference/asyncGetter_es2017.js | 11 ++ .../asyncImportedPromise_es2017.errors.txt | 13 ++ .../reference/asyncImportedPromise_es2017.js | 21 +++ .../asyncInterface_es2017.errors.txt | 8 ++ .../reference/asyncInterface_es2017.js | 5 + .../reference/asyncMethodWithSuper_es2017.js | 90 ++++++++++++ .../asyncMethodWithSuper_es2017.symbols | 102 ++++++++++++++ .../asyncMethodWithSuper_es2017.types | 123 +++++++++++++++++ .../reference/asyncModule_es2017.errors.txt | 8 ++ .../baselines/reference/asyncModule_es2017.js | 5 + .../reference/asyncMultiFile_es2017.js | 11 ++ .../reference/asyncMultiFile_es2017.symbols | 8 ++ .../reference/asyncMultiFile_es2017.types | 8 ++ ...asyncQualifiedReturnType_es2017.errors.txt | 13 ++ .../asyncQualifiedReturnType_es2017.js | 18 +++ .../reference/asyncSetter_es2017.errors.txt | 10 ++ .../baselines/reference/asyncSetter_es2017.js | 11 ++ ...syncUnParenthesizedArrowFunction_es2017.js | 9 ++ ...nParenthesizedArrowFunction_es2017.symbols | 19 +++ ...cUnParenthesizedArrowFunction_es2017.types | 25 ++++ .../reference/asyncUseStrict_es2017.js | 13 ++ .../reference/asyncUseStrict_es2017.symbols | 18 +++ .../reference/asyncUseStrict_es2017.types | 22 +++ .../awaitBinaryExpression1_es2017.js | 17 +++ .../awaitBinaryExpression1_es2017.symbols | 29 ++++ .../awaitBinaryExpression1_es2017.types | 33 +++++ .../awaitBinaryExpression2_es2017.js | 17 +++ .../awaitBinaryExpression2_es2017.symbols | 29 ++++ .../awaitBinaryExpression2_es2017.types | 33 +++++ .../awaitBinaryExpression3_es2017.js | 17 +++ .../awaitBinaryExpression3_es2017.symbols | 29 ++++ .../awaitBinaryExpression3_es2017.types | 33 +++++ .../awaitBinaryExpression4_es2017.js | 17 +++ .../awaitBinaryExpression4_es2017.symbols | 29 ++++ .../awaitBinaryExpression4_es2017.types | 34 +++++ .../awaitBinaryExpression5_es2017.js | 19 +++ .../awaitBinaryExpression5_es2017.symbols | 34 +++++ .../awaitBinaryExpression5_es2017.types | 38 ++++++ .../reference/awaitCallExpression1_es2017.js | 21 +++ .../awaitCallExpression1_es2017.symbols | 59 ++++++++ .../awaitCallExpression1_es2017.types | 62 +++++++++ .../reference/awaitCallExpression2_es2017.js | 21 +++ .../awaitCallExpression2_es2017.symbols | 59 ++++++++ .../awaitCallExpression2_es2017.types | 63 +++++++++ .../reference/awaitCallExpression3_es2017.js | 21 +++ .../awaitCallExpression3_es2017.symbols | 59 ++++++++ .../awaitCallExpression3_es2017.types | 63 +++++++++ .../reference/awaitCallExpression4_es2017.js | 21 +++ .../awaitCallExpression4_es2017.symbols | 59 ++++++++ .../awaitCallExpression4_es2017.types | 64 +++++++++ .../reference/awaitCallExpression5_es2017.js | 21 +++ .../awaitCallExpression5_es2017.symbols | 61 +++++++++ .../awaitCallExpression5_es2017.types | 64 +++++++++ .../reference/awaitCallExpression6_es2017.js | 21 +++ .../awaitCallExpression6_es2017.symbols | 61 +++++++++ .../awaitCallExpression6_es2017.types | 65 +++++++++ .../reference/awaitCallExpression7_es2017.js | 21 +++ .../awaitCallExpression7_es2017.symbols | 61 +++++++++ .../awaitCallExpression7_es2017.types | 65 +++++++++ .../reference/awaitCallExpression8_es2017.js | 21 +++ .../awaitCallExpression8_es2017.symbols | 61 +++++++++ .../awaitCallExpression8_es2017.types | 66 +++++++++ .../reference/awaitClassExpression_es2017.js | 14 ++ .../awaitClassExpression_es2017.symbols | 18 +++ .../awaitClassExpression_es2017.types | 20 +++ .../baselines/reference/awaitUnion_es2017.js | 22 +++ .../reference/awaitUnion_es2017.symbols | 44 ++++++ .../reference/awaitUnion_es2017.types | 49 +++++++ .../reference/await_unaryExpression_es2017.js | 31 +++++ .../await_unaryExpression_es2017.symbols | 25 ++++ .../await_unaryExpression_es2017.types | 37 +++++ .../await_unaryExpression_es2017_1.js | 38 ++++++ .../await_unaryExpression_es2017_1.symbols | 31 +++++ .../await_unaryExpression_es2017_1.types | 46 +++++++ .../await_unaryExpression_es2017_2.js | 24 ++++ .../await_unaryExpression_es2017_2.symbols | 19 +++ .../await_unaryExpression_es2017_2.types | 28 ++++ .../await_unaryExpression_es2017_3.errors.txt | 27 ++++ .../await_unaryExpression_es2017_3.js | 37 +++++ tests/baselines/reference/es2017basicAsync.js | 4 +- .../reference/es2017basicAsync.symbols | 22 +-- .../reference/es2017basicAsync.types | 2 +- .../es2017/asyncAliasReturnType_es2017.ts | 6 + ...owFunctionWithParameterNameAsync_es2017.ts | 4 + .../asyncArrowFunction10_es2017.ts | 7 + .../asyncArrowFunction1_es2017.ts | 5 + .../asyncArrowFunction2_es2017.ts | 4 + .../asyncArrowFunction3_es2017.ts | 4 + .../asyncArrowFunction4_es2017.ts | 4 + .../asyncArrowFunction5_es2017.ts | 5 + .../asyncArrowFunction6_es2017.ts | 5 + .../asyncArrowFunction7_es2017.ts | 8 ++ .../asyncArrowFunction8_es2017.ts | 6 + .../asyncArrowFunction9_es2017.ts | 4 + ...ncArrowFunctionCapturesArguments_es2017.ts | 8 ++ .../asyncArrowFunctionCapturesThis_es2017.ts | 7 + ...syncUnParenthesizedArrowFunction_es2017.ts | 6 + .../asyncAwaitIsolatedModules_es2017.ts | 41 ++++++ .../async/es2017/asyncAwait_es2017.ts | 40 ++++++ .../async/es2017/asyncClass_es2017.ts | 4 + .../async/es2017/asyncConstructor_es2017.ts | 6 + .../async/es2017/asyncDeclare_es2017.ts | 3 + .../async/es2017/asyncEnum_es2017.ts | 5 + .../async/es2017/asyncGetter_es2017.ts | 6 + .../es2017/asyncImportedPromise_es2017.ts | 10 ++ .../async/es2017/asyncInterface_es2017.ts | 4 + .../es2017/asyncMethodWithSuper_es2017.ts | 52 +++++++ .../async/es2017/asyncModule_es2017.ts | 4 + .../async/es2017/asyncMultiFile_es2017.ts | 5 + .../es2017/asyncQualifiedReturnType_es2017.ts | 9 ++ .../async/es2017/asyncSetter_es2017.ts | 6 + .../async/es2017/asyncUseStrict_es2017.ts | 8 ++ .../awaitBinaryExpression1_es2017.ts | 11 ++ .../awaitBinaryExpression2_es2017.ts | 11 ++ .../awaitBinaryExpression3_es2017.ts | 11 ++ .../awaitBinaryExpression4_es2017.ts | 11 ++ .../awaitBinaryExpression5_es2017.ts | 12 ++ .../awaitCallExpression1_es2017.ts | 15 ++ .../awaitCallExpression2_es2017.ts | 15 ++ .../awaitCallExpression3_es2017.ts | 15 ++ .../awaitCallExpression4_es2017.ts | 15 ++ .../awaitCallExpression5_es2017.ts | 15 ++ .../awaitCallExpression6_es2017.ts | 15 ++ .../awaitCallExpression7_es2017.ts | 15 ++ .../awaitCallExpression8_es2017.ts | 15 ++ .../es2017/awaitClassExpression_es2017.ts | 9 ++ .../async/es2017/awaitUnion_es2017.ts | 14 ++ .../es2017/await_unaryExpression_es2017.ts | 17 +++ .../es2017/await_unaryExpression_es2017_1.ts | 21 +++ .../es2017/await_unaryExpression_es2017_2.ts | 13 ++ .../es2017/await_unaryExpression_es2017_3.ts | 19 +++ .../asyncFunctionDeclaration10_es2017.ts | 4 + .../asyncFunctionDeclaration11_es2017.ts | 4 + .../asyncFunctionDeclaration12_es2017.ts | 3 + .../asyncFunctionDeclaration13_es2017.ts | 6 + .../asyncFunctionDeclaration14_es2017.ts | 5 + .../asyncFunctionDeclaration15_es2017.ts | 25 ++++ .../asyncFunctionDeclaration1_es2017.ts | 4 + .../asyncFunctionDeclaration2_es2017.ts | 4 + .../asyncFunctionDeclaration3_es2017.ts | 4 + .../asyncFunctionDeclaration4_es2017.ts | 4 + .../asyncFunctionDeclaration5_es2017.ts | 4 + .../asyncFunctionDeclaration6_es2017.ts | 4 + .../asyncFunctionDeclaration7_es2017.ts | 7 + .../asyncFunctionDeclaration8_es2017.ts | 3 + .../asyncFunctionDeclaration9_es2017.ts | 5 + 230 files changed, 4602 insertions(+), 14 deletions(-) create mode 100644 tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js create mode 100644 tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols create mode 100644 tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types create mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.js create mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.symbols create mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.types create mode 100644 tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction10_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction1_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction1_es2017.symbols create mode 100644 tests/baselines/reference/asyncArrowFunction1_es2017.types create mode 100644 tests/baselines/reference/asyncArrowFunction2_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction2_es2017.symbols create mode 100644 tests/baselines/reference/asyncArrowFunction2_es2017.types create mode 100644 tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction3_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction4_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction4_es2017.symbols create mode 100644 tests/baselines/reference/asyncArrowFunction4_es2017.types create mode 100644 tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction5_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction6_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction7_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction8_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncArrowFunction9_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols create mode 100644 tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types create mode 100644 tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js create mode 100644 tests/baselines/reference/asyncAwait_es2017.js create mode 100644 tests/baselines/reference/asyncAwait_es2017.symbols create mode 100644 tests/baselines/reference/asyncAwait_es2017.types create mode 100644 tests/baselines/reference/asyncClass_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncClass_es2017.js create mode 100644 tests/baselines/reference/asyncConstructor_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncConstructor_es2017.js create mode 100644 tests/baselines/reference/asyncDeclare_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncDeclare_es2017.js create mode 100644 tests/baselines/reference/asyncEnum_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncEnum_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration10_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration11_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols create mode 100644 tests/baselines/reference/asyncFunctionDeclaration11_es2017.types create mode 100644 tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration12_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration13_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration14_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols create mode 100644 tests/baselines/reference/asyncFunctionDeclaration14_es2017.types create mode 100644 tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration15_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration1_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols create mode 100644 tests/baselines/reference/asyncFunctionDeclaration1_es2017.types create mode 100644 tests/baselines/reference/asyncFunctionDeclaration2_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols create mode 100644 tests/baselines/reference/asyncFunctionDeclaration2_es2017.types create mode 100644 tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration3_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration4_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols create mode 100644 tests/baselines/reference/asyncFunctionDeclaration4_es2017.types create mode 100644 tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration5_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration6_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration7_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration8_es2017.js create mode 100644 tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncFunctionDeclaration9_es2017.js create mode 100644 tests/baselines/reference/asyncGetter_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncGetter_es2017.js create mode 100644 tests/baselines/reference/asyncImportedPromise_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncImportedPromise_es2017.js create mode 100644 tests/baselines/reference/asyncInterface_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncInterface_es2017.js create mode 100644 tests/baselines/reference/asyncMethodWithSuper_es2017.js create mode 100644 tests/baselines/reference/asyncMethodWithSuper_es2017.symbols create mode 100644 tests/baselines/reference/asyncMethodWithSuper_es2017.types create mode 100644 tests/baselines/reference/asyncModule_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncModule_es2017.js create mode 100644 tests/baselines/reference/asyncMultiFile_es2017.js create mode 100644 tests/baselines/reference/asyncMultiFile_es2017.symbols create mode 100644 tests/baselines/reference/asyncMultiFile_es2017.types create mode 100644 tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncQualifiedReturnType_es2017.js create mode 100644 tests/baselines/reference/asyncSetter_es2017.errors.txt create mode 100644 tests/baselines/reference/asyncSetter_es2017.js create mode 100644 tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js create mode 100644 tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols create mode 100644 tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types create mode 100644 tests/baselines/reference/asyncUseStrict_es2017.js create mode 100644 tests/baselines/reference/asyncUseStrict_es2017.symbols create mode 100644 tests/baselines/reference/asyncUseStrict_es2017.types create mode 100644 tests/baselines/reference/awaitBinaryExpression1_es2017.js create mode 100644 tests/baselines/reference/awaitBinaryExpression1_es2017.symbols create mode 100644 tests/baselines/reference/awaitBinaryExpression1_es2017.types create mode 100644 tests/baselines/reference/awaitBinaryExpression2_es2017.js create mode 100644 tests/baselines/reference/awaitBinaryExpression2_es2017.symbols create mode 100644 tests/baselines/reference/awaitBinaryExpression2_es2017.types create mode 100644 tests/baselines/reference/awaitBinaryExpression3_es2017.js create mode 100644 tests/baselines/reference/awaitBinaryExpression3_es2017.symbols create mode 100644 tests/baselines/reference/awaitBinaryExpression3_es2017.types create mode 100644 tests/baselines/reference/awaitBinaryExpression4_es2017.js create mode 100644 tests/baselines/reference/awaitBinaryExpression4_es2017.symbols create mode 100644 tests/baselines/reference/awaitBinaryExpression4_es2017.types create mode 100644 tests/baselines/reference/awaitBinaryExpression5_es2017.js create mode 100644 tests/baselines/reference/awaitBinaryExpression5_es2017.symbols create mode 100644 tests/baselines/reference/awaitBinaryExpression5_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression1_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression1_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression1_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression2_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression2_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression2_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression3_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression3_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression3_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression4_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression4_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression4_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression5_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression5_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression5_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression6_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression6_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression6_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression7_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression7_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression7_es2017.types create mode 100644 tests/baselines/reference/awaitCallExpression8_es2017.js create mode 100644 tests/baselines/reference/awaitCallExpression8_es2017.symbols create mode 100644 tests/baselines/reference/awaitCallExpression8_es2017.types create mode 100644 tests/baselines/reference/awaitClassExpression_es2017.js create mode 100644 tests/baselines/reference/awaitClassExpression_es2017.symbols create mode 100644 tests/baselines/reference/awaitClassExpression_es2017.types create mode 100644 tests/baselines/reference/awaitUnion_es2017.js create mode 100644 tests/baselines/reference/awaitUnion_es2017.symbols create mode 100644 tests/baselines/reference/awaitUnion_es2017.types create mode 100644 tests/baselines/reference/await_unaryExpression_es2017.js create mode 100644 tests/baselines/reference/await_unaryExpression_es2017.symbols create mode 100644 tests/baselines/reference/await_unaryExpression_es2017.types create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_1.js create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_1.symbols create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_1.types create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_2.js create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_2.symbols create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_2.types create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt create mode 100644 tests/baselines/reference/await_unaryExpression_es2017_3.js create mode 100644 tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncAwait_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncClass_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncEnum_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncGetter_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncInterface_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncModule_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncSetter_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/awaitUnion_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts create mode 100644 tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts create mode 100644 tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts create mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js new file mode 100644 index 00000000000..daaff29cad9 --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.js @@ -0,0 +1,6 @@ +//// [arrowFunctionWithParameterNameAsync_es2017.ts] + +const x = async => async; + +//// [arrowFunctionWithParameterNameAsync_es2017.js] +var x = function (async) { return async; }; diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols new file mode 100644 index 00000000000..481697c0afd --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts === + +const x = async => async; +>x : Symbol(x, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 5)) +>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9)) +>async : Symbol(async, Decl(arrowFunctionWithParameterNameAsync_es2017.ts, 1, 9)) + diff --git a/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types new file mode 100644 index 00000000000..ccb8654284c --- /dev/null +++ b/tests/baselines/reference/arrowFunctionWithParameterNameAsync_es2017.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts === + +const x = async => async; +>x : (async: any) => any +>async => async : (async: any) => any +>async : any +>async : any + diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.js b/tests/baselines/reference/asyncAliasReturnType_es2017.js new file mode 100644 index 00000000000..f76f2b13b45 --- /dev/null +++ b/tests/baselines/reference/asyncAliasReturnType_es2017.js @@ -0,0 +1,9 @@ +//// [asyncAliasReturnType_es2017.ts] +type PromiseAlias = Promise; + +async function f(): PromiseAlias { +} + +//// [asyncAliasReturnType_es2017.js] +async function f() { +} diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.symbols b/tests/baselines/reference/asyncAliasReturnType_es2017.symbols new file mode 100644 index 00000000000..cc4fc5b8096 --- /dev/null +++ b/tests/baselines/reference/asyncAliasReturnType_es2017.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts === +type PromiseAlias = Promise; +>PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es2017.ts, 0, 0)) +>T : Symbol(T, Decl(asyncAliasReturnType_es2017.ts, 0, 18)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>T : Symbol(T, Decl(asyncAliasReturnType_es2017.ts, 0, 18)) + +async function f(): PromiseAlias { +>f : Symbol(f, Decl(asyncAliasReturnType_es2017.ts, 0, 34)) +>PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es2017.ts, 0, 0)) +} diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.types b/tests/baselines/reference/asyncAliasReturnType_es2017.types new file mode 100644 index 00000000000..67c521b77fa --- /dev/null +++ b/tests/baselines/reference/asyncAliasReturnType_es2017.types @@ -0,0 +1,11 @@ +=== tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts === +type PromiseAlias = Promise; +>PromiseAlias : Promise +>T : T +>Promise : Promise +>T : T + +async function f(): PromiseAlias { +>f : () => Promise +>PromiseAlias : Promise +} diff --git a/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt new file mode 100644 index 00000000000..923dbed6dad --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction10_es2017.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts(4,11): error TS2304: Cannot find name 'await'. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts (1 errors) ==== + + var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction10_es2017.js b/tests/baselines/reference/asyncArrowFunction10_es2017.js new file mode 100644 index 00000000000..3c966201bc2 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction10_es2017.js @@ -0,0 +1,13 @@ +//// [asyncArrowFunction10_es2017.ts] + +var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; +} + + +//// [asyncArrowFunction10_es2017.js] +var foo = async () => { + // Legal to use 'await' in a type context. + var v; +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.js b/tests/baselines/reference/asyncArrowFunction1_es2017.js new file mode 100644 index 00000000000..ff6a4624242 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction1_es2017.ts] + +var foo = async (): Promise => { +}; + +//// [asyncArrowFunction1_es2017.js] +var foo = async () => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.symbols b/tests/baselines/reference/asyncArrowFunction1_es2017.symbols new file mode 100644 index 00000000000..35fd033d6b4 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts === + +var foo = async (): Promise => { +>foo : Symbol(foo, Decl(asyncArrowFunction1_es2017.ts, 1, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +}; diff --git a/tests/baselines/reference/asyncArrowFunction1_es2017.types b/tests/baselines/reference/asyncArrowFunction1_es2017.types new file mode 100644 index 00000000000..bdc6cacc917 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction1_es2017.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts === + +var foo = async (): Promise => { +>foo : () => Promise +>async (): Promise => {} : () => Promise +>Promise : Promise + +}; diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.js b/tests/baselines/reference/asyncArrowFunction2_es2017.js new file mode 100644 index 00000000000..d2a5d0306b1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction2_es2017.ts] +var f = (await) => { +} + +//// [asyncArrowFunction2_es2017.js] +var f = (await) => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.symbols b/tests/baselines/reference/asyncArrowFunction2_es2017.symbols new file mode 100644 index 00000000000..a56c5bb62c8 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts === +var f = (await) => { +>f : Symbol(f, Decl(asyncArrowFunction2_es2017.ts, 0, 3)) +>await : Symbol(await, Decl(asyncArrowFunction2_es2017.ts, 0, 9)) +} diff --git a/tests/baselines/reference/asyncArrowFunction2_es2017.types b/tests/baselines/reference/asyncArrowFunction2_es2017.types new file mode 100644 index 00000000000..1feb033e6ee --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction2_es2017.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts === +var f = (await) => { +>f : (await: any) => void +>(await) => {} : (await: any) => void +>await : any +} diff --git a/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt new file mode 100644 index 00000000000..1c1fd711760 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction3_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts (1 errors) ==== + function f(await = await) { + ~~~~~ +!!! error TS2372: Parameter 'await' cannot be referenced in its initializer. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction3_es2017.js b/tests/baselines/reference/asyncArrowFunction3_es2017.js new file mode 100644 index 00000000000..7ae371facc1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction3_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction3_es2017.ts] +function f(await = await) { +} + +//// [asyncArrowFunction3_es2017.js] +function f(await = await) { +} diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.js b/tests/baselines/reference/asyncArrowFunction4_es2017.js new file mode 100644 index 00000000000..ebec1e6dbd6 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.js @@ -0,0 +1,7 @@ +//// [asyncArrowFunction4_es2017.ts] +var await = () => { +} + +//// [asyncArrowFunction4_es2017.js] +var await = () => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.symbols b/tests/baselines/reference/asyncArrowFunction4_es2017.symbols new file mode 100644 index 00000000000..b44fc0dbdf6 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts === +var await = () => { +>await : Symbol(await, Decl(asyncArrowFunction4_es2017.ts, 0, 3)) +} diff --git a/tests/baselines/reference/asyncArrowFunction4_es2017.types b/tests/baselines/reference/asyncArrowFunction4_es2017.types new file mode 100644 index 00000000000..6af5f94c758 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction4_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts === +var await = () => { +>await : () => void +>() => {} : () => void +} diff --git a/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt new file mode 100644 index 00000000000..3df56177107 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction5_es2017.errors.txt @@ -0,0 +1,24 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,11): error TS2304: Cannot find name 'async'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,18): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,24): error TS1005: ',' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,26): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,33): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts(2,40): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts (6 errors) ==== + + var foo = async (await): Promise => { + ~~~~~ +!!! error TS2304: Cannot find name 'async'. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ',' expected. + ~~~~~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. + ~ +!!! error TS1005: '=' expected. + ~~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction5_es2017.js b/tests/baselines/reference/asyncArrowFunction5_es2017.js new file mode 100644 index 00000000000..0c61a141f17 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction5_es2017.js @@ -0,0 +1,9 @@ +//// [asyncArrowFunction5_es2017.ts] + +var foo = async (await): Promise => { +} + +//// [asyncArrowFunction5_es2017.js] +var foo = async(await), Promise = ; +{ +} diff --git a/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt new file mode 100644 index 00000000000..202ecb1727f --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction6_es2017.errors.txt @@ -0,0 +1,12 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts(2,22): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts(2,27): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts (2 errors) ==== + + var foo = async (a = await): Promise => { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction6_es2017.js b/tests/baselines/reference/asyncArrowFunction6_es2017.js new file mode 100644 index 00000000000..c36f75a180a --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction6_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction6_es2017.ts] + +var foo = async (a = await): Promise => { +} + +//// [asyncArrowFunction6_es2017.js] +var foo = async (a = await ) => { +}; diff --git a/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt new file mode 100644 index 00000000000..33e03624283 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction7_es2017.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts(4,24): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts(4,29): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts (2 errors) ==== + + var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction7_es2017.js b/tests/baselines/reference/asyncArrowFunction7_es2017.js new file mode 100644 index 00000000000..11d8c879eb8 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction7_es2017.js @@ -0,0 +1,14 @@ +//// [asyncArrowFunction7_es2017.ts] + +var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + } +} + +//// [asyncArrowFunction7_es2017.js] +var bar = async () => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await ) => { + }; +}; diff --git a/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt new file mode 100644 index 00000000000..75e460490bd --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction8_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts(3,19): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts (1 errors) ==== + + var foo = async (): Promise => { + var v = { [await]: foo } + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction8_es2017.js b/tests/baselines/reference/asyncArrowFunction8_es2017.js new file mode 100644 index 00000000000..1358f186ce2 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction8_es2017.js @@ -0,0 +1,10 @@ +//// [asyncArrowFunction8_es2017.ts] + +var foo = async (): Promise => { + var v = { [await]: foo } +} + +//// [asyncArrowFunction8_es2017.js] +var foo = async () => { + var v = { [await ]: foo }; +}; diff --git a/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt b/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt new file mode 100644 index 00000000000..ee94f3f9caf --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction9_es2017.errors.txt @@ -0,0 +1,23 @@ +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,11): error TS2304: Cannot find name 'async'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,18): error TS2304: Cannot find name 'a'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,37): error TS1005: ',' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,39): error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,46): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts(1,53): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts (6 errors) ==== + var foo = async (a = await => await): Promise => { + ~~~~~ +!!! error TS2304: Cannot find name 'async'. + ~ +!!! error TS2304: Cannot find name 'a'. + ~ +!!! error TS1005: ',' expected. + ~~~~~~~ +!!! error TS2403: Subsequent variable declarations must have the same type. Variable 'Promise' must be of type 'PromiseConstructor', but here has type 'void'. + ~ +!!! error TS1005: '=' expected. + ~~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncArrowFunction9_es2017.js b/tests/baselines/reference/asyncArrowFunction9_es2017.js new file mode 100644 index 00000000000..c1fec991ec1 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunction9_es2017.js @@ -0,0 +1,8 @@ +//// [asyncArrowFunction9_es2017.ts] +var foo = async (a = await => await): Promise => { +} + +//// [asyncArrowFunction9_es2017.js] +var foo = async(a = await => await), Promise = ; +{ +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js new file mode 100644 index 00000000000..f7f813ad502 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.js @@ -0,0 +1,16 @@ +//// [asyncArrowFunctionCapturesArguments_es2017.ts] +class C { + method() { + function other() {} + var fn = async () => await other.apply(this, arguments); + } +} + + +//// [asyncArrowFunctionCapturesArguments_es2017.js] +class C { + method() { + function other() { } + var fn = async () => await other.apply(this, arguments); + } +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols new file mode 100644 index 00000000000..ccd9b48e400 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.symbols @@ -0,0 +1,20 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts === +class C { +>C : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 0)) + + method() { +>method : Symbol(C.method, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 9)) + + function other() {} +>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 1, 13)) + + var fn = async () => await other.apply(this, arguments); +>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 3, 9)) +>other.apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>other : Symbol(other, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 1, 13)) +>apply : Symbol(Function.apply, Decl(lib.es5.d.ts, --, --)) +>this : Symbol(C, Decl(asyncArrowFunctionCapturesArguments_es2017.ts, 0, 0)) +>arguments : Symbol(arguments) + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types new file mode 100644 index 00000000000..a7a80424e19 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesArguments_es2017.types @@ -0,0 +1,23 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts === +class C { +>C : C + + method() { +>method : () => void + + function other() {} +>other : () => void + + var fn = async () => await other.apply(this, arguments); +>fn : () => Promise +>async () => await other.apply(this, arguments) : () => Promise +>await other.apply(this, arguments) : any +>other.apply(this, arguments) : any +>other.apply : (this: Function, thisArg: any, argArray?: any) => any +>other : () => void +>apply : (this: Function, thisArg: any, argArray?: any) => any +>this : this +>arguments : IArguments + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js new file mode 100644 index 00000000000..13560557ffe --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.js @@ -0,0 +1,14 @@ +//// [asyncArrowFunctionCapturesThis_es2017.ts] +class C { + method() { + var fn = async () => await this; + } +} + + +//// [asyncArrowFunctionCapturesThis_es2017.js] +class C { + method() { + var fn = async () => await this; + } +} diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols new file mode 100644 index 00000000000..bc14bafa0c5 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.symbols @@ -0,0 +1,13 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts === +class C { +>C : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 0)) + + method() { +>method : Symbol(C.method, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 9)) + + var fn = async () => await this; +>fn : Symbol(fn, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 2, 9)) +>this : Symbol(C, Decl(asyncArrowFunctionCapturesThis_es2017.ts, 0, 0)) + } +} + diff --git a/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types new file mode 100644 index 00000000000..57f59302bb5 --- /dev/null +++ b/tests/baselines/reference/asyncArrowFunctionCapturesThis_es2017.types @@ -0,0 +1,15 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts === +class C { +>C : C + + method() { +>method : () => void + + var fn = async () => await this; +>fn : () => Promise +>async () => await this : () => Promise +>await this : this +>this : this + } +} + diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt new file mode 100644 index 00000000000..95927c283aa --- /dev/null +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.errors.txt @@ -0,0 +1,45 @@ +tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts(1,27): error TS2307: Cannot find module 'missing'. + + +==== tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts (1 errors) ==== + import { MyPromise } from "missing"; + ~~~~~~~~~ +!!! error TS2307: Cannot find module 'missing'. + + declare var p: Promise; + declare var mp: MyPromise; + + async function f0() { } + async function f1(): Promise { } + async function f3(): MyPromise { } + + let f4 = async function() { } + let f5 = async function(): Promise { } + let f6 = async function(): MyPromise { } + + let f7 = async () => { }; + let f8 = async (): Promise => { }; + let f9 = async (): MyPromise => { }; + let f10 = async () => p; + let f11 = async () => mp; + let f12 = async (): Promise => mp; + let f13 = async (): MyPromise => p; + + let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } + }; + + class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } + } + + module M { + export async function f1() { } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js new file mode 100644 index 00000000000..065aa675b6e --- /dev/null +++ b/tests/baselines/reference/asyncAwaitIsolatedModules_es2017.js @@ -0,0 +1,73 @@ +//// [asyncAwaitIsolatedModules_es2017.ts] +import { MyPromise } from "missing"; + +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} + +//// [asyncAwaitIsolatedModules_es2017.js] +async function f0() { } +async function f1() { } +async function f3() { } +let f4 = async function () { }; +let f5 = async function () { }; +let f6 = async function () { }; +let f7 = async () => { }; +let f8 = async () => { }; +let f9 = async () => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async () => mp; +let f13 = async () => p; +let o = { + async m1() { }, + async m2() { }, + async m3() { } +}; +class C { + async m1() { } + async m2() { } + async m3() { } + static async m4() { } + static async m5() { } + static async m6() { } +} +var M; +(function (M) { + async function f1() { } + M.f1 = f1; +})(M || (M = {})); diff --git a/tests/baselines/reference/asyncAwait_es2017.js b/tests/baselines/reference/asyncAwait_es2017.js new file mode 100644 index 00000000000..314c99fa210 --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.js @@ -0,0 +1,73 @@ +//// [asyncAwait_es2017.ts] +type MyPromise = Promise; +declare var MyPromise: typeof Promise; +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} + +//// [asyncAwait_es2017.js] +async function f0() { } +async function f1() { } +async function f3() { } +let f4 = async function () { }; +let f5 = async function () { }; +let f6 = async function () { }; +let f7 = async () => { }; +let f8 = async () => { }; +let f9 = async () => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async () => mp; +let f13 = async () => p; +let o = { + async m1() { }, + async m2() { }, + async m3() { } +}; +class C { + async m1() { } + async m2() { } + async m3() { } + static async m4() { } + static async m5() { } + static async m6() { } +} +var M; +(function (M) { + async function f1() { } + M.f1 = f1; +})(M || (M = {})); diff --git a/tests/baselines/reference/asyncAwait_es2017.symbols b/tests/baselines/reference/asyncAwait_es2017.symbols new file mode 100644 index 00000000000..34dc9802a25 --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.symbols @@ -0,0 +1,118 @@ +=== tests/cases/conformance/async/es2017/asyncAwait_es2017.ts === +type MyPromise = Promise; +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>T : Symbol(T, Decl(asyncAwait_es2017.ts, 0, 15)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>T : Symbol(T, Decl(asyncAwait_es2017.ts, 0, 15)) + +declare var MyPromise: typeof Promise; +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare var p: Promise; +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare var mp: MyPromise; +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +async function f0() { } +>f0 : Symbol(f0, Decl(asyncAwait_es2017.ts, 3, 34)) + +async function f1(): Promise { } +>f1 : Symbol(f1, Decl(asyncAwait_es2017.ts, 5, 23)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +async function f3(): MyPromise { } +>f3 : Symbol(f3, Decl(asyncAwait_es2017.ts, 6, 38)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f4 = async function() { } +>f4 : Symbol(f4, Decl(asyncAwait_es2017.ts, 9, 3)) + +let f5 = async function(): Promise { } +>f5 : Symbol(f5, Decl(asyncAwait_es2017.ts, 10, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +let f6 = async function(): MyPromise { } +>f6 : Symbol(f6, Decl(asyncAwait_es2017.ts, 11, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f7 = async () => { }; +>f7 : Symbol(f7, Decl(asyncAwait_es2017.ts, 13, 3)) + +let f8 = async (): Promise => { }; +>f8 : Symbol(f8, Decl(asyncAwait_es2017.ts, 14, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +let f9 = async (): MyPromise => { }; +>f9 : Symbol(f9, Decl(asyncAwait_es2017.ts, 15, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +let f10 = async () => p; +>f10 : Symbol(f10, Decl(asyncAwait_es2017.ts, 16, 3)) +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) + +let f11 = async () => mp; +>f11 : Symbol(f11, Decl(asyncAwait_es2017.ts, 17, 3)) +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) + +let f12 = async (): Promise => mp; +>f12 : Symbol(f12, Decl(asyncAwait_es2017.ts, 18, 3)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>mp : Symbol(mp, Decl(asyncAwait_es2017.ts, 3, 11)) + +let f13 = async (): MyPromise => p; +>f13 : Symbol(f13, Decl(asyncAwait_es2017.ts, 19, 3)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +>p : Symbol(p, Decl(asyncAwait_es2017.ts, 2, 11)) + +let o = { +>o : Symbol(o, Decl(asyncAwait_es2017.ts, 21, 3)) + + async m1() { }, +>m1 : Symbol(m1, Decl(asyncAwait_es2017.ts, 21, 9)) + + async m2(): Promise { }, +>m2 : Symbol(m2, Decl(asyncAwait_es2017.ts, 22, 16)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + async m3(): MyPromise { } +>m3 : Symbol(m3, Decl(asyncAwait_es2017.ts, 23, 31)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + +}; + +class C { +>C : Symbol(C, Decl(asyncAwait_es2017.ts, 25, 2)) + + async m1() { } +>m1 : Symbol(C.m1, Decl(asyncAwait_es2017.ts, 27, 9)) + + async m2(): Promise { } +>m2 : Symbol(C.m2, Decl(asyncAwait_es2017.ts, 28, 15)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + async m3(): MyPromise { } +>m3 : Symbol(C.m3, Decl(asyncAwait_es2017.ts, 29, 30)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) + + static async m4() { } +>m4 : Symbol(C.m4, Decl(asyncAwait_es2017.ts, 30, 32)) + + static async m5(): Promise { } +>m5 : Symbol(C.m5, Decl(asyncAwait_es2017.ts, 31, 22)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + static async m6(): MyPromise { } +>m6 : Symbol(C.m6, Decl(asyncAwait_es2017.ts, 32, 37)) +>MyPromise : Symbol(MyPromise, Decl(asyncAwait_es2017.ts, 0, 0), Decl(asyncAwait_es2017.ts, 1, 11)) +} + +module M { +>M : Symbol(M, Decl(asyncAwait_es2017.ts, 34, 1)) + + export async function f1() { } +>f1 : Symbol(f1, Decl(asyncAwait_es2017.ts, 36, 10)) +} diff --git a/tests/baselines/reference/asyncAwait_es2017.types b/tests/baselines/reference/asyncAwait_es2017.types new file mode 100644 index 00000000000..a1226d0cbfe --- /dev/null +++ b/tests/baselines/reference/asyncAwait_es2017.types @@ -0,0 +1,129 @@ +=== tests/cases/conformance/async/es2017/asyncAwait_es2017.ts === +type MyPromise = Promise; +>MyPromise : Promise +>T : T +>Promise : Promise +>T : T + +declare var MyPromise: typeof Promise; +>MyPromise : PromiseConstructor +>Promise : PromiseConstructor + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare var mp: MyPromise; +>mp : Promise +>MyPromise : Promise + +async function f0() { } +>f0 : () => Promise + +async function f1(): Promise { } +>f1 : () => Promise +>Promise : Promise + +async function f3(): MyPromise { } +>f3 : () => Promise +>MyPromise : Promise + +let f4 = async function() { } +>f4 : () => Promise +>async function() { } : () => Promise + +let f5 = async function(): Promise { } +>f5 : () => Promise +>async function(): Promise { } : () => Promise +>Promise : Promise + +let f6 = async function(): MyPromise { } +>f6 : () => Promise +>async function(): MyPromise { } : () => Promise +>MyPromise : Promise + +let f7 = async () => { }; +>f7 : () => Promise +>async () => { } : () => Promise + +let f8 = async (): Promise => { }; +>f8 : () => Promise +>async (): Promise => { } : () => Promise +>Promise : Promise + +let f9 = async (): MyPromise => { }; +>f9 : () => Promise +>async (): MyPromise => { } : () => Promise +>MyPromise : Promise + +let f10 = async () => p; +>f10 : () => Promise +>async () => p : () => Promise +>p : Promise + +let f11 = async () => mp; +>f11 : () => Promise +>async () => mp : () => Promise +>mp : Promise + +let f12 = async (): Promise => mp; +>f12 : () => Promise +>async (): Promise => mp : () => Promise +>Promise : Promise +>mp : Promise + +let f13 = async (): MyPromise => p; +>f13 : () => Promise +>async (): MyPromise => p : () => Promise +>MyPromise : Promise +>p : Promise + +let o = { +>o : { m1(): Promise; m2(): Promise; m3(): Promise; } +>{ async m1() { }, async m2(): Promise { }, async m3(): MyPromise { }} : { m1(): Promise; m2(): Promise; m3(): Promise; } + + async m1() { }, +>m1 : () => Promise + + async m2(): Promise { }, +>m2 : () => Promise +>Promise : Promise + + async m3(): MyPromise { } +>m3 : () => Promise +>MyPromise : Promise + +}; + +class C { +>C : C + + async m1() { } +>m1 : () => Promise + + async m2(): Promise { } +>m2 : () => Promise +>Promise : Promise + + async m3(): MyPromise { } +>m3 : () => Promise +>MyPromise : Promise + + static async m4() { } +>m4 : () => Promise + + static async m5(): Promise { } +>m5 : () => Promise +>Promise : Promise + + static async m6(): MyPromise { } +>m6 : () => Promise +>MyPromise : Promise +} + +module M { +>M : typeof M + + export async function f1() { } +>f1 : () => Promise +} diff --git a/tests/baselines/reference/asyncClass_es2017.errors.txt b/tests/baselines/reference/asyncClass_es2017.errors.txt new file mode 100644 index 00000000000..37612b0b0f2 --- /dev/null +++ b/tests/baselines/reference/asyncClass_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/asyncClass_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. + + +==== tests/cases/conformance/async/es2017/asyncClass_es2017.ts (1 errors) ==== + async class C { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncClass_es2017.js b/tests/baselines/reference/asyncClass_es2017.js new file mode 100644 index 00000000000..e619bd50b97 --- /dev/null +++ b/tests/baselines/reference/asyncClass_es2017.js @@ -0,0 +1,7 @@ +//// [asyncClass_es2017.ts] +async class C { +} + +//// [asyncClass_es2017.js] +async class C { +} diff --git a/tests/baselines/reference/asyncConstructor_es2017.errors.txt b/tests/baselines/reference/asyncConstructor_es2017.errors.txt new file mode 100644 index 00000000000..3b0c1b42fa9 --- /dev/null +++ b/tests/baselines/reference/asyncConstructor_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts(2,3): error TS1089: 'async' modifier cannot appear on a constructor declaration. + + +==== tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts (1 errors) ==== + class C { + async constructor() { + ~~~~~ +!!! error TS1089: 'async' modifier cannot appear on a constructor declaration. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncConstructor_es2017.js b/tests/baselines/reference/asyncConstructor_es2017.js new file mode 100644 index 00000000000..7dcd6ec6943 --- /dev/null +++ b/tests/baselines/reference/asyncConstructor_es2017.js @@ -0,0 +1,11 @@ +//// [asyncConstructor_es2017.ts] +class C { + async constructor() { + } +} + +//// [asyncConstructor_es2017.js] +class C { + async constructor() { + } +} diff --git a/tests/baselines/reference/asyncDeclare_es2017.errors.txt b/tests/baselines/reference/asyncDeclare_es2017.errors.txt new file mode 100644 index 00000000000..bb74a3865d5 --- /dev/null +++ b/tests/baselines/reference/asyncDeclare_es2017.errors.txt @@ -0,0 +1,7 @@ +tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts(1,9): error TS1040: 'async' modifier cannot be used in an ambient context. + + +==== tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts (1 errors) ==== + declare async function foo(): Promise; + ~~~~~ +!!! error TS1040: 'async' modifier cannot be used in an ambient context. \ No newline at end of file diff --git a/tests/baselines/reference/asyncDeclare_es2017.js b/tests/baselines/reference/asyncDeclare_es2017.js new file mode 100644 index 00000000000..2ff588b2851 --- /dev/null +++ b/tests/baselines/reference/asyncDeclare_es2017.js @@ -0,0 +1,4 @@ +//// [asyncDeclare_es2017.ts] +declare async function foo(): Promise; + +//// [asyncDeclare_es2017.js] diff --git a/tests/baselines/reference/asyncEnum_es2017.errors.txt b/tests/baselines/reference/asyncEnum_es2017.errors.txt new file mode 100644 index 00000000000..8e0015d0b24 --- /dev/null +++ b/tests/baselines/reference/asyncEnum_es2017.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/async/es2017/asyncEnum_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. + + +==== tests/cases/conformance/async/es2017/asyncEnum_es2017.ts (1 errors) ==== + async enum E { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + Value + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncEnum_es2017.js b/tests/baselines/reference/asyncEnum_es2017.js new file mode 100644 index 00000000000..df1f846c2f9 --- /dev/null +++ b/tests/baselines/reference/asyncEnum_es2017.js @@ -0,0 +1,10 @@ +//// [asyncEnum_es2017.ts] +async enum E { + Value +} + +//// [asyncEnum_es2017.js] +var E; +(function (E) { + E[E["Value"] = 0] = "Value"; +})(E || (E = {})); diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt new file mode 100644 index 00000000000..d5da3432264 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.errors.txt @@ -0,0 +1,26 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,20): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,30): error TS1109: Expression expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,33): error TS1138: Parameter declaration expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,33): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,38): error TS1005: ';' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,39): error TS1128: Declaration or statement expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts(1,53): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts (7 errors) ==== + async function foo(a = await => await): Promise { + ~~~~~~~~~ +!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. + ~~ +!!! error TS1109: Expression expected. + ~~~~~ +!!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js new file mode 100644 index 00000000000..0e687c1e0d5 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration10_es2017.ts] +async function foo(a = await => await): Promise { +} + +//// [asyncFunctionDeclaration10_es2017.js] +await; +Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js new file mode 100644 index 00000000000..0ae906ebfe1 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration11_es2017.ts] +async function await(): Promise { +} + +//// [asyncFunctionDeclaration11_es2017.js] +async function await() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols new file mode 100644 index 00000000000..02c35d81d62 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts === +async function await(): Promise { +>await : Symbol(await, Decl(asyncFunctionDeclaration11_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types new file mode 100644 index 00000000000..b86601bf33d --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration11_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts === +async function await(): Promise { +>await : () => Promise +>Promise : Promise +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt new file mode 100644 index 00000000000..f951bee715c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.errors.txt @@ -0,0 +1,16 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,24): error TS1005: '(' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,29): error TS1005: '=' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,33): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts(1,47): error TS1005: '=>' expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts (4 errors) ==== + var v = async function await(): Promise { } + ~~~~~ +!!! error TS1005: '(' expected. + ~ +!!! error TS1005: '=' expected. + ~~~~~~~~~~~~~ +!!! error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. + ~ +!!! error TS1005: '=>' expected. \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js new file mode 100644 index 00000000000..69f5993f5c0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js @@ -0,0 +1,5 @@ +//// [asyncFunctionDeclaration12_es2017.ts] +var v = async function await(): Promise { } + +//// [asyncFunctionDeclaration12_es2017.js] +var v = , await = () => { }; diff --git a/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt new file mode 100644 index 00000000000..41ea0a7cafb --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts(3,11): error TS2304: Cannot find name 'await'. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts (1 errors) ==== + async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js new file mode 100644 index 00000000000..a16236aea7f --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration13_es2017.js @@ -0,0 +1,12 @@ +//// [asyncFunctionDeclaration13_es2017.ts] +async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; +} + + +//// [asyncFunctionDeclaration13_es2017.js] +async function foo() { + // Legal to use 'await' in a type context. + var v; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js new file mode 100644 index 00000000000..308b8f1763c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.js @@ -0,0 +1,9 @@ +//// [asyncFunctionDeclaration14_es2017.ts] +async function foo(): Promise { + return; +} + +//// [asyncFunctionDeclaration14_es2017.js] +async function foo() { + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols new file mode 100644 index 00000000000..1b5bca844c0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.symbols @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts === +async function foo(): Promise { +>foo : Symbol(foo, Decl(asyncFunctionDeclaration14_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types new file mode 100644 index 00000000000..1e505f93a2c --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration14_es2017.types @@ -0,0 +1,7 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts === +async function foo(): Promise { +>foo : () => Promise +>Promise : Promise + + return; +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt new file mode 100644 index 00000000000..efc1e2440bf --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt @@ -0,0 +1,48 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(6,23): error TS1064: The return type of an async function or method must be the global Promise type. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(7,23): error TS1064: The return type of an async function or method must be the global Promise type. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(8,23): error TS1064: The return type of an async function or method must be the global Promise type. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(9,23): error TS1064: The return type of an async function or method must be the global Promise type. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(10,23): error TS1064: The return type of an async function or method must be the global Promise type. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(17,16): error TS1059: Return expression in async function does not have a valid callable 'then' member. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(23,25): error TS1058: Operand for 'await' does not have a valid callable 'then' member. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts (7 errors) ==== + declare class Thenable { then(): void; } + declare let a: any; + declare let obj: { then: string; }; + declare let thenable: Thenable; + async function fn1() { } // valid: Promise + async function fn2(): { } { } // error + ~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + async function fn3(): any { } // error + ~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + async function fn4(): number { } // error + ~~~~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + async function fn5(): PromiseLike { } // error + ~~~~~~~~~~~~~~~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + async function fn6(): Thenable { } // error + ~~~~~~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + async function fn7() { return; } // valid: Promise + async function fn8() { return 1; } // valid: Promise + async function fn9() { return null; } // valid: Promise + async function fn10() { return undefined; } // valid: Promise + async function fn11() { return a; } // valid: Promise + async function fn12() { return obj; } // valid: Promise<{ then: string; }> + async function fn13() { return thenable; } // error + ~~~~ +!!! error TS1059: Return expression in async function does not have a valid callable 'then' member. + async function fn14() { await 1; } // valid: Promise + async function fn15() { await null; } // valid: Promise + async function fn16() { await undefined; } // valid: Promise + async function fn17() { await a; } // valid: Promise + async function fn18() { await obj; } // valid: Promise + async function fn19() { await thenable; } // error + ~~~~~~~~~~~~~~ +!!! error TS1058: Operand for 'await' does not have a valid callable 'then' member. + \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js new file mode 100644 index 00000000000..5704366025e --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js @@ -0,0 +1,64 @@ +//// [asyncFunctionDeclaration15_es2017.ts] +declare class Thenable { then(): void; } +declare let a: any; +declare let obj: { then: string; }; +declare let thenable: Thenable; +async function fn1() { } // valid: Promise +async function fn2(): { } { } // error +async function fn3(): any { } // error +async function fn4(): number { } // error +async function fn5(): PromiseLike { } // error +async function fn6(): Thenable { } // error +async function fn7() { return; } // valid: Promise +async function fn8() { return 1; } // valid: Promise +async function fn9() { return null; } // valid: Promise +async function fn10() { return undefined; } // valid: Promise +async function fn11() { return a; } // valid: Promise +async function fn12() { return obj; } // valid: Promise<{ then: string; }> +async function fn13() { return thenable; } // error +async function fn14() { await 1; } // valid: Promise +async function fn15() { await null; } // valid: Promise +async function fn16() { await undefined; } // valid: Promise +async function fn17() { await a; } // valid: Promise +async function fn18() { await obj; } // valid: Promise +async function fn19() { await thenable; } // error + + +//// [asyncFunctionDeclaration15_es2017.js] +async function fn1() { } // valid: Promise +// valid: Promise +async function fn2() { } // error +// error +async function fn3() { } // error +// error +async function fn4() { } // error +// error +async function fn5() { } // error +// error +async function fn6() { } // error +// error +async function fn7() { return; } // valid: Promise +// valid: Promise +async function fn8() { return 1; } // valid: Promise +// valid: Promise +async function fn9() { return null; } // valid: Promise +// valid: Promise +async function fn10() { return undefined; } // valid: Promise +// valid: Promise +async function fn11() { return a; } // valid: Promise +// valid: Promise +async function fn12() { return obj; } // valid: Promise<{ then: string; }> +// valid: Promise<{ then: string; }> +async function fn13() { return thenable; } // error +// error +async function fn14() { await 1; } // valid: Promise +// valid: Promise +async function fn15() { await null; } // valid: Promise +// valid: Promise +async function fn16() { await undefined; } // valid: Promise +// valid: Promise +async function fn17() { await a; } // valid: Promise +// valid: Promise +async function fn18() { await obj; } // valid: Promise +// valid: Promise +async function fn19() { await thenable; } // error diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js new file mode 100644 index 00000000000..549fd226b2f --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration1_es2017.ts] +async function foo(): Promise { +} + +//// [asyncFunctionDeclaration1_es2017.js] +async function foo() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols new file mode 100644 index 00000000000..a712df45896 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts === +async function foo(): Promise { +>foo : Symbol(foo, Decl(asyncFunctionDeclaration1_es2017.ts, 0, 0)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types new file mode 100644 index 00000000000..ff97e686c43 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration1_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts === +async function foo(): Promise { +>foo : () => Promise +>Promise : Promise +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js new file mode 100644 index 00000000000..6de061456e8 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration2_es2017.ts] +function f(await) { +} + +//// [asyncFunctionDeclaration2_es2017.js] +function f(await) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols new file mode 100644 index 00000000000..aed41f50310 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts === +function f(await) { +>f : Symbol(f, Decl(asyncFunctionDeclaration2_es2017.ts, 0, 0)) +>await : Symbol(await, Decl(asyncFunctionDeclaration2_es2017.ts, 0, 11)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types new file mode 100644 index 00000000000..8413bea692a --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration2_es2017.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts === +function f(await) { +>f : (await: any) => void +>await : any +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt new file mode 100644 index 00000000000..53a85074834 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts(1,20): error TS2372: Parameter 'await' cannot be referenced in its initializer. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts (1 errors) ==== + function f(await = await) { + ~~~~~ +!!! error TS2372: Parameter 'await' cannot be referenced in its initializer. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js new file mode 100644 index 00000000000..d6110265fdc --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration3_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration3_es2017.ts] +function f(await = await) { +} + +//// [asyncFunctionDeclaration3_es2017.js] +function f(await = await) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js new file mode 100644 index 00000000000..6209531e549 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration4_es2017.ts] +function await() { +} + +//// [asyncFunctionDeclaration4_es2017.js] +function await() { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols new file mode 100644 index 00000000000..7afbd879c59 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.symbols @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts === +function await() { +>await : Symbol(await, Decl(asyncFunctionDeclaration4_es2017.ts, 0, 0)) +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types new file mode 100644 index 00000000000..f7c4248f7c3 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration4_es2017.types @@ -0,0 +1,4 @@ +=== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts === +function await() { +>await : () => void +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt new file mode 100644 index 00000000000..ad8c0280206 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,20): error TS1138: Parameter declaration expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,20): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,25): error TS1005: ';' expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,26): error TS1128: Declaration or statement expected. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts(1,40): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts (5 errors) ==== + async function foo(await): Promise { + ~~~~~ +!!! error TS1138: Parameter declaration expected. + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js new file mode 100644 index 00000000000..13c04c5d5bc --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration5_es2017.ts] +async function foo(await): Promise { +} + +//// [asyncFunctionDeclaration5_es2017.js] +await; +Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt new file mode 100644 index 00000000000..b5a5ddccdce --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts(1,24): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts(1,29): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts (2 errors) ==== + async function foo(a = await): Promise { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js new file mode 100644 index 00000000000..6df02000846 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration6_es2017.js @@ -0,0 +1,7 @@ +//// [asyncFunctionDeclaration6_es2017.ts] +async function foo(a = await): Promise { +} + +//// [asyncFunctionDeclaration6_es2017.js] +async function foo(a = await ) { +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt new file mode 100644 index 00000000000..ad9ec9a043a --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts(3,26): error TS2524: 'await' expressions cannot be used in a parameter initializer. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts(3,31): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts (2 errors) ==== + async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + ~~~~~ +!!! error TS2524: 'await' expressions cannot be used in a parameter initializer. + ~ +!!! error TS1109: Expression expected. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js new file mode 100644 index 00000000000..c9aaa80b9b0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration7_es2017.js @@ -0,0 +1,13 @@ +//// [asyncFunctionDeclaration7_es2017.ts] +async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + } +} + +//// [asyncFunctionDeclaration7_es2017.js] +async function bar() { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await ) { + } +} diff --git a/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt new file mode 100644 index 00000000000..b82f012d694 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts(1,12): error TS2304: Cannot find name 'await'. +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts(1,20): error TS2304: Cannot find name 'foo'. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts (2 errors) ==== + var v = { [await]: foo } + ~~~~~ +!!! error TS2304: Cannot find name 'await'. + ~~~ +!!! error TS2304: Cannot find name 'foo'. \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js new file mode 100644 index 00000000000..db7bfa4f9fb --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration8_es2017.js @@ -0,0 +1,5 @@ +//// [asyncFunctionDeclaration8_es2017.ts] +var v = { [await]: foo } + +//// [asyncFunctionDeclaration8_es2017.js] +var v = { [await]: foo }; diff --git a/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt new file mode 100644 index 00000000000..27c41d8b253 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts(2,19): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts (1 errors) ==== + async function foo(): Promise { + var v = { [await]: foo } + ~ +!!! error TS1109: Expression expected. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js new file mode 100644 index 00000000000..08cb8e44ba0 --- /dev/null +++ b/tests/baselines/reference/asyncFunctionDeclaration9_es2017.js @@ -0,0 +1,9 @@ +//// [asyncFunctionDeclaration9_es2017.ts] +async function foo(): Promise { + var v = { [await]: foo } +} + +//// [asyncFunctionDeclaration9_es2017.js] +async function foo() { + var v = { [await ]: foo }; +} diff --git a/tests/baselines/reference/asyncGetter_es2017.errors.txt b/tests/baselines/reference/asyncGetter_es2017.errors.txt new file mode 100644 index 00000000000..386e95d5977 --- /dev/null +++ b/tests/baselines/reference/asyncGetter_es2017.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/async/es2017/asyncGetter_es2017.ts(2,3): error TS1042: 'async' modifier cannot be used here. +tests/cases/conformance/async/es2017/asyncGetter_es2017.ts(2,13): error TS2378: A 'get' accessor must return a value. + + +==== tests/cases/conformance/async/es2017/asyncGetter_es2017.ts (2 errors) ==== + class C { + async get foo() { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + ~~~ +!!! error TS2378: A 'get' accessor must return a value. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncGetter_es2017.js b/tests/baselines/reference/asyncGetter_es2017.js new file mode 100644 index 00000000000..ad8fa347cb5 --- /dev/null +++ b/tests/baselines/reference/asyncGetter_es2017.js @@ -0,0 +1,11 @@ +//// [asyncGetter_es2017.ts] +class C { + async get foo() { + } +} + +//// [asyncGetter_es2017.js] +class C { + async get foo() { + } +} diff --git a/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt b/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt new file mode 100644 index 00000000000..a0348b2e691 --- /dev/null +++ b/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/async/es2017/test.ts(3,25): error TS1064: The return type of an async function or method must be the global Promise type. + + +==== tests/cases/conformance/async/es2017/task.ts (0 errors) ==== + export class Task extends Promise { } + +==== tests/cases/conformance/async/es2017/test.ts (1 errors) ==== + import { Task } from "./task"; + class Test { + async example(): Task { return; } + ~~~~~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncImportedPromise_es2017.js b/tests/baselines/reference/asyncImportedPromise_es2017.js new file mode 100644 index 00000000000..a48c58c1707 --- /dev/null +++ b/tests/baselines/reference/asyncImportedPromise_es2017.js @@ -0,0 +1,21 @@ +//// [tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts] //// + +//// [task.ts] +export class Task extends Promise { } + +//// [test.ts] +import { Task } from "./task"; +class Test { + async example(): Task { return; } +} + +//// [task.js] +"use strict"; +class Task extends Promise { +} +exports.Task = Task; +//// [test.js] +"use strict"; +class Test { + async example() { return; } +} diff --git a/tests/baselines/reference/asyncInterface_es2017.errors.txt b/tests/baselines/reference/asyncInterface_es2017.errors.txt new file mode 100644 index 00000000000..dfbc8789797 --- /dev/null +++ b/tests/baselines/reference/asyncInterface_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/asyncInterface_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. + + +==== tests/cases/conformance/async/es2017/asyncInterface_es2017.ts (1 errors) ==== + async interface I { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncInterface_es2017.js b/tests/baselines/reference/asyncInterface_es2017.js new file mode 100644 index 00000000000..4d897389538 --- /dev/null +++ b/tests/baselines/reference/asyncInterface_es2017.js @@ -0,0 +1,5 @@ +//// [asyncInterface_es2017.ts] +async interface I { +} + +//// [asyncInterface_es2017.js] diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.js b/tests/baselines/reference/asyncMethodWithSuper_es2017.js new file mode 100644 index 00000000000..b6925793163 --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.js @@ -0,0 +1,90 @@ +//// [asyncMethodWithSuper_es2017.ts] +class A { + x() { + } +} + +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => {}; + + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + + // property access (assign) + super.x = f; + + // element access (assign) + super["x"] = f; + + // destructuring assign with property access + ({ f: super.x } = { f }); + + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} + +//// [asyncMethodWithSuper_es2017.js] +class A { + x() { + } +} +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + // call with element access + super["x"](); + // property access (read) + const a = super.x; + // element access (read) + const b = super["x"]; + } + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => { }; + // call with property access + super.x(); + // call with element access + super["x"](); + // property access (read) + const a = super.x; + // element access (read) + const b = super["x"]; + // property access (assign) + super.x = f; + // element access (assign) + super["x"] = f; + // destructuring assign with property access + ({ f: super.x } = { f }); + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols new file mode 100644 index 00000000000..39ed91d7acb --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols @@ -0,0 +1,102 @@ +=== tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts === +class A { +>A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) + + x() { +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + } +} + +class B extends A { +>B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 3, 1)) +>A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) + + // async method with only call/get on 'super' does not require a binding + async simple() { +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 5, 19)) + + // call with property access + super.x(); +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // call with element access + super["x"](); +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (read) + const a = super.x; +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 15, 13)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // element access (read) + const b = super["x"]; +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 18, 13)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 19, 5)) + + const f = () => {}; +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // call with property access + super.x(); +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // call with element access + super["x"](); +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (read) + const a = super.x; +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 32, 13)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // element access (read) + const b = super["x"]; +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 35, 13)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + + // property access (assign) + super.x = f; +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // element access (assign) + super["x"] = f; +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) + + // destructuring assign with property access + ({ f: super.x } = { f }); +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 10)) +>super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 27)) + + // destructuring assign with element access + ({ f: super["x"] } = { f }); +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 10)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 30)) + } +} diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.types b/tests/baselines/reference/asyncMethodWithSuper_es2017.types new file mode 100644 index 00000000000..b2678e8b837 --- /dev/null +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.types @@ -0,0 +1,123 @@ +=== tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts === +class A { +>A : A + + x() { +>x : () => void + } +} + +class B extends A { +>B : B +>A : A + + // async method with only call/get on 'super' does not require a binding + async simple() { +>simple : () => Promise + + // call with property access + super.x(); +>super.x() : void +>super.x : () => void +>super : A +>x : () => void + + // call with element access + super["x"](); +>super["x"]() : void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (read) + const a = super.x; +>a : () => void +>super.x : () => void +>super : A +>x : () => void + + // element access (read) + const b = super["x"]; +>b : () => void +>super["x"] : () => void +>super : A +>"x" : "x" + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { +>advanced : () => Promise + + const f = () => {}; +>f : () => void +>() => {} : () => void + + // call with property access + super.x(); +>super.x() : void +>super.x : () => void +>super : A +>x : () => void + + // call with element access + super["x"](); +>super["x"]() : void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (read) + const a = super.x; +>a : () => void +>super.x : () => void +>super : A +>x : () => void + + // element access (read) + const b = super["x"]; +>b : () => void +>super["x"] : () => void +>super : A +>"x" : "x" + + // property access (assign) + super.x = f; +>super.x = f : () => void +>super.x : () => void +>super : A +>x : () => void +>f : () => void + + // element access (assign) + super["x"] = f; +>super["x"] = f : () => void +>super["x"] : () => void +>super : A +>"x" : "x" +>f : () => void + + // destructuring assign with property access + ({ f: super.x } = { f }); +>({ f: super.x } = { f }) : { f: () => void; } +>{ f: super.x } = { f } : { f: () => void; } +>{ f: super.x } : { f: () => void; } +>f : () => void +>super.x : () => void +>super : A +>x : () => void +>{ f } : { f: () => void; } +>f : () => void + + // destructuring assign with element access + ({ f: super["x"] } = { f }); +>({ f: super["x"] } = { f }) : { f: () => void; } +>{ f: super["x"] } = { f } : { f: () => void; } +>{ f: super["x"] } : { f: () => void; } +>f : () => void +>super["x"] : () => void +>super : A +>"x" : "x" +>{ f } : { f: () => void; } +>f : () => void + } +} diff --git a/tests/baselines/reference/asyncModule_es2017.errors.txt b/tests/baselines/reference/asyncModule_es2017.errors.txt new file mode 100644 index 00000000000..8b6a4c3dc66 --- /dev/null +++ b/tests/baselines/reference/asyncModule_es2017.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/async/es2017/asyncModule_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. + + +==== tests/cases/conformance/async/es2017/asyncModule_es2017.ts (1 errors) ==== + async module M { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncModule_es2017.js b/tests/baselines/reference/asyncModule_es2017.js new file mode 100644 index 00000000000..fe3e17d5e74 --- /dev/null +++ b/tests/baselines/reference/asyncModule_es2017.js @@ -0,0 +1,5 @@ +//// [asyncModule_es2017.ts] +async module M { +} + +//// [asyncModule_es2017.js] diff --git a/tests/baselines/reference/asyncMultiFile_es2017.js b/tests/baselines/reference/asyncMultiFile_es2017.js new file mode 100644 index 00000000000..804a58e4b4c --- /dev/null +++ b/tests/baselines/reference/asyncMultiFile_es2017.js @@ -0,0 +1,11 @@ +//// [tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts] //// + +//// [a.ts] +async function f() {} +//// [b.ts] +function g() { } + +//// [a.js] +async function f() { } +//// [b.js] +function g() { } diff --git a/tests/baselines/reference/asyncMultiFile_es2017.symbols b/tests/baselines/reference/asyncMultiFile_es2017.symbols new file mode 100644 index 00000000000..9d8ff6dbe85 --- /dev/null +++ b/tests/baselines/reference/asyncMultiFile_es2017.symbols @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/a.ts === +async function f() {} +>f : Symbol(f, Decl(a.ts, 0, 0)) + +=== tests/cases/conformance/async/es2017/b.ts === +function g() { } +>g : Symbol(g, Decl(b.ts, 0, 0)) + diff --git a/tests/baselines/reference/asyncMultiFile_es2017.types b/tests/baselines/reference/asyncMultiFile_es2017.types new file mode 100644 index 00000000000..e1f8da34c94 --- /dev/null +++ b/tests/baselines/reference/asyncMultiFile_es2017.types @@ -0,0 +1,8 @@ +=== tests/cases/conformance/async/es2017/a.ts === +async function f() {} +>f : () => Promise + +=== tests/cases/conformance/async/es2017/b.ts === +function g() { } +>g : () => void + diff --git a/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt b/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt new file mode 100644 index 00000000000..b9027c36539 --- /dev/null +++ b/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts(6,21): error TS1064: The return type of an async function or method must be the global Promise type. + + +==== tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts (1 errors) ==== + namespace X { + export class MyPromise extends Promise { + } + } + + async function f(): X.MyPromise { + ~~~~~~~~~~~~~~~~~ +!!! error TS1064: The return type of an async function or method must be the global Promise type. + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncQualifiedReturnType_es2017.js b/tests/baselines/reference/asyncQualifiedReturnType_es2017.js new file mode 100644 index 00000000000..164a4fef610 --- /dev/null +++ b/tests/baselines/reference/asyncQualifiedReturnType_es2017.js @@ -0,0 +1,18 @@ +//// [asyncQualifiedReturnType_es2017.ts] +namespace X { + export class MyPromise extends Promise { + } +} + +async function f(): X.MyPromise { +} + +//// [asyncQualifiedReturnType_es2017.js] +var X; +(function (X) { + class MyPromise extends Promise { + } + X.MyPromise = MyPromise; +})(X || (X = {})); +async function f() { +} diff --git a/tests/baselines/reference/asyncSetter_es2017.errors.txt b/tests/baselines/reference/asyncSetter_es2017.errors.txt new file mode 100644 index 00000000000..0acd8538f20 --- /dev/null +++ b/tests/baselines/reference/asyncSetter_es2017.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/async/es2017/asyncSetter_es2017.ts(2,3): error TS1042: 'async' modifier cannot be used here. + + +==== tests/cases/conformance/async/es2017/asyncSetter_es2017.ts (1 errors) ==== + class C { + async set foo(value) { + ~~~~~ +!!! error TS1042: 'async' modifier cannot be used here. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/asyncSetter_es2017.js b/tests/baselines/reference/asyncSetter_es2017.js new file mode 100644 index 00000000000..8260c5232a2 --- /dev/null +++ b/tests/baselines/reference/asyncSetter_es2017.js @@ -0,0 +1,11 @@ +//// [asyncSetter_es2017.ts] +class C { + async set foo(value) { + } +} + +//// [asyncSetter_es2017.js] +class C { + async set foo(value) { + } +} diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js new file mode 100644 index 00000000000..c97fda43011 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.js @@ -0,0 +1,9 @@ +//// [asyncUnParenthesizedArrowFunction_es2017.ts] + +declare function someOtherFunction(i: any): Promise; +const x = async i => await someOtherFunction(i) +const x1 = async (i) => await someOtherFunction(i); + +//// [asyncUnParenthesizedArrowFunction_es2017.js] +const x = async (i) => await someOtherFunction(i); +const x1 = async (i) => await someOtherFunction(i); diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols new file mode 100644 index 00000000000..b5f83de6021 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts === + +declare function someOtherFunction(i: any): Promise; +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 1, 35)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +const x = async i => await someOtherFunction(i) +>x : Symbol(x, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 5)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 15)) +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 2, 15)) + +const x1 = async (i) => await someOtherFunction(i); +>x1 : Symbol(x1, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 5)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 18)) +>someOtherFunction : Symbol(someOtherFunction, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 0, 0)) +>i : Symbol(i, Decl(asyncUnParenthesizedArrowFunction_es2017.ts, 3, 18)) + diff --git a/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types new file mode 100644 index 00000000000..ff573e29ed3 --- /dev/null +++ b/tests/baselines/reference/asyncUnParenthesizedArrowFunction_es2017.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts === + +declare function someOtherFunction(i: any): Promise; +>someOtherFunction : (i: any) => Promise +>i : any +>Promise : Promise + +const x = async i => await someOtherFunction(i) +>x : (i: any) => Promise +>async i => await someOtherFunction(i) : (i: any) => Promise +>i : any +>await someOtherFunction(i) : void +>someOtherFunction(i) : Promise +>someOtherFunction : (i: any) => Promise +>i : any + +const x1 = async (i) => await someOtherFunction(i); +>x1 : (i: any) => Promise +>async (i) => await someOtherFunction(i) : (i: any) => Promise +>i : any +>await someOtherFunction(i) : void +>someOtherFunction(i) : Promise +>someOtherFunction : (i: any) => Promise +>i : any + diff --git a/tests/baselines/reference/asyncUseStrict_es2017.js b/tests/baselines/reference/asyncUseStrict_es2017.js new file mode 100644 index 00000000000..1b9d1dc7f20 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.js @@ -0,0 +1,13 @@ +//// [asyncUseStrict_es2017.ts] +declare var a: boolean; +declare var p: Promise; +async function func(): Promise { + "use strict"; + var b = await p || a; +} + +//// [asyncUseStrict_es2017.js] +async function func() { + "use strict"; + var b = await p || a; +} diff --git a/tests/baselines/reference/asyncUseStrict_es2017.symbols b/tests/baselines/reference/asyncUseStrict_es2017.symbols new file mode 100644 index 00000000000..23fd654ca29 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.symbols @@ -0,0 +1,18 @@ +=== tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(asyncUseStrict_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(asyncUseStrict_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +async function func(): Promise { +>func : Symbol(func, Decl(asyncUseStrict_es2017.ts, 1, 32)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + "use strict"; + var b = await p || a; +>b : Symbol(b, Decl(asyncUseStrict_es2017.ts, 4, 7)) +>p : Symbol(p, Decl(asyncUseStrict_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(asyncUseStrict_es2017.ts, 0, 11)) +} diff --git a/tests/baselines/reference/asyncUseStrict_es2017.types b/tests/baselines/reference/asyncUseStrict_es2017.types new file mode 100644 index 00000000000..267eda83525 --- /dev/null +++ b/tests/baselines/reference/asyncUseStrict_es2017.types @@ -0,0 +1,22 @@ +=== tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + "use strict"; +>"use strict" : "use strict" + + var b = await p || a; +>b : boolean +>await p || a : boolean +>await p : boolean +>p : Promise +>a : boolean +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.js b/tests/baselines/reference/awaitBinaryExpression1_es2017.js new file mode 100644 index 00000000000..9016a2b5826 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression1_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p || a; + after(); +} + +//// [awaitBinaryExpression1_es2017.js] +async function func() { + before(); + var b = await p || a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols new file mode 100644 index 00000000000..827769b3db5 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression1_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression1_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression1_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression1_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression1_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression1_es2017.ts, 1, 32)) + + var b = await p || a; +>b : Symbol(b, Decl(awaitBinaryExpression1_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression1_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression1_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression1_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression1_es2017.types b/tests/baselines/reference/awaitBinaryExpression1_es2017.types new file mode 100644 index 00000000000..c86631804c5 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression1_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p || a; +>b : boolean +>await p || a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.js b/tests/baselines/reference/awaitBinaryExpression2_es2017.js new file mode 100644 index 00000000000..1d5ad324fda --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression2_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p && a; + after(); +} + +//// [awaitBinaryExpression2_es2017.js] +async function func() { + before(); + var b = await p && a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols new file mode 100644 index 00000000000..549eb49cf92 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression2_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression2_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression2_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression2_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression2_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression2_es2017.ts, 1, 32)) + + var b = await p && a; +>b : Symbol(b, Decl(awaitBinaryExpression2_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression2_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression2_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression2_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression2_es2017.types b/tests/baselines/reference/awaitBinaryExpression2_es2017.types new file mode 100644 index 00000000000..f803b1ac840 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression2_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p && a; +>b : boolean +>await p && a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.js b/tests/baselines/reference/awaitBinaryExpression3_es2017.js new file mode 100644 index 00000000000..c752ec3be4a --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression3_es2017.ts] +declare var a: number; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p + a; + after(); +} + +//// [awaitBinaryExpression3_es2017.js] +async function func() { + before(); + var b = await p + a; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols new file mode 100644 index 00000000000..29c8fb7f398 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts === +declare var a: number; +>a : Symbol(a, Decl(awaitBinaryExpression3_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression3_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression3_es2017.ts, 1, 31)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression3_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression3_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression3_es2017.ts, 1, 31)) + + var b = await p + a; +>b : Symbol(b, Decl(awaitBinaryExpression3_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression3_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression3_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression3_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression3_es2017.types b/tests/baselines/reference/awaitBinaryExpression3_es2017.types new file mode 100644 index 00000000000..623d0695237 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression3_es2017.types @@ -0,0 +1,33 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts === +declare var a: number; +>a : number + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = await p + a; +>b : number +>await p + a : number +>await p : number +>p : Promise +>a : number + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.js b/tests/baselines/reference/awaitBinaryExpression4_es2017.js new file mode 100644 index 00000000000..3fc296ea142 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.js @@ -0,0 +1,17 @@ +//// [awaitBinaryExpression4_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await p, a); + after(); +} + +//// [awaitBinaryExpression4_es2017.js] +async function func() { + before(); + var b = (await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols new file mode 100644 index 00000000000..0db5a20e0c1 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.symbols @@ -0,0 +1,29 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression4_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression4_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression4_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression4_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression4_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression4_es2017.ts, 1, 32)) + + var b = (await p, a); +>b : Symbol(b, Decl(awaitBinaryExpression4_es2017.ts, 6, 7)) +>p : Symbol(p, Decl(awaitBinaryExpression4_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitBinaryExpression4_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression4_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression4_es2017.types b/tests/baselines/reference/awaitBinaryExpression4_es2017.types new file mode 100644 index 00000000000..714b6b1ea3a --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression4_es2017.types @@ -0,0 +1,34 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await p, a); +>b : boolean +>(await p, a) : boolean +>await p, a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.js b/tests/baselines/reference/awaitBinaryExpression5_es2017.js new file mode 100644 index 00000000000..b6c5e12ce76 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.js @@ -0,0 +1,19 @@ +//// [awaitBinaryExpression5_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var o: { a: boolean; }; + o.a = await p; + after(); +} + +//// [awaitBinaryExpression5_es2017.js] +async function func() { + before(); + var o; + o.a = await p; + after(); +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols b/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols new file mode 100644 index 00000000000..e2d30c658f7 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.symbols @@ -0,0 +1,34 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitBinaryExpression5_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitBinaryExpression5_es2017.ts, 1, 32)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitBinaryExpression5_es2017.ts, 2, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitBinaryExpression5_es2017.ts, 3, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitBinaryExpression5_es2017.ts, 1, 32)) + + var o: { a: boolean; }; +>o : Symbol(o, Decl(awaitBinaryExpression5_es2017.ts, 6, 7)) +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) + + o.a = await p; +>o.a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) +>o : Symbol(o, Decl(awaitBinaryExpression5_es2017.ts, 6, 7)) +>a : Symbol(a, Decl(awaitBinaryExpression5_es2017.ts, 6, 12)) +>p : Symbol(p, Decl(awaitBinaryExpression5_es2017.ts, 1, 11)) + + after(); +>after : Symbol(after, Decl(awaitBinaryExpression5_es2017.ts, 2, 32)) +} diff --git a/tests/baselines/reference/awaitBinaryExpression5_es2017.types b/tests/baselines/reference/awaitBinaryExpression5_es2017.types new file mode 100644 index 00000000000..763f9e50862 --- /dev/null +++ b/tests/baselines/reference/awaitBinaryExpression5_es2017.types @@ -0,0 +1,38 @@ +=== tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var o: { a: boolean; }; +>o : { a: boolean; } +>a : boolean + + o.a = await p; +>o.a = await p : boolean +>o.a : boolean +>o : { a: boolean; } +>a : boolean +>await p : boolean +>p : Promise + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.js b/tests/baselines/reference/awaitCallExpression1_es2017.js new file mode 100644 index 00000000000..89fe7dfd912 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression1_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, a, a); + after(); +} + +//// [awaitCallExpression1_es2017.js] +async function func() { + before(); + var b = fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.symbols b/tests/baselines/reference/awaitCallExpression1_es2017.symbols new file mode 100644 index 00000000000..68c28d15350 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression1_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression1_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression1_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression1_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression1_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression1_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression1_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression1_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression1_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression1_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression1_es2017.ts, 5, 84)) + + var b = fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression1_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression1_es2017.ts, 1, 32)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression1_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression1_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression1_es2017.types b/tests/baselines/reference/awaitCallExpression1_es2017.types new file mode 100644 index 00000000000..c5cea091878 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression1_es2017.types @@ -0,0 +1,62 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(a, a, a); +>b : void +>fn(a, a, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.js b/tests/baselines/reference/awaitCallExpression2_es2017.js new file mode 100644 index 00000000000..24b3012f85d --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression2_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(await p, a, a); + after(); +} + +//// [awaitCallExpression2_es2017.js] +async function func() { + before(); + var b = fn(await p, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.symbols b/tests/baselines/reference/awaitCallExpression2_es2017.symbols new file mode 100644 index 00000000000..4528ae4c074 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression2_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression2_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression2_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression2_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression2_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression2_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression2_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression2_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression2_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression2_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression2_es2017.ts, 5, 84)) + + var b = fn(await p, a, a); +>b : Symbol(b, Decl(awaitCallExpression2_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression2_es2017.ts, 1, 32)) +>p : Symbol(p, Decl(awaitCallExpression2_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression2_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression2_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression2_es2017.types b/tests/baselines/reference/awaitCallExpression2_es2017.types new file mode 100644 index 00000000000..a15609a4078 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression2_es2017.types @@ -0,0 +1,63 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(await p, a, a); +>b : void +>fn(await p, a, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await p : boolean +>p : Promise +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.js b/tests/baselines/reference/awaitCallExpression3_es2017.js new file mode 100644 index 00000000000..6b432851b00 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression3_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, await p, a); + after(); +} + +//// [awaitCallExpression3_es2017.js] +async function func() { + before(); + var b = fn(a, await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.symbols b/tests/baselines/reference/awaitCallExpression3_es2017.symbols new file mode 100644 index 00000000000..a1120103fb0 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression3_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression3_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression3_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression3_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression3_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression3_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression3_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression3_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression3_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression3_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression3_es2017.ts, 5, 84)) + + var b = fn(a, await p, a); +>b : Symbol(b, Decl(awaitCallExpression3_es2017.ts, 10, 7)) +>fn : Symbol(fn, Decl(awaitCallExpression3_es2017.ts, 1, 32)) +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) +>p : Symbol(p, Decl(awaitCallExpression3_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression3_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression3_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression3_es2017.types b/tests/baselines/reference/awaitCallExpression3_es2017.types new file mode 100644 index 00000000000..a491836fa06 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression3_es2017.types @@ -0,0 +1,63 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = fn(a, await p, a); +>b : void +>fn(a, await p, a) : void +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.js b/tests/baselines/reference/awaitCallExpression4_es2017.js new file mode 100644 index 00000000000..9243ac58f82 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression4_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await pfn)(a, a, a); + after(); +} + +//// [awaitCallExpression4_es2017.js] +async function func() { + before(); + var b = (await pfn)(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.symbols b/tests/baselines/reference/awaitCallExpression4_es2017.symbols new file mode 100644 index 00000000000..fb607d9841f --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.symbols @@ -0,0 +1,59 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression4_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression4_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression4_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression4_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression4_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression4_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression4_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression4_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression4_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression4_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression4_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression4_es2017.ts, 5, 84)) + + var b = (await pfn)(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression4_es2017.ts, 10, 7)) +>pfn : Symbol(pfn, Decl(awaitCallExpression4_es2017.ts, 4, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression4_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression4_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression4_es2017.types b/tests/baselines/reference/awaitCallExpression4_es2017.types new file mode 100644 index 00000000000..3f1b478e669 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression4_es2017.types @@ -0,0 +1,64 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await pfn)(a, a, a); +>b : void +>(await pfn)(a, a, a) : void +>(await pfn) : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await pfn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.js b/tests/baselines/reference/awaitCallExpression5_es2017.js new file mode 100644 index 00000000000..d08823ac5a3 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression5_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, a, a); + after(); +} + +//// [awaitCallExpression5_es2017.js] +async function func() { + before(); + var b = o.fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.symbols b/tests/baselines/reference/awaitCallExpression5_es2017.symbols new file mode 100644 index 00000000000..3854353314a --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression5_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression5_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression5_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression5_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression5_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression5_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression5_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression5_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression5_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression5_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression5_es2017.ts, 5, 84)) + + var b = o.fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression5_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression5_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression5_es2017.ts, 3, 16)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression5_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression5_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression5_es2017.types b/tests/baselines/reference/awaitCallExpression5_es2017.types new file mode 100644 index 00000000000..f31320e44f7 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression5_es2017.types @@ -0,0 +1,64 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(a, a, a); +>b : void +>o.fn(a, a, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.js b/tests/baselines/reference/awaitCallExpression6_es2017.js new file mode 100644 index 00000000000..77a47ba8065 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression6_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(await p, a, a); + after(); +} + +//// [awaitCallExpression6_es2017.js] +async function func() { + before(); + var b = o.fn(await p, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.symbols b/tests/baselines/reference/awaitCallExpression6_es2017.symbols new file mode 100644 index 00000000000..6a651510328 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression6_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression6_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression6_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression6_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression6_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression6_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression6_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression6_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression6_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression6_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression6_es2017.ts, 5, 84)) + + var b = o.fn(await p, a, a); +>b : Symbol(b, Decl(awaitCallExpression6_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression6_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression6_es2017.ts, 3, 16)) +>p : Symbol(p, Decl(awaitCallExpression6_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression6_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression6_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression6_es2017.types b/tests/baselines/reference/awaitCallExpression6_es2017.types new file mode 100644 index 00000000000..ccce4cad366 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression6_es2017.types @@ -0,0 +1,65 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(await p, a, a); +>b : void +>o.fn(await p, a, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>await p : boolean +>p : Promise +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.js b/tests/baselines/reference/awaitCallExpression7_es2017.js new file mode 100644 index 00000000000..b3391ced6b6 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression7_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, await p, a); + after(); +} + +//// [awaitCallExpression7_es2017.js] +async function func() { + before(); + var b = o.fn(a, await p, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.symbols b/tests/baselines/reference/awaitCallExpression7_es2017.symbols new file mode 100644 index 00000000000..e95078c6850 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression7_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression7_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression7_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression7_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression7_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression7_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression7_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression7_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression7_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression7_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression7_es2017.ts, 5, 84)) + + var b = o.fn(a, await p, a); +>b : Symbol(b, Decl(awaitCallExpression7_es2017.ts, 10, 7)) +>o.fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>o : Symbol(o, Decl(awaitCallExpression7_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression7_es2017.ts, 3, 16)) +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) +>p : Symbol(p, Decl(awaitCallExpression7_es2017.ts, 1, 11)) +>a : Symbol(a, Decl(awaitCallExpression7_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression7_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression7_es2017.types b/tests/baselines/reference/awaitCallExpression7_es2017.types new file mode 100644 index 00000000000..aefe7916852 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression7_es2017.types @@ -0,0 +1,65 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = o.fn(a, await p, a); +>b : void +>o.fn(a, await p, a) : void +>o.fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>await p : boolean +>p : Promise +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.js b/tests/baselines/reference/awaitCallExpression8_es2017.js new file mode 100644 index 00000000000..7e04402e90a --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.js @@ -0,0 +1,21 @@ +//// [awaitCallExpression8_es2017.ts] +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await po).fn(a, a, a); + after(); +} + +//// [awaitCallExpression8_es2017.js] +async function func() { + before(); + var b = (await po).fn(a, a, a); + after(); +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.symbols b/tests/baselines/reference/awaitCallExpression8_es2017.symbols new file mode 100644 index 00000000000..e3fd465c120 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.symbols @@ -0,0 +1,61 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts === +declare var a: boolean; +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitCallExpression8_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 1, 32)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 2, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 2, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 2, 49)) + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : Symbol(o, Decl(awaitCallExpression8_es2017.ts, 3, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 3, 16)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 3, 20)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 3, 34)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 3, 49)) + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Symbol(pfn, Decl(awaitCallExpression8_es2017.ts, 4, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 4, 28)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 4, 42)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 4, 57)) + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Symbol(po, Decl(awaitCallExpression8_es2017.ts, 5, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>arg0 : Symbol(arg0, Decl(awaitCallExpression8_es2017.ts, 5, 29)) +>arg1 : Symbol(arg1, Decl(awaitCallExpression8_es2017.ts, 5, 43)) +>arg2 : Symbol(arg2, Decl(awaitCallExpression8_es2017.ts, 5, 58)) + +declare function before(): void; +>before : Symbol(before, Decl(awaitCallExpression8_es2017.ts, 5, 84)) + +declare function after(): void; +>after : Symbol(after, Decl(awaitCallExpression8_es2017.ts, 6, 32)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitCallExpression8_es2017.ts, 7, 31)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + before(); +>before : Symbol(before, Decl(awaitCallExpression8_es2017.ts, 5, 84)) + + var b = (await po).fn(a, a, a); +>b : Symbol(b, Decl(awaitCallExpression8_es2017.ts, 10, 7)) +>(await po).fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>po : Symbol(po, Decl(awaitCallExpression8_es2017.ts, 5, 11)) +>fn : Symbol(fn, Decl(awaitCallExpression8_es2017.ts, 5, 25)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) +>a : Symbol(a, Decl(awaitCallExpression8_es2017.ts, 0, 11)) + + after(); +>after : Symbol(after, Decl(awaitCallExpression8_es2017.ts, 6, 32)) +} diff --git a/tests/baselines/reference/awaitCallExpression8_es2017.types b/tests/baselines/reference/awaitCallExpression8_es2017.types new file mode 100644 index 00000000000..a9a115d39f2 --- /dev/null +++ b/tests/baselines/reference/awaitCallExpression8_es2017.types @@ -0,0 +1,66 @@ +=== tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts === +declare var a: boolean; +>a : boolean + +declare var p: Promise; +>p : Promise +>Promise : Promise + +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +>o : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>pfn : Promise<(arg0: boolean, arg1: boolean, arg2: boolean) => void> +>Promise : Promise +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>Promise : Promise +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>arg0 : boolean +>arg1 : boolean +>arg2 : boolean + +declare function before(): void; +>before : () => void + +declare function after(): void; +>after : () => void + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + before(); +>before() : void +>before : () => void + + var b = (await po).fn(a, a, a); +>b : void +>(await po).fn(a, a, a) : void +>(await po).fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>(await po) : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>await po : { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; } +>po : Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }> +>fn : (arg0: boolean, arg1: boolean, arg2: boolean) => void +>a : boolean +>a : boolean +>a : boolean + + after(); +>after() : void +>after : () => void +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.js b/tests/baselines/reference/awaitClassExpression_es2017.js new file mode 100644 index 00000000000..d84f01f61cf --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.js @@ -0,0 +1,14 @@ +//// [awaitClassExpression_es2017.ts] +declare class C { } +declare var p: Promise; + +async function func(): Promise { + class D extends (await p) { + } +} + +//// [awaitClassExpression_es2017.js] +async function func() { + class D extends (await p) { + } +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.symbols b/tests/baselines/reference/awaitClassExpression_es2017.symbols new file mode 100644 index 00000000000..bebffa2bbad --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.symbols @@ -0,0 +1,18 @@ +=== tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts === +declare class C { } +>C : Symbol(C, Decl(awaitClassExpression_es2017.ts, 0, 0)) + +declare var p: Promise; +>p : Symbol(p, Decl(awaitClassExpression_es2017.ts, 1, 11)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) +>C : Symbol(C, Decl(awaitClassExpression_es2017.ts, 0, 0)) + +async function func(): Promise { +>func : Symbol(func, Decl(awaitClassExpression_es2017.ts, 1, 33)) +>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) + + class D extends (await p) { +>D : Symbol(D, Decl(awaitClassExpression_es2017.ts, 3, 38)) +>p : Symbol(p, Decl(awaitClassExpression_es2017.ts, 1, 11)) + } +} diff --git a/tests/baselines/reference/awaitClassExpression_es2017.types b/tests/baselines/reference/awaitClassExpression_es2017.types new file mode 100644 index 00000000000..39d17b1cc50 --- /dev/null +++ b/tests/baselines/reference/awaitClassExpression_es2017.types @@ -0,0 +1,20 @@ +=== tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts === +declare class C { } +>C : C + +declare var p: Promise; +>p : Promise +>Promise : Promise +>C : typeof C + +async function func(): Promise { +>func : () => Promise +>Promise : Promise + + class D extends (await p) { +>D : D +>(await p) : C +>await p : typeof C +>p : Promise + } +} diff --git a/tests/baselines/reference/awaitUnion_es2017.js b/tests/baselines/reference/awaitUnion_es2017.js new file mode 100644 index 00000000000..12f8b95a652 --- /dev/null +++ b/tests/baselines/reference/awaitUnion_es2017.js @@ -0,0 +1,22 @@ +//// [awaitUnion_es2017.ts] +declare let a: number | string; +declare let b: PromiseLike | PromiseLike; +declare let c: PromiseLike; +declare let d: number | PromiseLike; +declare let e: number | PromiseLike; +async function f() { + let await_a = await a; + let await_b = await b; + let await_c = await c; + let await_d = await d; + let await_e = await e; +} + +//// [awaitUnion_es2017.js] +async function f() { + let await_a = await a; + let await_b = await b; + let await_c = await c; + let await_d = await d; + let await_e = await e; +} diff --git a/tests/baselines/reference/awaitUnion_es2017.symbols b/tests/baselines/reference/awaitUnion_es2017.symbols new file mode 100644 index 00000000000..e70abce4f0b --- /dev/null +++ b/tests/baselines/reference/awaitUnion_es2017.symbols @@ -0,0 +1,44 @@ +=== tests/cases/conformance/async/es2017/awaitUnion_es2017.ts === +declare let a: number | string; +>a : Symbol(a, Decl(awaitUnion_es2017.ts, 0, 11)) + +declare let b: PromiseLike | PromiseLike; +>b : Symbol(b, Decl(awaitUnion_es2017.ts, 1, 11)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) + +declare let c: PromiseLike; +>c : Symbol(c, Decl(awaitUnion_es2017.ts, 2, 11)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) + +declare let d: number | PromiseLike; +>d : Symbol(d, Decl(awaitUnion_es2017.ts, 3, 11)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) + +declare let e: number | PromiseLike; +>e : Symbol(e, Decl(awaitUnion_es2017.ts, 4, 11)) +>PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) + +async function f() { +>f : Symbol(f, Decl(awaitUnion_es2017.ts, 4, 53)) + + let await_a = await a; +>await_a : Symbol(await_a, Decl(awaitUnion_es2017.ts, 6, 4)) +>a : Symbol(a, Decl(awaitUnion_es2017.ts, 0, 11)) + + let await_b = await b; +>await_b : Symbol(await_b, Decl(awaitUnion_es2017.ts, 7, 4)) +>b : Symbol(b, Decl(awaitUnion_es2017.ts, 1, 11)) + + let await_c = await c; +>await_c : Symbol(await_c, Decl(awaitUnion_es2017.ts, 8, 4)) +>c : Symbol(c, Decl(awaitUnion_es2017.ts, 2, 11)) + + let await_d = await d; +>await_d : Symbol(await_d, Decl(awaitUnion_es2017.ts, 9, 4)) +>d : Symbol(d, Decl(awaitUnion_es2017.ts, 3, 11)) + + let await_e = await e; +>await_e : Symbol(await_e, Decl(awaitUnion_es2017.ts, 10, 4)) +>e : Symbol(e, Decl(awaitUnion_es2017.ts, 4, 11)) +} diff --git a/tests/baselines/reference/awaitUnion_es2017.types b/tests/baselines/reference/awaitUnion_es2017.types new file mode 100644 index 00000000000..58f8a4ec4b4 --- /dev/null +++ b/tests/baselines/reference/awaitUnion_es2017.types @@ -0,0 +1,49 @@ +=== tests/cases/conformance/async/es2017/awaitUnion_es2017.ts === +declare let a: number | string; +>a : string | number + +declare let b: PromiseLike | PromiseLike; +>b : PromiseLike | PromiseLike +>PromiseLike : PromiseLike +>PromiseLike : PromiseLike + +declare let c: PromiseLike; +>c : PromiseLike +>PromiseLike : PromiseLike + +declare let d: number | PromiseLike; +>d : number | PromiseLike +>PromiseLike : PromiseLike + +declare let e: number | PromiseLike; +>e : number | PromiseLike +>PromiseLike : PromiseLike + +async function f() { +>f : () => Promise + + let await_a = await a; +>await_a : string | number +>await a : string | number +>a : string | number + + let await_b = await b; +>await_b : string | number +>await b : string | number +>b : PromiseLike | PromiseLike + + let await_c = await c; +>await_c : string | number +>await c : string | number +>c : PromiseLike + + let await_d = await d; +>await_d : string | number +>await d : string | number +>d : number | PromiseLike + + let await_e = await e; +>await_e : string | number +>await e : string | number +>e : number | PromiseLike +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.js b/tests/baselines/reference/await_unaryExpression_es2017.js new file mode 100644 index 00000000000..83fce6588e6 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.js @@ -0,0 +1,31 @@ +//// [await_unaryExpression_es2017.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} + +//// [await_unaryExpression_es2017.js] +async function bar() { + !await 42; // OK +} +async function bar1() { + +await 42; // OK +} +async function bar3() { + -await 42; // OK +} +async function bar4() { + ~await 42; // OK +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.symbols b/tests/baselines/reference/await_unaryExpression_es2017.symbols new file mode 100644 index 00000000000..1aa31031177 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.symbols @@ -0,0 +1,25 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es2017.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017.ts, 3, 1)) + + +await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017.ts, 7, 1)) + + -await 42; // OK +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es2017.ts, 11, 1)) + + ~await 42; // OK +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017.types b/tests/baselines/reference/await_unaryExpression_es2017.types new file mode 100644 index 00000000000..4f4254df318 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017.types @@ -0,0 +1,37 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar1() { +>bar1 : () => Promise + + +await 42; // OK +>+await 42 : number +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + -await 42; // OK +>-await 42 : number +>await 42 : 42 +>42 : 42 +} + +async function bar4() { +>bar4 : () => Promise + + ~await 42; // OK +>~await 42 : number +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.js b/tests/baselines/reference/await_unaryExpression_es2017_1.js new file mode 100644 index 00000000000..f863fb19a7e --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.js @@ -0,0 +1,38 @@ +//// [await_unaryExpression_es2017_1.ts] + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} + +//// [await_unaryExpression_es2017_1.js] +async function bar() { + !await 42; // OK +} +async function bar1() { + delete await 42; // OK +} +async function bar2() { + delete await 42; // OK +} +async function bar3() { + void await 42; +} +async function bar4() { + +await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.symbols b/tests/baselines/reference/await_unaryExpression_es2017_1.symbols new file mode 100644 index 00000000000..81bb31a7efd --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts === + +async function bar() { +>bar : Symbol(bar, Decl(await_unaryExpression_es2017_1.ts, 0, 0)) + + !await 42; // OK +} + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017_1.ts, 3, 1)) + + delete await 42; // OK +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es2017_1.ts, 7, 1)) + + delete await 42; // OK +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017_1.ts, 11, 1)) + + void await 42; +} + +async function bar4() { +>bar4 : Symbol(bar4, Decl(await_unaryExpression_es2017_1.ts, 15, 1)) + + +await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_1.types b/tests/baselines/reference/await_unaryExpression_es2017_1.types new file mode 100644 index 00000000000..7afa4fe9001 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_1.types @@ -0,0 +1,46 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts === + +async function bar() { +>bar : () => Promise + + !await 42; // OK +>!await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar1() { +>bar1 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; // OK +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : 42 +>42 : 42 +} + +async function bar4() { +>bar4 : () => Promise + + +await 42; +>+await 42 : number +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.js b/tests/baselines/reference/await_unaryExpression_es2017_2.js new file mode 100644 index 00000000000..b982b20245c --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.js @@ -0,0 +1,24 @@ +//// [await_unaryExpression_es2017_2.ts] + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} + +//// [await_unaryExpression_es2017_2.js] +async function bar1() { + delete await 42; +} +async function bar2() { + delete await 42; +} +async function bar3() { + void await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.symbols b/tests/baselines/reference/await_unaryExpression_es2017_2.symbols new file mode 100644 index 00000000000..d4b8a7493d9 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts === + +async function bar1() { +>bar1 : Symbol(bar1, Decl(await_unaryExpression_es2017_2.ts, 0, 0)) + + delete await 42; +} + +async function bar2() { +>bar2 : Symbol(bar2, Decl(await_unaryExpression_es2017_2.ts, 3, 1)) + + delete await 42; +} + +async function bar3() { +>bar3 : Symbol(bar3, Decl(await_unaryExpression_es2017_2.ts, 7, 1)) + + void await 42; +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_2.types b/tests/baselines/reference/await_unaryExpression_es2017_2.types new file mode 100644 index 00000000000..acaa76d2d67 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_2.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts === + +async function bar1() { +>bar1 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar2() { +>bar2 : () => Promise + + delete await 42; +>delete await 42 : boolean +>await 42 : 42 +>42 : 42 +} + +async function bar3() { +>bar3 : () => Promise + + void await 42; +>void await 42 : undefined +>await 42 : 42 +>42 : 42 +} diff --git a/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt b/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt new file mode 100644 index 00000000000..5d11c4bbb20 --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_3.errors.txt @@ -0,0 +1,27 @@ +tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts(3,7): error TS1109: Expression expected. +tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts(7,7): error TS1109: Expression expected. + + +==== tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts (2 errors) ==== + + async function bar1() { + ++await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar2() { + --await 42; // Error + ~~~~~ +!!! error TS1109: Expression expected. + } + + async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis + } + + async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis + } \ No newline at end of file diff --git a/tests/baselines/reference/await_unaryExpression_es2017_3.js b/tests/baselines/reference/await_unaryExpression_es2017_3.js new file mode 100644 index 00000000000..5e3c3c3a4bf --- /dev/null +++ b/tests/baselines/reference/await_unaryExpression_es2017_3.js @@ -0,0 +1,37 @@ +//// [await_unaryExpression_es2017_3.ts] + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} + +//// [await_unaryExpression_es2017_3.js] +async function bar1() { + ++; + await 42; // Error +} +async function bar2() { + --; + await 42; // Error +} +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} diff --git a/tests/baselines/reference/es2017basicAsync.js b/tests/baselines/reference/es2017basicAsync.js index da219f4614c..b19eaa4b0ba 100644 --- a/tests/baselines/reference/es2017basicAsync.js +++ b/tests/baselines/reference/es2017basicAsync.js @@ -1,4 +1,4 @@ -//// [es2017-async.ts] +//// [es2017basicAsync.ts] async (): Promise => { await 0; @@ -47,7 +47,7 @@ class AsyncClass { } -//// [es2017-async.js] +//// [es2017basicAsync.js] async () => { await 0; }; diff --git a/tests/baselines/reference/es2017basicAsync.symbols b/tests/baselines/reference/es2017basicAsync.symbols index be3b2e723f4..75f4d2cfa76 100644 --- a/tests/baselines/reference/es2017basicAsync.symbols +++ b/tests/baselines/reference/es2017basicAsync.symbols @@ -1,4 +1,4 @@ -=== tests/cases/compiler/es2017-async.ts === +=== tests/cases/compiler/es2017basicAsync.ts === async (): Promise => { >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) @@ -7,20 +7,20 @@ async (): Promise => { } async function asyncFunc() { ->asyncFunc : Symbol(asyncFunc, Decl(es2017-async.ts, 3, 1)) +>asyncFunc : Symbol(asyncFunc, Decl(es2017basicAsync.ts, 3, 1)) await 0; } const asycnArrowFunc = async (): Promise => { ->asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es2017-async.ts, 9, 5)) +>asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es2017basicAsync.ts, 9, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 0; } async function asyncIIFE() { ->asyncIIFE : Symbol(asyncIIFE, Decl(es2017-async.ts, 11, 1)) +>asyncIIFE : Symbol(asyncIIFE, Decl(es2017basicAsync.ts, 11, 1)) await 0; @@ -31,7 +31,7 @@ async function asyncIIFE() { })(); await (async function asyncNamedFunc(): Promise { ->asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es2017-async.ts, 20, 11)) +>asyncNamedFunc : Symbol(asyncNamedFunc, Decl(es2017basicAsync.ts, 20, 11)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 1; @@ -45,32 +45,32 @@ async function asyncIIFE() { } class AsyncClass { ->AsyncClass : Symbol(AsyncClass, Decl(es2017-async.ts, 27, 1)) +>AsyncClass : Symbol(AsyncClass, Decl(es2017basicAsync.ts, 27, 1)) asyncPropFunc = async function(): Promise { ->asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es2017-async.ts, 29, 18)) +>asyncPropFunc : Symbol(AsyncClass.asyncPropFunc, Decl(es2017basicAsync.ts, 29, 18)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } asyncPropNamedFunc = async function namedFunc(): Promise { ->asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es2017-async.ts, 32, 5)) ->namedFunc : Symbol(namedFunc, Decl(es2017-async.ts, 34, 24)) +>asyncPropNamedFunc : Symbol(AsyncClass.asyncPropNamedFunc, Decl(es2017basicAsync.ts, 32, 5)) +>namedFunc : Symbol(namedFunc, Decl(es2017basicAsync.ts, 34, 24)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } asyncPropArrowFunc = async (): Promise => { ->asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es2017-async.ts, 36, 5)) +>asyncPropArrowFunc : Symbol(AsyncClass.asyncPropArrowFunc, Decl(es2017basicAsync.ts, 36, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; } async asyncMethod(): Promise { ->asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es2017-async.ts, 40, 5)) +>asyncMethod : Symbol(AsyncClass.asyncMethod, Decl(es2017basicAsync.ts, 40, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 2; diff --git a/tests/baselines/reference/es2017basicAsync.types b/tests/baselines/reference/es2017basicAsync.types index 79f3a005e6e..71c2dbe50f3 100644 --- a/tests/baselines/reference/es2017basicAsync.types +++ b/tests/baselines/reference/es2017basicAsync.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/es2017-async.ts === +=== tests/cases/compiler/es2017basicAsync.ts === async (): Promise => { >async (): Promise => { await 0;} : () => Promise diff --git a/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts b/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts new file mode 100644 index 00000000000..87bbc42e166 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +type PromiseAlias = Promise; + +async function f(): PromiseAlias { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts new file mode 100644 index 00000000000..1ade02c09d2 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/arrowFunctionWithParameterNameAsync_es2017.ts @@ -0,0 +1,4 @@ +// @target: ES5 +// @noEmitHelpers: true + +const x = async => async; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts new file mode 100644 index 00000000000..09d97cc253b --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction10_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { + // Legal to use 'await' in a type context. + var v: await; +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts new file mode 100644 index 00000000000..0f9ec479a31 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction1_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { +}; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts new file mode 100644 index 00000000000..b11441372ff --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction2_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var f = (await) => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts new file mode 100644 index 00000000000..9b5924fc145 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction3_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await = await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts new file mode 100644 index 00000000000..5a988277836 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction4_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var await = () => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts new file mode 100644 index 00000000000..aabe5a99372 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction5_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts new file mode 100644 index 00000000000..d82ce864421 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction6_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (a = await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts new file mode 100644 index 00000000000..bc49c5995e6 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction7_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true + +var bar = async (): Promise => { + // 'await' here is an identifier, and not an await expression. + var foo = async (a = await): Promise => { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts new file mode 100644 index 00000000000..387b09c791a --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction8_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true + +var foo = async (): Promise => { + var v = { [await]: foo } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts new file mode 100644 index 00000000000..93254fee5c7 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunction9_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +var foo = async (a = await => await): Promise => { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts new file mode 100644 index 00000000000..c71c6ddecb0 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesArguments_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + method() { + function other() {} + var fn = async () => await other.apply(this, arguments); + } +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts new file mode 100644 index 00000000000..3f398d9be82 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncArrowFunctionCapturesThis_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + method() { + var fn = async () => await this; + } +} diff --git a/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts new file mode 100644 index 00000000000..9b63b7bd468 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncArrowFunction/asyncUnParenthesizedArrowFunction_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true + +declare function someOtherFunction(i: any): Promise; +const x = async i => await someOtherFunction(i) +const x1 = async (i) => await someOtherFunction(i); \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts b/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts new file mode 100644 index 00000000000..c0ab4838f70 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncAwaitIsolatedModules_es2017.ts @@ -0,0 +1,41 @@ +// @target: es2017 +// @isolatedModules: true +import { MyPromise } from "missing"; + +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts b/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts new file mode 100644 index 00000000000..a255cb7cb71 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncAwait_es2017.ts @@ -0,0 +1,40 @@ +// @target: es2017 +type MyPromise = Promise; +declare var MyPromise: typeof Promise; +declare var p: Promise; +declare var mp: MyPromise; + +async function f0() { } +async function f1(): Promise { } +async function f3(): MyPromise { } + +let f4 = async function() { } +let f5 = async function(): Promise { } +let f6 = async function(): MyPromise { } + +let f7 = async () => { }; +let f8 = async (): Promise => { }; +let f9 = async (): MyPromise => { }; +let f10 = async () => p; +let f11 = async () => mp; +let f12 = async (): Promise => mp; +let f13 = async (): MyPromise => p; + +let o = { + async m1() { }, + async m2(): Promise { }, + async m3(): MyPromise { } +}; + +class C { + async m1() { } + async m2(): Promise { } + async m3(): MyPromise { } + static async m4() { } + static async m5(): Promise { } + static async m6(): MyPromise { } +} + +module M { + export async function f1() { } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncClass_es2017.ts b/tests/cases/conformance/async/es2017/asyncClass_es2017.ts new file mode 100644 index 00000000000..78746c972d0 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncClass_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async class C { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts b/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts new file mode 100644 index 00000000000..874c0b99239 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + async constructor() { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts b/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts new file mode 100644 index 00000000000..d7fd4888fed --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts @@ -0,0 +1,3 @@ +// @target: es2017 +// @noEmitHelpers: true +declare async function foo(): Promise; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts b/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts new file mode 100644 index 00000000000..dc995206e84 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true +async enum E { + Value +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts b/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts new file mode 100644 index 00000000000..340c33138cf --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + async get foo() { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts b/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts new file mode 100644 index 00000000000..81f5b690edd --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts @@ -0,0 +1,10 @@ +// @target: es2017 +// @module: commonjs +// @filename: task.ts +export class Task extends Promise { } + +// @filename: test.ts +import { Task } from "./task"; +class Test { + async example(): Task { return; } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts b/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts new file mode 100644 index 00000000000..252730f9ff6 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async interface I { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts new file mode 100644 index 00000000000..b9005c48596 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncMethodWithSuper_es2017.ts @@ -0,0 +1,52 @@ +// @target: es2017 +// @noEmitHelpers: true +class A { + x() { + } +} + +class B extends A { + // async method with only call/get on 'super' does not require a binding + async simple() { + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + } + + // async method with assignment/destructuring on 'super' requires a binding + async advanced() { + const f = () => {}; + + // call with property access + super.x(); + + // call with element access + super["x"](); + + // property access (read) + const a = super.x; + + // element access (read) + const b = super["x"]; + + // property access (assign) + super.x = f; + + // element access (assign) + super["x"] = f; + + // destructuring assign with property access + ({ f: super.x } = { f }); + + // destructuring assign with element access + ({ f: super["x"] } = { f }); + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncModule_es2017.ts b/tests/cases/conformance/async/es2017/asyncModule_es2017.ts new file mode 100644 index 00000000000..7c577e27fb9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncModule_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async module M { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts b/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts new file mode 100644 index 00000000000..920bdfb8bda --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @filename: a.ts +async function f() {} +// @filename: b.ts +function g() { } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts b/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts new file mode 100644 index 00000000000..95695168cea --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts @@ -0,0 +1,9 @@ +// @target: es2017 +// @noEmitHelpers: true +namespace X { + export class MyPromise extends Promise { + } +} + +async function f(): X.MyPromise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts b/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts new file mode 100644 index 00000000000..658c07d42e8 --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +class C { + async set foo(value) { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts b/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts new file mode 100644 index 00000000000..c4d4cafef8a --- /dev/null +++ b/tests/cases/conformance/async/es2017/asyncUseStrict_es2017.ts @@ -0,0 +1,8 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +async function func(): Promise { + "use strict"; + var b = await p || a; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts new file mode 100644 index 00000000000..ef9076a8bee --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression1_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p || a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts new file mode 100644 index 00000000000..84d2f622292 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression2_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p && a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts new file mode 100644 index 00000000000..1f3a8245d42 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression3_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: number; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = await p + a; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts new file mode 100644 index 00000000000..6c36f1e4ce5 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression4_es2017.ts @@ -0,0 +1,11 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts new file mode 100644 index 00000000000..abbcbb95ba9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitBinaryExpression/awaitBinaryExpression5_es2017.ts @@ -0,0 +1,12 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var o: { a: boolean; }; + o.a = await p; + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts new file mode 100644 index 00000000000..da46e04ed1e --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression1_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts new file mode 100644 index 00000000000..baf75ab95c3 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression2_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(await p, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts new file mode 100644 index 00000000000..17cf6d8c6c9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression3_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = fn(a, await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts new file mode 100644 index 00000000000..ef5e1d203d9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression4_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await pfn)(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts new file mode 100644 index 00000000000..8494bc11b4c --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression5_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts new file mode 100644 index 00000000000..7939572baea --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression6_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(await p, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts new file mode 100644 index 00000000000..3f1231a50d6 --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression7_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = o.fn(a, await p, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts new file mode 100644 index 00000000000..c669122bada --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitCallExpression/awaitCallExpression8_es2017.ts @@ -0,0 +1,15 @@ +// @target: es2017 +// @noEmitHelpers: true +declare var a: boolean; +declare var p: Promise; +declare function fn(arg0: boolean, arg1: boolean, arg2: boolean): void; +declare var o: { fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }; +declare var pfn: Promise<{ (arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare var po: Promise<{ fn(arg0: boolean, arg1: boolean, arg2: boolean): void; }>; +declare function before(): void; +declare function after(): void; +async function func(): Promise { + before(); + var b = (await po).fn(a, a, a); + after(); +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts b/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts new file mode 100644 index 00000000000..fe34d53a03c --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitClassExpression_es2017.ts @@ -0,0 +1,9 @@ +// @target: es2017 +// @noEmitHelpers: true +declare class C { } +declare var p: Promise; + +async function func(): Promise { + class D extends (await p) { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts b/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts new file mode 100644 index 00000000000..493aa838ffe --- /dev/null +++ b/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts @@ -0,0 +1,14 @@ +// @target: es2017 +// @noEmitHelpers: true +declare let a: number | string; +declare let b: PromiseLike | PromiseLike; +declare let c: PromiseLike; +declare let d: number | PromiseLike; +declare let e: number | PromiseLike; +async function f() { + let await_a = await a; + let await_b = await b; + let await_c = await c; + let await_d = await d; + let await_e = await e; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts new file mode 100644 index 00000000000..dee2554653d --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017.ts @@ -0,0 +1,17 @@ +// @target: es2017 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + +await 42; // OK +} + +async function bar3() { + -await 42; // OK +} + +async function bar4() { + ~await 42; // OK +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts new file mode 100644 index 00000000000..f38260b332d --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_1.ts @@ -0,0 +1,21 @@ +// @target: es2017 + +async function bar() { + !await 42; // OK +} + +async function bar1() { + delete await 42; // OK +} + +async function bar2() { + delete await 42; // OK +} + +async function bar3() { + void await 42; +} + +async function bar4() { + +await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts new file mode 100644 index 00000000000..b48c661f0b9 --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_2.ts @@ -0,0 +1,13 @@ +// @target: es2017 + +async function bar1() { + delete await 42; +} + +async function bar2() { + delete await 42; +} + +async function bar3() { + void await 42; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts new file mode 100644 index 00000000000..d2c608d0e7b --- /dev/null +++ b/tests/cases/conformance/async/es2017/await_unaryExpression_es2017_3.ts @@ -0,0 +1,19 @@ +// @target: es2017 + +async function bar1() { + ++await 42; // Error +} + +async function bar2() { + --await 42; // Error +} + +async function bar3() { + var x = 42; + await x++; // OK but shouldn't need parenthesis +} + +async function bar4() { + var x = 42; + await x--; // OK but shouldn't need parenthesis +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts new file mode 100644 index 00000000000..9b744713945 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration10_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(a = await => await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts new file mode 100644 index 00000000000..9613e866163 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration11_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function await(): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts new file mode 100644 index 00000000000..02b6e833c2c --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration12_es2017.ts @@ -0,0 +1,3 @@ +// @target: es2017 +// @noEmitHelpers: true +var v = async function await(): Promise { } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts new file mode 100644 index 00000000000..40177c1fbcb --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration13_es2017.ts @@ -0,0 +1,6 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + // Legal to use 'await' in a type context. + var v: await; +} diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts new file mode 100644 index 00000000000..06bd2de3eef --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration14_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + return; +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts new file mode 100644 index 00000000000..2585dc666f4 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts @@ -0,0 +1,25 @@ +// @target: es2017 +// @noEmitHelpers: true +declare class Thenable { then(): void; } +declare let a: any; +declare let obj: { then: string; }; +declare let thenable: Thenable; +async function fn1() { } // valid: Promise +async function fn2(): { } { } // error +async function fn3(): any { } // error +async function fn4(): number { } // error +async function fn5(): PromiseLike { } // error +async function fn6(): Thenable { } // error +async function fn7() { return; } // valid: Promise +async function fn8() { return 1; } // valid: Promise +async function fn9() { return null; } // valid: Promise +async function fn10() { return undefined; } // valid: Promise +async function fn11() { return a; } // valid: Promise +async function fn12() { return obj; } // valid: Promise<{ then: string; }> +async function fn13() { return thenable; } // error +async function fn14() { await 1; } // valid: Promise +async function fn15() { await null; } // valid: Promise +async function fn16() { await undefined; } // valid: Promise +async function fn17() { await a; } // valid: Promise +async function fn18() { await obj; } // valid: Promise +async function fn19() { await thenable; } // error diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts new file mode 100644 index 00000000000..178611ad91b --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration1_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts new file mode 100644 index 00000000000..08711a4cfbd --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration2_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts new file mode 100644 index 00000000000..9b5924fc145 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration3_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function f(await = await) { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts new file mode 100644 index 00000000000..84c6c93b90f --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration4_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +function await() { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts new file mode 100644 index 00000000000..c57fb73d6d7 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration5_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts new file mode 100644 index 00000000000..1ceb160c12b --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration6_es2017.ts @@ -0,0 +1,4 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(a = await): Promise { +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts new file mode 100644 index 00000000000..e5c2649d34e --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration7_es2017.ts @@ -0,0 +1,7 @@ +// @target: es2017 +// @noEmitHelpers: true +async function bar(): Promise { + // 'await' here is an identifier, and not a yield expression. + async function foo(a = await): Promise { + } +} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts new file mode 100644 index 00000000000..64e62a2719e --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration8_es2017.ts @@ -0,0 +1,3 @@ +// @target: es2017 +// @noEmitHelpers: true +var v = { [await]: foo } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts new file mode 100644 index 00000000000..7d3b7213b99 --- /dev/null +++ b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration9_es2017.ts @@ -0,0 +1,5 @@ +// @target: es2017 +// @noEmitHelpers: true +async function foo(): Promise { + var v = { [await]: foo } +} \ No newline at end of file From 7497d81eecd8a3a17f65154c0c657f9e7966fbb7 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 12 Oct 2016 14:12:32 -0700 Subject: [PATCH 32/74] Narrow string and number types in equality checks and switch cases --- src/compiler/checker.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a1a8ae0da5c..6555710137a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8791,6 +8791,10 @@ namespace ts { assumeTrue ? TypeFacts.EQUndefined : TypeFacts.NEUndefined; return getTypeWithFacts(type, facts); } + if (type.flags & TypeFlags.String && isTypeOfKind(valueType, TypeFlags.StringLiteral) || + type.flags & TypeFlags.Number && isTypeOfKind(valueType, TypeFlags.NumberLiteral)) { + return assumeTrue? valueType : type; + } if (type.flags & TypeFlags.NotUnionOrUnit) { return type; } @@ -8843,7 +8847,11 @@ namespace ts { const clauseTypes = switchTypes.slice(clauseStart, clauseEnd); const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType); const discriminantType = getUnionType(clauseTypes); - const caseType = discriminantType.flags & TypeFlags.Never ? neverType : filterType(type, t => isTypeComparableTo(discriminantType, t)); + const caseType = + discriminantType.flags & TypeFlags.Never ? neverType : + type.flags & TypeFlags.String && isTypeOfKind(discriminantType, TypeFlags.StringLiteral) ? discriminantType : + type.flags & TypeFlags.Number && isTypeOfKind(discriminantType, TypeFlags.NumberLiteral) ? discriminantType : + filterType(type, t => isTypeComparableTo(discriminantType, t)); if (!hasDefaultClause) { return caseType; } From 4c581def93d9d1dbeeb0528901f083cf05f198c3 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 12 Oct 2016 14:12:47 -0700 Subject: [PATCH 33/74] Fix bug in scanner --- src/compiler/scanner.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index e7b3872f2e3..b79106766da 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1190,7 +1190,7 @@ namespace ts { } function scanBinaryOrOctalDigits(base: number): number { - Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); let value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. From 92b63fa7251e1c6f7d70ca9edc7062f5c284c4e8 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Wed, 12 Oct 2016 11:02:56 -0700 Subject: [PATCH 34/74] Merge pull request #11550 from Microsoft/vladima/generate-protocol Automatically generate protocol.d.ts by pulling in necessary dependencies --- Jakefile.js | 48 ++- scripts/buildProtocol.ts | 143 +++++++++ src/compiler/types.ts | 10 +- src/harness/unittests/compileOnSave.ts | 40 +-- src/server/builder.ts | 1 - src/server/client.ts | 1 - src/server/editorServices.ts | 1 - src/server/{protocol.d.ts => protocol.ts} | 355 +++++++++++++++++----- src/server/scriptInfo.ts | 2 +- src/server/scriptVersionCache.ts | 1 - src/server/session.ts | 144 ++++----- src/server/tsconfig.json | 2 +- src/services/types.ts | 32 +- 13 files changed, 570 insertions(+), 210 deletions(-) create mode 100644 scripts/buildProtocol.ts rename src/server/{protocol.d.ts => protocol.ts} (80%) diff --git a/Jakefile.js b/Jakefile.js index 64a8553ef39..b548a0d3dd8 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -174,7 +174,7 @@ var serverCoreSources = [ "lsHost.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", + "protocol.ts", "session.ts", "server.ts" ].map(function (f) { @@ -198,14 +198,13 @@ var typingsInstallerSources = [ var serverSources = serverCoreSources.concat(servicesSources); var languageServiceLibrarySources = [ - "protocol.d.ts", + "protocol.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", "lsHost.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", "session.ts", ].map(function (f) { @@ -259,7 +258,7 @@ var harnessSources = harnessCoreSources.concat([ ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ - "protocol.d.ts", + "protocol.ts", "utilities.ts", "scriptVersionCache.ts", "scriptInfo.ts", @@ -267,7 +266,6 @@ var harnessSources = harnessCoreSources.concat([ "project.ts", "typingsCache.ts", "editorServices.ts", - "protocol.d.ts", "session.ts", ].map(function (f) { return path.join(serverDirectory, f); @@ -518,6 +516,40 @@ compileFile(processDiagnosticMessagesJs, [], /*useBuiltCompiler*/ false); +var buildProtocolTs = path.join(scriptsDirectory, "buildProtocol.ts"); +var buildProtocolJs = path.join(scriptsDirectory, "buildProtocol.js"); +var buildProtocolDts = path.join(builtLocalDirectory, "protocol.d.ts"); +var typescriptServicesDts = path.join(builtLocalDirectory, "typescriptServices.d.ts"); + +file(buildProtocolTs); + +compileFile(buildProtocolJs, + [buildProtocolTs], + [buildProtocolTs], + [], + /*useBuiltCompiler*/ false, + {noOutFile: true}); + +file(buildProtocolDts, [buildProtocolTs, buildProtocolJs, typescriptServicesDts], function() { + + var protocolTs = path.join(serverDirectory, "protocol.ts"); + + var cmd = host + " " + buildProtocolJs + " "+ protocolTs + " " + typescriptServicesDts + " " + buildProtocolDts; + console.log(cmd); + var ex = jake.createExec([cmd]); + // Add listeners for output and error + ex.addListener("stdout", function (output) { + process.stdout.write(output); + }); + ex.addListener("stderr", function (error) { + process.stderr.write(error); + }); + ex.addListener("cmdEnd", function () { + complete(); + }); + ex.run(); +}, { async: true }) + // The generated diagnostics map; built for the compiler and for the 'generate-diagnostics' task file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson], function () { var cmd = host + " " + processDiagnosticMessagesJs + " " + diagnosticMessagesJson; @@ -655,6 +687,8 @@ compileFile( inlineSourceMap: true }); +file(typescriptServicesDts, [servicesFile]); + var cancellationTokenFile = path.join(builtLocalDirectory, "cancellationToken.js"); compileFile(cancellationTokenFile, cancellationTokenSources, [builtLocalDirectory].concat(cancellationTokenSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true, { outDir: builtLocalDirectory, noOutFile: true }); @@ -689,7 +723,7 @@ task("build-fold-end", [], function () { // Local target to build the compiler and services desc("Builds the full compiler and services"); -task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]); +task("local", ["build-fold-start", "generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile, buildProtocolDts, builtGeneratedDiagnosticMessagesJSON, "lssl", "build-fold-end"]); // Local target to build only tsc.js desc("Builds only the compiler"); @@ -745,7 +779,7 @@ task("generate-spec", [specMd]); // Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory desc("Makes a new LKG out of the built js files"); task("LKG", ["clean", "release", "local"].concat(libraryTargets), function () { - var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile].concat(libraryTargets); + var expectedFiles = [tscFile, servicesFile, serverFile, nodePackageFile, nodeDefinitionsFile, standaloneDefinitionsFile, tsserverLibraryFile, tsserverLibraryDefinitionFile, cancellationTokenFile, typingsInstallerFile, buildProtocolDts].concat(libraryTargets); var missingFiles = expectedFiles.filter(function (f) { return !fs.existsSync(f); }); diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts new file mode 100644 index 00000000000..8d49262a470 --- /dev/null +++ b/scripts/buildProtocol.ts @@ -0,0 +1,143 @@ +/// + +import * as ts from "../lib/typescript"; +import * as path from "path"; + +function endsWith(s: string, suffix: string) { + return s.lastIndexOf(suffix, s.length - suffix.length) !== -1; +} + +class DeclarationsWalker { + private visitedTypes: ts.Type[] = []; + private text = ""; + private constructor(private typeChecker: ts.TypeChecker, private protocolFile: ts.SourceFile) { + } + + static getExtraDeclarations(typeChecker: ts.TypeChecker, protocolFile: ts.SourceFile): string { + let text = "declare namespace ts.server.protocol {\n"; + var walker = new DeclarationsWalker(typeChecker, protocolFile); + walker.visitTypeNodes(protocolFile); + return walker.text + ? `declare namespace ts.server.protocol {\n${walker.text}}` + : ""; + } + + private processType(type: ts.Type): void { + if (this.visitedTypes.indexOf(type) >= 0) { + return; + } + this.visitedTypes.push(type); + let s = type.aliasSymbol || type.getSymbol(); + if (!s) { + return; + } + if (s.name === "Array") { + // we should process type argument instead + return this.processType((type).typeArguments[0]); + } + else { + for (const decl of s.getDeclarations()) { + const sourceFile = decl.getSourceFile(); + if (sourceFile === this.protocolFile || path.basename(sourceFile.fileName) === "lib.d.ts") { + return; + } + // splice declaration in final d.ts file + const text = decl.getFullText(); + this.text += `${text}\n`; + + // recursively pull all dependencies into result dts file + this.visitTypeNodes(decl); + } + } + } + + private visitTypeNodes(node: ts.Node) { + if (node.parent) { + switch (node.parent.kind) { + case ts.SyntaxKind.VariableDeclaration: + case ts.SyntaxKind.MethodDeclaration: + case ts.SyntaxKind.MethodSignature: + case ts.SyntaxKind.PropertyDeclaration: + case ts.SyntaxKind.PropertySignature: + case ts.SyntaxKind.Parameter: + case ts.SyntaxKind.IndexSignature: + if (((node.parent).type) === node) { + const type = this.typeChecker.getTypeAtLocation(node); + if (type && !(type.flags & ts.TypeFlags.TypeParameter)) { + this.processType(type); + } + } + break; + } + } + ts.forEachChild(node, n => this.visitTypeNodes(n)); + } +} + +function generateProtocolFile(protocolTs: string, typeScriptServicesDts: string): string { + const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: true, types: [], stripInternal: true }; + + /** + * 1st pass - generate a program from protocol.ts and typescriptservices.d.ts and emit core version of protocol.d.ts with all internal members stripped + * @return text of protocol.d.t.s + */ + function getInitialDtsFileForProtocol() { + const program = ts.createProgram([protocolTs, typeScriptServicesDts], options); + + let protocolDts: string; + program.emit(program.getSourceFile(protocolTs), (file, content) => { + if (endsWith(file, ".d.ts")) { + protocolDts = content; + } + }); + if (protocolDts === undefined) { + throw new Error(`Declaration file for protocol.ts is not generated`) + } + return protocolDts; + } + + const protocolFileName = "protocol.d.ts"; + /** + * Second pass - generate a program from protocol.d.ts and typescriptservices.d.ts, then augment core protocol.d.ts with extra types from typescriptservices.d.ts + */ + function getProgramWithProtocolText(protocolDts: string, includeTypeScriptServices: boolean) { + const host = ts.createCompilerHost(options); + const originalGetSourceFile = host.getSourceFile; + host.getSourceFile = (fileName) => { + if (fileName === protocolFileName) { + return ts.createSourceFile(fileName, protocolDts, options.target); + } + return originalGetSourceFile.apply(host, [fileName]); + } + const rootFiles = includeTypeScriptServices ? [protocolFileName, typeScriptServicesDts] : [protocolFileName]; + return ts.createProgram(rootFiles, options, host); + } + + let protocolDts = getInitialDtsFileForProtocol(); + const program = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ true); + + const protocolFile = program.getSourceFile("protocol.d.ts"); + const extraDeclarations = DeclarationsWalker.getExtraDeclarations(program.getTypeChecker(), protocolFile); + if (extraDeclarations) { + protocolDts += extraDeclarations; + } + // do sanity check and try to compile generated text as standalone program + const sanityCheckProgram = getProgramWithProtocolText(protocolDts, /*includeTypeScriptServices*/ false); + const diagnostics = [...program.getSyntacticDiagnostics(), ...program.getSemanticDiagnostics(), ...program.getGlobalDiagnostics()]; + if (diagnostics.length) { + const flattenedDiagnostics = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, "\n")).join("\n"); + throw new Error(`Unexpected errors during sanity check: ${flattenedDiagnostics}`); + } + return protocolDts; +} + +if (process.argv.length < 5) { + console.log(`Expected 3 arguments: path to 'protocol.ts', path to 'typescriptservices.d.ts' and path to output file`); + process.exit(1); +} + +const protocolTs = process.argv[2]; +const typeScriptServicesDts = process.argv[3]; +const outputFile = process.argv[4]; +const generatedProtocolDts = generateProtocolFile(protocolTs, typeScriptServicesDts); +ts.sys.writeFile(outputFile, generatedProtocolDts); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 638504e613f..e751f32b3da 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2917,11 +2917,7 @@ namespace ts { NodeJs = 2 } - export type RootPaths = string[]; - export type PathSubstitutions = MapLike; - export type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - - export type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + export type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; export interface CompilerOptions { allowJs?: boolean; @@ -2973,14 +2969,14 @@ namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; /* @internal */ pretty?: DiagnosticStyle; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; diff --git a/src/harness/unittests/compileOnSave.ts b/src/harness/unittests/compileOnSave.ts index 24fd47ee0cb..797268000eb 100644 --- a/src/harness/unittests/compileOnSave.ts +++ b/src/harness/unittests/compileOnSave.ts @@ -3,6 +3,8 @@ /// namespace ts.projectSystem { + import CommandNames = server.CommandNames; + function createTestTypingsInstaller(host: server.ServerHost) { return new TestTypingsInstaller("/a/data/", /*throttleLimit*/5, host); } @@ -75,7 +77,7 @@ namespace ts.projectSystem { }; // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1ShapeRequest1 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1ShapeRequest1 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -85,7 +87,7 @@ namespace ts.projectSystem { }); // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1InternalRequest1 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1InternalRequest1 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -95,7 +97,7 @@ namespace ts.projectSystem { }); // Change the content of file1 to `export var T: number;export function Foo() { };` - changeModuleFile1ShapeRequest2 = makeSessionRequest(server.CommandNames.Change, { + changeModuleFile1ShapeRequest2 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -104,7 +106,7 @@ namespace ts.projectSystem { insertString: `export var T2: number;` }); - moduleFile1FileListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path }); + moduleFile1FileListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path, projectFileName: configFile.path }); }); it("should contains only itself if a module file's shape didn't change, and all files referencing it if its shape changed", () => { @@ -120,7 +122,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]); // Change the content of file1 to `export var T: number;export function Foo() { console.log('hi'); };` - const changeFile1InternalRequest = makeSessionRequest(server.CommandNames.Change, { + const changeFile1InternalRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 46, @@ -143,7 +145,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2] }]); // Change file2 content to `let y = Foo();` - const removeFile1Consumer1ImportRequest = makeSessionRequest(server.CommandNames.Change, { + const removeFile1Consumer1ImportRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 1, offset: 1, @@ -156,7 +158,7 @@ namespace ts.projectSystem { sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer2] }]); // Add the import statements back to file2 - const addFile2ImportRequest = makeSessionRequest(server.CommandNames.Change, { + const addFile2ImportRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 1, offset: 1, @@ -167,7 +169,7 @@ namespace ts.projectSystem { session.executeCommand(addFile2ImportRequest); // Change the content of file1 to `export var T2: string;export var T: number;export function Foo() { };` - const changeModuleFile1ShapeRequest2 = makeSessionRequest(server.CommandNames.Change, { + const changeModuleFile1ShapeRequest2 = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 1, @@ -272,7 +274,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([globalFile3], session); - const changeGlobalFile3ShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const changeGlobalFile3ShapeRequest = makeSessionRequest(CommandNames.Change, { file: globalFile3.path, line: 1, offset: 1, @@ -283,7 +285,7 @@ namespace ts.projectSystem { // check after file1 shape changes session.executeCommand(changeGlobalFile3ShapeRequest); - const globalFile3FileListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path }); + const globalFile3FileListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: globalFile3.path }); sendAffectedFileRequestAndCheckResult(session, globalFile3FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer2, globalFile3, moduleFile2] }]); }); @@ -316,7 +318,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([moduleFile1], session); - const file1ChangeShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const file1ChangeShapeRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 27, @@ -345,7 +347,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([moduleFile1], session); - const file1ChangeShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const file1ChangeShapeRequest = makeSessionRequest(CommandNames.Change, { file: moduleFile1.path, line: 1, offset: 27, @@ -369,7 +371,7 @@ namespace ts.projectSystem { openFilesForSession([moduleFile1, file1Consumer1], session); sendAffectedFileRequestAndCheckResult(session, moduleFile1FileListRequest, [{ projectFileName: configFile.path, files: [moduleFile1, file1Consumer1, file1Consumer1Consumer1] }]); - const changeFile1Consumer1ShapeRequest = makeSessionRequest(server.CommandNames.Change, { + const changeFile1Consumer1ShapeRequest = makeSessionRequest(CommandNames.Change, { file: file1Consumer1.path, line: 2, offset: 1, @@ -400,7 +402,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([file1, file2], session); - const file1AffectedListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); + const file1AffectedListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [{ projectFileName: configFile.path, files: [file1, file2] }]); }); @@ -415,7 +417,7 @@ namespace ts.projectSystem { const session = createSession(host); openFilesForSession([file1, file2, file3], session); - const file1AffectedListRequest = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); + const file1AffectedListRequest = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: file1.path }); sendAffectedFileRequestAndCheckResult(session, file1AffectedListRequest, [ { projectFileName: configFile1.path, files: [file1, file2] }, @@ -437,11 +439,11 @@ namespace ts.projectSystem { host.reloadFS([referenceFile1, configFile]); host.triggerFileWatcherCallback(moduleFile1.path, /*removed*/ true); - const request = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); + const request = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); sendAffectedFileRequestAndCheckResult(session, request, [ { projectFileName: configFile.path, files: [referenceFile1] } ]); - const requestForMissingFile = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path }); + const requestForMissingFile = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: moduleFile1.path }); sendAffectedFileRequestAndCheckResult(session, requestForMissingFile, []); }); @@ -456,7 +458,7 @@ namespace ts.projectSystem { const session = createSession(host); openFilesForSession([referenceFile1], session); - const request = makeSessionRequest(server.CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); + const request = makeSessionRequest(CommandNames.CompileOnSaveAffectedFileList, { file: referenceFile1.path }); sendAffectedFileRequestAndCheckResult(session, request, [ { projectFileName: configFile.path, files: [referenceFile1] } ]); @@ -483,7 +485,7 @@ namespace ts.projectSystem { const session = new server.Session(host, nullCancellationToken, /*useSingleInferredProject*/ false, typingsInstaller, Utils.byteLength, process.hrtime, nullLogger, /*canUseEvents*/ false); openFilesForSession([file1, file2], session); - const compileFileRequest = makeSessionRequest(server.CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path }); + const compileFileRequest = makeSessionRequest(CommandNames.CompileOnSaveEmitFile, { file: file1.path, projectFileName: configFile.path }); session.executeCommand(compileFileRequest); const expectedEmittedFileName = "/a/b/f1.js"; diff --git a/src/server/builder.ts b/src/server/builder.ts index 639c41d2b63..475202a0aab 100644 --- a/src/server/builder.ts +++ b/src/server/builder.ts @@ -1,6 +1,5 @@ /// /// -/// /// /// diff --git a/src/server/client.ts b/src/server/client.ts index 058abdff41d..b0bc2c5dac0 100644 --- a/src/server/client.ts +++ b/src/server/client.ts @@ -1,7 +1,6 @@ /// namespace ts.server { - export interface SessionClientHost extends LanguageServiceHost { writeMessage(message: string): void; } diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index dc2c45156cd..1a331c09320 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1,6 +1,5 @@ /// /// -/// /// /// /// diff --git a/src/server/protocol.d.ts b/src/server/protocol.ts similarity index 80% rename from src/server/protocol.d.ts rename to src/server/protocol.ts index 2f447934040..80623f05aec 100644 --- a/src/server/protocol.d.ts +++ b/src/server/protocol.ts @@ -1,7 +1,102 @@ /** * Declaration module describing the TypeScript Server protocol */ -declare namespace ts.server.protocol { +namespace ts.server.protocol { + export namespace CommandTypes { + export type Brace = "brace"; + /* @internal */ + export type BraceFull = "brace-full"; + export type BraceCompletion = "braceCompletion"; + export type Change = "change"; + export type Close = "close"; + export type Completions = "completions"; + /* @internal */ + export type CompletionsFull = "completions-full"; + export type CompletionDetails = "completionEntryDetails"; + export type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + export type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + export type Configure = "configure"; + export type Definition = "definition"; + /* @internal */ + export type DefinitionFull = "definition-full"; + export type Implementation = "implementation"; + /* @internal */ + export type ImplementationFull = "implementation-full"; + export type Exit = "exit"; + export type Format = "format"; + export type Formatonkey = "formatonkey"; + /* @internal */ + export type FormatFull = "format-full"; + /* @internal */ + export type FormatonkeyFull = "formatonkey-full"; + /* @internal */ + export type FormatRangeFull = "formatRange-full"; + export type Geterr = "geterr"; + export type GeterrForProject = "geterrForProject"; + export type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + export type NavBar = "navbar"; + /* @internal */ + export type NavBarFull = "navbar-full"; + export type Navto = "navto"; + /* @internal */ + export type NavtoFull = "navto-full"; + export type NavTree = "navtree"; + export type NavTreeFull = "navtree-full"; + export type Occurrences = "occurrences"; + export type DocumentHighlights = "documentHighlights"; + /* @internal */ + export type DocumentHighlightsFull = "documentHighlights-full"; + export type Open = "open"; + export type Quickinfo = "quickinfo"; + /* @internal */ + export type QuickinfoFull = "quickinfo-full"; + export type References = "references"; + /* @internal */ + export type ReferencesFull = "references-full"; + export type Reload = "reload"; + export type Rename = "rename"; + /* @internal */ + export type RenameInfoFull = "rename-full"; + /* @internal */ + export type RenameLocationsFull = "renameLocations-full"; + export type Saveto = "saveto"; + export type SignatureHelp = "signatureHelp"; + /* @internal */ + export type SignatureHelpFull = "signatureHelp-full"; + export type TypeDefinition = "typeDefinition"; + export type ProjectInfo = "projectInfo"; + export type ReloadProjects = "reloadProjects"; + export type Unknown = "unknown"; + export type OpenExternalProject = "openExternalProject"; + export type OpenExternalProjects = "openExternalProjects"; + export type CloseExternalProject = "closeExternalProject"; + /* @internal */ + export type SynchronizeProjectList = "synchronizeProjectList"; + /* @internal */ + export type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + /* @internal */ + export type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + /* @internal */ + export type Cleanup = "cleanup"; + /* @internal */ + export type OutliningSpans = "outliningSpans"; + export type TodoComments = "todoComments"; + export type Indentation = "indentation"; + export type DocCommentTemplate = "docCommentTemplate"; + /* @internal */ + export type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + /* @internal */ + export type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + /* @internal */ + export type BreakpointStatement = "breakpointStatement"; + export type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + export type GetCodeFixes = "getCodeFixes"; + /* @internal */ + export type GetCodeFixesFull = "getCodeFixes-full"; + export type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + /** * A TypeScript Server message */ @@ -36,6 +131,7 @@ declare namespace ts.server.protocol { * Request to reload the project structure for all the opened files */ export interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; } /** @@ -98,10 +194,25 @@ declare namespace ts.server.protocol { projectFileName?: string; } + /** + * Requests a JS Doc comment template for a given position + */ + export interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + + /** + * Response to DocCommentTemplateRequest + */ + export interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** * A request to get TODO comments from the file */ export interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; arguments: TodoCommentRequestArgs; } @@ -115,13 +226,58 @@ declare namespace ts.server.protocol { descriptors: TodoCommentDescriptor[]; } + /** + * Response for TodoCommentRequest request. + */ + export interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + + /** + * Request to obtain outlining spans in file. + */ + /* @internal */ + export interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + + /** + * Response to OutliningSpansRequest request. + */ + /* @internal */ + export interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + /** * A request to get indentation for a location in file */ export interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; arguments: IndentationRequestArgs; } + /** + * Response for IndentationRequest request. + */ + export interface IndentationResponse extends Response { + body?: IndentationResult; + } + + /** + * Indentation result representing where indentation should be placed + */ + export interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** * Arguments for IndentationRequest request. */ @@ -147,6 +303,7 @@ declare namespace ts.server.protocol { * A request to get the project information of the current file. */ export interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; arguments: ProjectInfoRequestArgs; } @@ -223,16 +380,17 @@ declare namespace ts.server.protocol { /** * The line number for the request (1-based). */ - line?: number; + line: number; /** * The character offset (on the line) for the request (1-based). */ - offset?: number; + offset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ position?: number; } @@ -240,6 +398,7 @@ declare namespace ts.server.protocol { * Request for the available codefixes at a specific position. */ export interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; arguments: CodeFixRequestArgs; } @@ -250,31 +409,33 @@ declare namespace ts.server.protocol { /** * The line number for the request (1-based). */ - startLine?: number; + startLine: number; /** * The character offset (on the line) for the request (1-based). */ - startOffset?: number; + startOffset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ startPosition?: number; /** * The line number for the request (1-based). */ - endLine?: number; + endLine: number; /** * The character offset (on the line) for the request (1-based). */ - endOffset?: number; + endOffset: number; /** * Position (can be specified instead of line/offset pair) */ + /* @internal */ endPosition?: number; /** @@ -283,6 +444,13 @@ declare namespace ts.server.protocol { errorCodes?: number[]; } + /** + * Response for GetCodeFixes request. + */ + export interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** * A request whose arguments specify a file location (file, line, col). */ @@ -291,16 +459,34 @@ declare namespace ts.server.protocol { } /** - * A request to get semantic diagnostics for a span in the file + * A request to get codes of supported code fixes. */ - export interface SemanticDiagnosticsRequest extends FileRequest { - arguments: SemanticDiagnosticsRequestArgs; + export interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; } /** - * Arguments for SemanticDiagnosticsRequest request. + * A response for GetSupportedCodeFixesRequest request. */ - export interface SemanticDiagnosticsRequestArgs extends FileRequestArgs { + export interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + + /** + * A request to get encoded semantic classifications for a span in the file + */ + /** @internal */ + export interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + export interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { /** * Start position of the span. */ @@ -328,6 +514,7 @@ declare namespace ts.server.protocol { * define the symbol found in file at location line, col. */ export interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; } /** @@ -336,6 +523,7 @@ declare namespace ts.server.protocol { * define the type for the symbol found in file at location line, col. */ export interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; } /** @@ -344,6 +532,7 @@ declare namespace ts.server.protocol { * implement the symbol found in file at location line, col. */ export interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; } /** @@ -404,6 +593,7 @@ declare namespace ts.server.protocol { * Request to get brace completion for a location in the file. */ export interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; arguments: BraceCompletionRequestArgs; } @@ -423,6 +613,7 @@ declare namespace ts.server.protocol { * in the file at a given line and column. */ export interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; } export interface OccurrencesResponseItem extends FileSpan { @@ -442,6 +633,7 @@ declare namespace ts.server.protocol { * in the file at a given line and column. */ export interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; arguments: DocumentHighlightsRequestArgs; } @@ -481,6 +673,7 @@ declare namespace ts.server.protocol { * reference the symbol found in file at location line, col. */ export interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; } export interface ReferencesResponseItem extends FileSpan { @@ -555,6 +748,7 @@ declare namespace ts.server.protocol { * name of the symbol so that client can print it unambiguously. */ export interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; arguments: RenameRequestArgs; } @@ -754,6 +948,7 @@ declare namespace ts.server.protocol { /** * Represents set of changes in open file */ + /* @internal */ export interface ChangedOpenFile { /** * Name of file @@ -765,65 +960,6 @@ declare namespace ts.server.protocol { changes: ts.TextChange[]; } - /** - * Editor options - */ - export interface EditorOptions { - - /** Number of spaces for each tab. Default value is 4. */ - tabSize?: number; - - /** Number of spaces to indent during formatting. Default value is 4. */ - indentSize?: number; - - /** Number of additional spaces to indent during formatting to preserve base indentation (ex. script block indentation). Default value is 0. */ - baseIndentSize?: number; - - /** The new line character to be used. Default value is the OS line delimiter. */ - newLineCharacter?: string; - - /** Whether tabs should be converted to spaces. Default value is true. */ - convertTabsToSpaces?: boolean; - } - - /** - * Format options - */ - export interface FormatOptions extends EditorOptions { - - /** Defines space handling after a comma delimiter. Default value is true. */ - insertSpaceAfterCommaDelimiter?: boolean; - - /** Defines space handling after a semicolon in a for statement. Default value is true */ - insertSpaceAfterSemicolonInForStatements?: boolean; - - /** Defines space handling after a binary operator. Default value is true. */ - insertSpaceBeforeAndAfterBinaryOperators?: boolean; - - /** Defines space handling after keywords in control flow statement. Default value is true. */ - insertSpaceAfterKeywordsInControlFlowStatements?: boolean; - - /** Defines space handling after function keyword for anonymous functions. Default value is false. */ - insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; - - /** Defines space handling after opening and before closing non empty parenthesis. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; - - /** Defines space handling after opening and before closing non empty brackets. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; - - /** Defines space handling before and after template string braces. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; - - /** Defines space handling before and after JSX expression braces. Default value is false. */ - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; - - /** Defines whether an open brace is put onto a new line for functions or not. Default value is false. */ - placeOpenBraceOnNewLineForFunctions?: boolean; - - /** Defines whether an open brace is put onto a new line for control blocks or not. Default value is false. */ - placeOpenBraceOnNewLineForControlBlocks?: boolean; - } /** * Information found in a configure request. @@ -844,12 +980,7 @@ declare namespace ts.server.protocol { /** * The format options to use during formatting and other code editing features. */ - formatOptions?: FormatOptions; - - /** - * If set to true - then all loose files will land into one inferred project - */ - useOneInferredProject?: boolean; + formatOptions?: FormatCodeSettings; } /** @@ -857,6 +988,7 @@ declare namespace ts.server.protocol { * host information, such as host type, tab size, and indent size. */ export interface ConfigureRequest extends Request { + command: CommandTypes.Configure; arguments: ConfigureRequestArguments; } @@ -892,6 +1024,7 @@ declare namespace ts.server.protocol { * send a response to an open request. */ export interface OpenRequest extends Request { + command: CommandTypes.Open; arguments: OpenRequestArgs; } @@ -899,18 +1032,20 @@ declare namespace ts.server.protocol { * Request to open or update external project */ export interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; arguments: OpenExternalProjectArgs; } /** * Arguments to OpenExternalProjectRequest request */ - type OpenExternalProjectArgs = ExternalProject; + export type OpenExternalProjectArgs = ExternalProject; /** * Request to open multiple external projects */ export interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; arguments: OpenExternalProjectsArgs; } @@ -924,10 +1059,25 @@ declare namespace ts.server.protocol { projects: ExternalProject[]; } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface OpenExternalProjectResponse extends Response { + } + + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface OpenExternalProjectsResponse extends Response { + } + /** * Request to close external project. */ export interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; arguments: CloseExternalProjectRequestArgs; } @@ -941,9 +1091,17 @@ declare namespace ts.server.protocol { projectFileName: string; } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + export interface CloseExternalProjectResponse extends Response { + } + /** * Request to check if given list of projects is up-to-date and synchronize them if necessary */ + /* @internal */ export interface SynchronizeProjectListRequest extends Request { arguments: SynchronizeProjectListRequestArgs; } @@ -961,6 +1119,7 @@ declare namespace ts.server.protocol { /** * Request to synchronize list of open files with the client */ + /* @internal */ export interface ApplyChangedToOpenFilesRequest extends Request { arguments: ApplyChangedToOpenFilesRequestArgs; } @@ -968,6 +1127,7 @@ declare namespace ts.server.protocol { /** * Arguments to ApplyChangedToOpenFilesRequest */ + /* @internal */ export interface ApplyChangedToOpenFilesRequestArgs { /** * List of newly open files @@ -993,6 +1153,7 @@ declare namespace ts.server.protocol { * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. */ export interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; arguments: SetCompilerOptionsForInferredProjectsArgs; } @@ -1006,11 +1167,19 @@ declare namespace ts.server.protocol { options: ExternalProjectCompilerOptions; } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + export interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** * Exit request; value of command field is "exit". Ask the server process * to exit. */ export interface ExitRequest extends Request { + command: CommandTypes.Exit; } /** @@ -1021,6 +1190,7 @@ declare namespace ts.server.protocol { * currently send a response to a close request. */ export interface CloseRequest extends FileRequest { + command: CommandTypes.Close; } /** @@ -1028,6 +1198,7 @@ declare namespace ts.server.protocol { * NOTE: this us query-only operation and does not generate any output on disk. */ export interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; } /** @@ -1055,7 +1226,8 @@ declare namespace ts.server.protocol { * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. */ export interface CompileOnSaveEmitFileRequest extends FileRequest { - args: CompileOnSaveEmitFileRequestArgs; + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; } /** @@ -1075,6 +1247,7 @@ declare namespace ts.server.protocol { * line, col. */ export interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; } /** @@ -1136,12 +1309,12 @@ declare namespace ts.server.protocol { /** * End position of the range for which to format text in file. */ + /* @internal */ endPosition?: number; - /** * Format options to be used. */ - options?: ts.FormatCodeOptions; + options?: FormatCodeSettings; } /** @@ -1152,6 +1325,7 @@ declare namespace ts.server.protocol { * reformatted text. */ export interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; arguments: FormatRequestArgs; } @@ -1213,7 +1387,7 @@ declare namespace ts.server.protocol { */ key: string; - options?: ts.FormatCodeOptions; + options?: FormatCodeSettings; } /** @@ -1225,6 +1399,7 @@ declare namespace ts.server.protocol { * reformatted text. */ export interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; arguments: FormatOnKeyRequestArgs; } @@ -1245,6 +1420,7 @@ declare namespace ts.server.protocol { * begin with prefix. */ export interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; arguments: CompletionsRequestArgs; } @@ -1265,6 +1441,7 @@ declare namespace ts.server.protocol { * detailed information for each completion entry. */ export interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; arguments: CompletionDetailsRequestArgs; } @@ -1451,6 +1628,7 @@ declare namespace ts.server.protocol { * help. */ export interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; arguments: SignatureHelpRequestArgs; } @@ -1465,6 +1643,7 @@ declare namespace ts.server.protocol { * Synchronous request for semantic diagnostics of one file. */ export interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; arguments: SemanticDiagnosticsSyncRequestArgs; } @@ -1483,6 +1662,7 @@ declare namespace ts.server.protocol { * Synchronous request for syntactic diagnostics of one file. */ export interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; arguments: SyntacticDiagnosticsSyncRequestArgs; } @@ -1519,6 +1699,7 @@ declare namespace ts.server.protocol { * it request for every file in this project. */ export interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; arguments: GeterrForProjectRequestArgs; } @@ -1550,6 +1731,7 @@ declare namespace ts.server.protocol { * file that is currently visible, in most-recently-used order. */ export interface GeterrRequest extends Request { + command: CommandTypes.Geterr; arguments: GeterrRequestArgs; } @@ -1642,11 +1824,12 @@ declare namespace ts.server.protocol { * The two names can be identical. */ export interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; arguments: ReloadRequestArgs; } /** - * Response to "reload" request. This is just an acknowledgement, so + * Response to "reload" request. This is just an acknowledgement, so * no body field is required. */ export interface ReloadResponse extends Response { @@ -1671,6 +1854,7 @@ declare namespace ts.server.protocol { * "saveto" request. */ export interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; arguments: SavetoRequestArgs; } @@ -1703,6 +1887,7 @@ declare namespace ts.server.protocol { * context for the search is given by the named file. */ export interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; arguments: NavtoRequestArgs; } @@ -1786,6 +1971,7 @@ declare namespace ts.server.protocol { * Server does not currently send a response to a change request. */ export interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; arguments: ChangeRequestArgs; } @@ -1802,6 +1988,7 @@ declare namespace ts.server.protocol { * found in file at location line, offset. */ export interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; } /** @@ -1810,6 +1997,7 @@ declare namespace ts.server.protocol { * extracted from the requested file. */ export interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; } /** @@ -1817,6 +2005,7 @@ declare namespace ts.server.protocol { * Return response giving the navigation tree of the requested file. */ export interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; } export interface NavigationBarItem { diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index ee5122ff4e1..68dd59d2d32 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -91,7 +91,7 @@ namespace ts.server { return this.containingProjects[0]; } - setFormatOptions(formatSettings: protocol.FormatOptions): void { + setFormatOptions(formatSettings: FormatCodeSettings): void { if (formatSettings) { if (!this.formatCodeSettings) { this.formatCodeSettings = getDefaultFormatCodeSettings(this.host); diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index 1508187c13e..8d0efa081ad 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -1,6 +1,5 @@ /// /// -/// /// namespace ts.server { diff --git a/src/server/session.ts b/src/server/session.ts index 172ae70d95a..111ba53a700 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// namespace ts.server { @@ -83,74 +83,74 @@ namespace ts.server { } export namespace CommandNames { - export const Brace = "brace"; - export const BraceFull = "brace-full"; - export const BraceCompletion = "braceCompletion"; - export const Change = "change"; - export const Close = "close"; - export const Completions = "completions"; - export const CompletionsFull = "completions-full"; - export const CompletionDetails = "completionEntryDetails"; - export const CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; - export const CompileOnSaveEmitFile = "compileOnSaveEmitFile"; - export const Configure = "configure"; - export const Definition = "definition"; - export const DefinitionFull = "definition-full"; - export const Exit = "exit"; - export const Format = "format"; - export const Formatonkey = "formatonkey"; - export const FormatFull = "format-full"; - export const FormatonkeyFull = "formatonkey-full"; - export const FormatRangeFull = "formatRange-full"; - export const Geterr = "geterr"; - export const GeterrForProject = "geterrForProject"; - export const Implementation = "implementation"; - export const ImplementationFull = "implementation-full"; - export const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - export const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - export const NavBar = "navbar"; - export const NavBarFull = "navbar-full"; - export const NavTree = "navtree"; - export const NavTreeFull = "navtree-full"; - export const Navto = "navto"; - export const NavtoFull = "navto-full"; - export const Occurrences = "occurrences"; - export const DocumentHighlights = "documentHighlights"; - export const DocumentHighlightsFull = "documentHighlights-full"; - export const Open = "open"; - export const Quickinfo = "quickinfo"; - export const QuickinfoFull = "quickinfo-full"; - export const References = "references"; - export const ReferencesFull = "references-full"; - export const Reload = "reload"; - export const Rename = "rename"; - export const RenameInfoFull = "rename-full"; - export const RenameLocationsFull = "renameLocations-full"; - export const Saveto = "saveto"; - export const SignatureHelp = "signatureHelp"; - export const SignatureHelpFull = "signatureHelp-full"; - export const TypeDefinition = "typeDefinition"; - export const ProjectInfo = "projectInfo"; - export const ReloadProjects = "reloadProjects"; - export const Unknown = "unknown"; - export const OpenExternalProject = "openExternalProject"; - export const OpenExternalProjects = "openExternalProjects"; - export const CloseExternalProject = "closeExternalProject"; - export const SynchronizeProjectList = "synchronizeProjectList"; - export const ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; - export const EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; - export const Cleanup = "cleanup"; - export const OutliningSpans = "outliningSpans"; - export const TodoComments = "todoComments"; - export const Indentation = "indentation"; - export const DocCommentTemplate = "docCommentTemplate"; - export const CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; - export const NameOrDottedNameSpan = "nameOrDottedNameSpan"; - export const BreakpointStatement = "breakpointStatement"; - export const CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; - export const GetCodeFixes = "getCodeFixes"; - export const GetCodeFixesFull = "getCodeFixes-full"; - export const GetSupportedCodeFixes = "getSupportedCodeFixes"; + export const Brace: protocol.CommandTypes.Brace = "brace"; + export const BraceFull: protocol.CommandTypes.BraceFull = "brace-full"; + export const BraceCompletion: protocol.CommandTypes.BraceCompletion = "braceCompletion"; + export const Change: protocol.CommandTypes.Change = "change"; + export const Close: protocol.CommandTypes.Close = "close"; + export const Completions: protocol.CommandTypes.Completions = "completions"; + export const CompletionsFull: protocol.CommandTypes.CompletionsFull = "completions-full"; + export const CompletionDetails: protocol.CommandTypes.CompletionDetails = "completionEntryDetails"; + export const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + export const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + export const Configure: protocol.CommandTypes.Configure = "configure"; + export const Definition: protocol.CommandTypes.Definition = "definition"; + export const DefinitionFull: protocol.CommandTypes.DefinitionFull = "definition-full"; + export const Exit: protocol.CommandTypes.Exit = "exit"; + export const Format: protocol.CommandTypes.Format = "format"; + export const Formatonkey: protocol.CommandTypes.Formatonkey = "formatonkey"; + export const FormatFull: protocol.CommandTypes.FormatFull = "format-full"; + export const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull = "formatonkey-full"; + export const FormatRangeFull: protocol.CommandTypes.FormatRangeFull = "formatRange-full"; + export const Geterr: protocol.CommandTypes.Geterr = "geterr"; + export const GeterrForProject: protocol.CommandTypes.GeterrForProject = "geterrForProject"; + export const Implementation: protocol.CommandTypes.Implementation = "implementation"; + export const ImplementationFull: protocol.CommandTypes.ImplementationFull = "implementation-full"; + export const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + export const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + export const NavBar: protocol.CommandTypes.NavBar = "navbar"; + export const NavBarFull: protocol.CommandTypes.NavBarFull = "navbar-full"; + export const NavTree: protocol.CommandTypes.NavTree = "navtree"; + export const NavTreeFull: protocol.CommandTypes.NavTreeFull = "navtree-full"; + export const Navto: protocol.CommandTypes.Navto = "navto"; + export const NavtoFull: protocol.CommandTypes.NavtoFull = "navto-full"; + export const Occurrences: protocol.CommandTypes.Occurrences = "occurrences"; + export const DocumentHighlights: protocol.CommandTypes.DocumentHighlights = "documentHighlights"; + export const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull = "documentHighlights-full"; + export const Open: protocol.CommandTypes.Open = "open"; + export const Quickinfo: protocol.CommandTypes.Quickinfo = "quickinfo"; + export const QuickinfoFull: protocol.CommandTypes.QuickinfoFull = "quickinfo-full"; + export const References: protocol.CommandTypes.References = "references"; + export const ReferencesFull: protocol.CommandTypes.ReferencesFull = "references-full"; + export const Reload: protocol.CommandTypes.Reload = "reload"; + export const Rename: protocol.CommandTypes.Rename = "rename"; + export const RenameInfoFull: protocol.CommandTypes.RenameInfoFull = "rename-full"; + export const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull = "renameLocations-full"; + export const Saveto: protocol.CommandTypes.Saveto = "saveto"; + export const SignatureHelp: protocol.CommandTypes.SignatureHelp = "signatureHelp"; + export const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull = "signatureHelp-full"; + export const TypeDefinition: protocol.CommandTypes.TypeDefinition = "typeDefinition"; + export const ProjectInfo: protocol.CommandTypes.ProjectInfo = "projectInfo"; + export const ReloadProjects: protocol.CommandTypes.ReloadProjects = "reloadProjects"; + export const Unknown: protocol.CommandTypes.Unknown = "unknown"; + export const OpenExternalProject: protocol.CommandTypes.OpenExternalProject = "openExternalProject"; + export const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects = "openExternalProjects"; + export const CloseExternalProject: protocol.CommandTypes.CloseExternalProject = "closeExternalProject"; + export const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList = "synchronizeProjectList"; + export const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + export const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + export const Cleanup: protocol.CommandTypes.Cleanup = "cleanup"; + export const OutliningSpans: protocol.CommandTypes.OutliningSpans = "outliningSpans"; + export const TodoComments: protocol.CommandTypes.TodoComments = "todoComments"; + export const Indentation: protocol.CommandTypes.Indentation = "indentation"; + export const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate = "docCommentTemplate"; + export const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + export const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + export const BreakpointStatement: protocol.CommandTypes.BreakpointStatement = "breakpointStatement"; + export const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + export const GetCodeFixes: protocol.CommandTypes.GetCodeFixes = "getCodeFixes"; + export const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull = "getCodeFixes-full"; + export const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes = "getSupportedCodeFixes"; } export function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string { @@ -363,7 +363,7 @@ namespace ts.server { } } - private getEncodedSemanticClassifications(args: protocol.SemanticDiagnosticsRequestArgs) { + private getEncodedSemanticClassifications(args: protocol.EncodedSemanticClassificationsRequestArgs) { const { file, project } = this.getFileAndProject(args); return project.getLanguageService().getEncodedSemanticClassifications(file, args); } @@ -1470,7 +1470,7 @@ namespace ts.server { [CommandNames.BraceCompletion]: (request: protocol.BraceCompletionRequest) => { return this.requiredResponse(this.isValidBraceCompletion(request.arguments)); }, - [CommandNames.DocCommentTemplate]: (request: protocol.FileLocationRequest) => { + [CommandNames.DocCommentTemplate]: (request: protocol.DocCommentTemplateRequest) => { return this.requiredResponse(this.getDocCommentTemplate(request.arguments)); }, [CommandNames.Format]: (request: protocol.FormatRequest) => { @@ -1512,7 +1512,7 @@ namespace ts.server { [CommandNames.CompilerOptionsDiagnosticsFull]: (request: protocol.CompilerOptionsDiagnosticsRequest) => { return this.requiredResponse(this.getCompilerOptionsDiagnostics(request.arguments)); }, - [CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.SemanticDiagnosticsRequest) => { + [CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.EncodedSemanticClassificationsRequest) => { return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments)); }, [CommandNames.Cleanup]: (request: protocol.Request) => { diff --git a/src/server/tsconfig.json b/src/server/tsconfig.json index 7eb8c28f383..9f907446c03 100644 --- a/src/server/tsconfig.json +++ b/src/server/tsconfig.json @@ -22,7 +22,7 @@ "typingsCache.ts", "project.ts", "editorServices.ts", - "protocol.d.ts", + "protocol.ts", "session.ts", "server.ts" ] diff --git a/src/services/types.ts b/src/services/types.ts index 9797c07b086..3d2bcf4c360 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -403,11 +403,11 @@ namespace ts { export interface EditorSettings { baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } /* @deprecated - consider using FormatCodeSettings instead */ @@ -428,19 +428,19 @@ namespace ts { } export interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; insertSpaceAfterTypeAssertion?: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } export interface DefinitionInfo { From c03b04bd4f278dc338ba15017ee8c47b20d96163 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Wed, 12 Oct 2016 14:26:30 -0700 Subject: [PATCH 35/74] Only use localeCompare in CompareStrings --- src/compiler/core.ts | 20 +++++++++++++------- src/harness/harness.ts | 2 +- src/server/session.ts | 2 +- src/services/navigateTo.ts | 4 ++-- src/services/navigationBar.ts | 2 +- 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 5ad9fa2c199..47eb66db07c 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -23,6 +23,10 @@ namespace ts { // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; + // This means "compare in a case insensitive manner but consider accentsor other diacritic marks" + // (e.g. a ≠ b, a ≠ á, a = A) + const accentSensitivity: Intl.CollatorOptions = { usage: "sort", sensitivity: "accent" }; + /** * Use this function instead of calling "String.prototype.localeCompre". This function will preform appropriate check to make sure that * "typeof Intl" is correct as there are reported issues #11110 nad #11339. @@ -1029,13 +1033,13 @@ namespace ts { return a < b ? Comparison.LessThan : Comparison.GreaterThan; } - export function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison { + export function compareStrings(a: string, b: string, locales?: string | string[], options?: Intl.CollatorOptions): Comparison { if (a === b) return Comparison.EqualTo; if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; - if (ignoreCase) { - const result = localeCompare(a, b, /*locales*/ undefined, /*options*/ { usage: "sort", sensitivity: "accent" }); - if (result) { + if (options) { + if (collator && String.prototype.localeCompare) { + const result = a.localeCompare(b, locales, options); return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo; } @@ -1048,7 +1052,7 @@ namespace ts { } export function compareStringsCaseInsensitive(a: string, b: string) { - return compareStrings(a, b, /*ignoreCase*/ true); + return compareStrings(a, b, /*locales*/ undefined, accentSensitivity); } function getDiagnosticFileName(diagnostic: Diagnostic): string { @@ -1418,7 +1422,8 @@ namespace ts { const bComponents = getNormalizedPathComponents(b, currentDirectory); const sharedLength = Math.min(aComponents.length, bComponents.length); for (let i = 0; i < sharedLength; i++) { - const result = compareStrings(aComponents[i], bComponents[i], ignoreCase); + const result = compareStrings(aComponents[i], bComponents[i], + /*locales*/ undefined, /*options*/ ignoreCase ? accentSensitivity : undefined); if (result !== Comparison.EqualTo) { return result; } @@ -1440,7 +1445,8 @@ namespace ts { } for (let i = 0; i < parentComponents.length; i++) { - const result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); + const result = compareStrings(parentComponents[i], childComponents[i], + /*locales*/ undefined, /*options*/ ignoreCase ? accentSensitivity : undefined); if (result !== Comparison.EqualTo) { return false; } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index f26a9dd062b..9d27257c80f 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1634,7 +1634,7 @@ namespace Harness { export function collateOutputs(outputFiles: Harness.Compiler.GeneratedFile[]): string { // Collect, test, and sort the fileNames - outputFiles.sort((a, b) => ts.localeCompare(cleanName(a.fileName), cleanName(b.fileName))); + outputFiles.sort((a, b) => ts.compareStrings(cleanName(a.fileName), cleanName(b.fileName))); // Emit them let result = ""; diff --git a/src/server/session.ts b/src/server/session.ts index d4633f119e3..cebdef717bc 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -959,7 +959,7 @@ namespace ts.server { result.push({ name, kind, kindModifiers, sortText, replacementSpan: convertedSpan }); } return result; - }, []).sort((a, b) => localeCompare(a.name, b.name)); + }, []).sort((a, b) => ts.compareStrings(a.name, b.name)); } else { return completions; diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 8c968db7ebb..2433dbe9795 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -188,8 +188,8 @@ namespace ts.NavigateTo { // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - ts.localeCompare(i1.name, i2.name, /*locales*/ undefined, /*options*/ baseSensitivity) || - ts.localeCompare(i1.name, i2.name); + ts.compareStrings(i1.name, i2.name, /*locales*/ undefined, /*options*/ baseSensitivity) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index f981ad6016d..4dacf202ef8 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -335,7 +335,7 @@ namespace ts.NavigationBar { if (chA === "'" && chB === "\"") { return -1; } - const cmp = ts.localeCompare(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); + const cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } From 7bbaef66aec9875c4abf38cb2c5f2aa136d7b7c3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Oct 2016 15:09:02 -0700 Subject: [PATCH 36/74] Change error message for referencing UMD globals from a module. --- src/compiler/checker.ts | 2 +- src/compiler/diagnosticMessages.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dfe6317e250..f24d5e3e0cb 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -922,7 +922,7 @@ namespace ts { if (result && isInExternalModule && (meaning & SymbolFlags.Value) === SymbolFlags.Value) { const decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === SyntaxKind.NamespaceExportDeclaration) { - error(errorLocation, Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 58c0e6ee3f2..b99a1a91b8e 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1923,7 +1923,7 @@ "category": "Error", "code": 2685 }, - "Identifier '{0}' must be imported from a module": { + "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead.": { "category": "Error", "code": 2686 }, From fbb9d5b148ff1a15d58a023bf5a464e901b0384e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Oct 2016 15:09:36 -0700 Subject: [PATCH 37/74] Accepted baselines. --- tests/baselines/reference/umd5.errors.txt | 4 ++-- tests/baselines/reference/umd8.errors.txt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/baselines/reference/umd5.errors.txt b/tests/baselines/reference/umd5.errors.txt index 9628ad738db..5595de8de29 100644 --- a/tests/baselines/reference/umd5.errors.txt +++ b/tests/baselines/reference/umd5.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: Identifier 'Foo' must be imported from a module +tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/a.ts (1 errors) ==== @@ -9,7 +9,7 @@ tests/cases/conformance/externalModules/a.ts(6,9): error TS2686: Identifier 'Foo // should error let z = Foo; ~~~ -!!! error TS2686: Identifier 'Foo' must be imported from a module +!!! error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/foo.d.ts (0 errors) ==== diff --git a/tests/baselines/reference/umd8.errors.txt b/tests/baselines/reference/umd8.errors.txt index 9396c8c5450..26c8adef561 100644 --- a/tests/baselines/reference/umd8.errors.txt +++ b/tests/baselines/reference/umd8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: Identifier 'Foo' must be imported from a module +tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/a.ts (1 errors) ==== @@ -10,7 +10,7 @@ tests/cases/conformance/externalModules/a.ts(7,14): error TS2686: Identifier 'Fo let z: Foo.SubThing; // OK in ns position let x: any = Foo; // Not OK in value position ~~~ -!!! error TS2686: Identifier 'Foo' must be imported from a module +!!! error TS2686: 'Foo' refers to a UMD global, but the current file is a module. Consider adding an import instead. ==== tests/cases/conformance/externalModules/foo.d.ts (0 errors) ==== From e60e97f5c9d7a2c21ba36631c17f9278166feeae Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 01:04:38 +0200 Subject: [PATCH 38/74] Cleanup comments --- src/compiler/transformers/es2017.ts | 2 -- src/compiler/transformers/ts.ts | 8 -------- 2 files changed, 10 deletions(-) diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 33376bbceb1..166e1160828 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -71,8 +71,6 @@ namespace ts { return visitEachChild(node, visitor, context); } - // node = visitEachChild(node, visitor, context); - // return visitEachChild(node, visitor, context); return node; } diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 30276deff92..2aa20410d8c 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -2247,10 +2247,6 @@ namespace ts { } function transformFunctionBody(node: MethodDeclaration | AccessorDeclaration | FunctionDeclaration | FunctionExpression): FunctionBody { - // if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES2017) { - // return transformAsyncFunctionBody(node); - // } - return transformFunctionBodyWorker(node.body); } @@ -2267,10 +2263,6 @@ namespace ts { } function transformConciseBody(node: ArrowFunction): ConciseBody { - // if (isAsyncFunctionLike(node) && languageVersion < ScriptTarget.ES2017) { - // return transformAsyncFunctionBody(node); - // } - return transformConciseBodyWorker(node.body, /*forceBlockFunctionBody*/ false); } From f0fd77ae8edb070e9f01cb0b5f6c69e9454f393a Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 11:58:01 +0200 Subject: [PATCH 39/74] Make async/await an ES2017 feature only --- src/compiler/binder.ts | 31 ++++++++---------- src/compiler/transformers/es2017.ts | 13 ++++---- src/compiler/transformers/ts.ts | 49 ++++++----------------------- 3 files changed, 28 insertions(+), 65 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 4edbb5d9e1a..3f5db2ae7c5 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2555,11 +2555,6 @@ namespace ts { // extends clause of a class. let transformFlags = subtreeFlags | TransformFlags.AssertES6; - // propagate ES2017 - if (node.expression.transformFlags & TransformFlags.ContainsES2017) { - transformFlags |= TransformFlags.ContainsES2017; - } - // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. if (node.typeArguments) { @@ -2591,16 +2586,16 @@ namespace ts { const typeParameters = node.typeParameters; const asteriskToken = node.asteriskToken; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // A MethodDeclaration is TypeScript syntax if it is either abstract, overloaded, // generic, or has a decorator. if (!body || typeParameters - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) + || (modifierFlags & ModifierFlags.Abstract) || (subtreeFlags & TransformFlags.ContainsDecorators)) { transformFlags |= TransformFlags.AssertTypeScript; } - // Async MethodDeclaration is ES2017 + // An async method declaration is ES2017 syntax. if (modifierFlags & ModifierFlags.Async) { transformFlags |= TransformFlags.AssertES2017; } @@ -2619,10 +2614,10 @@ namespace ts { const modifierFlags = getModifierFlags(node); const body = node.body; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, + // An accessor is TypeScript syntax if it is either abstract, overloaded, // generic, or has a decorator. if (!body - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) + || (modifierFlags & ModifierFlags.Abstract) || (subtreeFlags & TransformFlags.ContainsDecorators)) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2664,9 +2659,9 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6; } - // If a FunctionDeclaration is async, then it is TypeScript syntax. + // An async function declaration is ES2017 syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; + transformFlags |= TransformFlags.AssertES2017; } // If a FunctionDeclaration's subtree has marked the container as needing to capture the @@ -2695,9 +2690,9 @@ namespace ts { const modifierFlags = getModifierFlags(node); const asteriskToken = node.asteriskToken; - // An async function expression is TypeScript syntax. + // An async function expression is ES2017 syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; + transformFlags |= TransformFlags.AssertES2017; } // If a FunctionExpression's subtree has marked the container as needing to capture the @@ -2725,9 +2720,9 @@ namespace ts { let transformFlags = subtreeFlags | TransformFlags.AssertES6; const modifierFlags = getModifierFlags(node); - // An async arrow function is TypeScript syntax. + // An async arrow function is ES2017 syntax. if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; + transformFlags |= TransformFlags.AssertES2017; } // If an ArrowFunction contains a lexical this, its container must capture the lexical this. @@ -2868,8 +2863,8 @@ namespace ts { switch (kind) { case SyntaxKind.AsyncKeyword: case SyntaxKind.AwaitExpression: - // Typescript async/await are ES2017 features - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2017; + // async/await is ES2017 syntax + transformFlags |= TransformFlags.AssertES2017; break; case SyntaxKind.PublicKeyword: diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 166e1160828..7555c3bdd77 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -77,26 +77,27 @@ namespace ts { function visitorWorker(node: Node): VisitResult { switch (node.kind) { case SyntaxKind.AsyncKeyword: + // ES2017 async modifier should be elided for targets < ES2017 return undefined; case SyntaxKind.AwaitExpression: - // Typescript 'await' expressions must be transformed for targets < ES2017. + // ES2017 'await' expressions must be transformed for targets < ES2017. return visitAwaitExpression(node); case SyntaxKind.MethodDeclaration: - // TypeScript method declarations may be 'async' + // ES2017 method declarations may be 'async' return visitMethodDeclaration(node); case SyntaxKind.FunctionDeclaration: - // TypeScript function declarations may be 'async' + // ES2017 function declarations may be 'async' return visitFunctionDeclaration(node); case SyntaxKind.FunctionExpression: - // TypeScript function expressions may be 'async' + // ES2017 function expressions may be 'async' return visitFunctionExpression(node); case SyntaxKind.ArrowFunction: - // TypeScript arrow functions may be 'async' + // ES2017 arrow functions may be 'async' return visitArrowFunction(node); default: @@ -160,9 +161,7 @@ namespace ts { * Visits a function declaration. * * This function will be called when one of the following conditions are met: - * - The node is an overload * - The node is marked async - * - The node is exported from a TypeScript namespace * * @param node The function node. */ diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 2aa20410d8c..61f40e1ed80 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -230,10 +230,6 @@ namespace ts { // ES6 export and default modifiers are elided when inside a namespace. return currentNamespace ? undefined : node; - // Typescript ES2017 async/await are handled by ES2017 transformer - case SyntaxKind.AsyncKeyword: - return node; - case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.ProtectedKeyword: @@ -297,7 +293,6 @@ namespace ts { // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassDeclaration(node); case SyntaxKind.ClassExpression: @@ -310,7 +305,6 @@ namespace ts { // - property declarations // - index signatures // - method overload signatures - // - async methods return visitClassExpression(node); case SyntaxKind.HeritageClause: @@ -325,7 +319,7 @@ namespace ts { return visitExpressionWithTypeArguments(node); case SyntaxKind.MethodDeclaration: - // TypeScript method declarations may be 'async', and may have decorators, modifiers + // TypeScript method declarations may have decorators, modifiers // or type annotations. return visitMethodDeclaration(node); @@ -334,19 +328,19 @@ namespace ts { return visitGetAccessor(node); case SyntaxKind.SetAccessor: - // Set Accessors can have TypeScript modifiers, decorators, and type annotations. + // Set Accessors can have TypeScript modifiers and type annotations. return visitSetAccessor(node); case SyntaxKind.FunctionDeclaration: - // TypeScript function declarations may be 'async' + // Typescript function declarations can have modifiers, decorators, and type annotations. return visitFunctionDeclaration(node); case SyntaxKind.FunctionExpression: - // TypeScript function expressions may be 'async' + // TypeScript function expressions can have modifiers and type annotations. return visitFunctionExpression(node); case SyntaxKind.ArrowFunction: - // TypeScript arrow functions may be 'async' + // TypeScript arrow functions can have modifiers and type annotations. return visitArrowFunction(node); case SyntaxKind.Parameter: @@ -378,10 +372,6 @@ namespace ts { // TypeScript enum declarations do not exist in ES6 and must be rewritten. return visitEnumDeclaration(node); - case SyntaxKind.AwaitExpression: - // Typescript ES2017 async/await are handled by ES2017 transformer - return visitAwaitExpression(node); - case SyntaxKind.VariableStatement: // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); @@ -2050,7 +2040,7 @@ namespace ts { * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked as abstract, async, public, private, protected, or readonly + * - The node is marked as abstract, public, private, protected, or readonly * - The node has both a decorator and a computed property name * * @param node The method node. @@ -2161,8 +2151,8 @@ namespace ts { * * This function will be called when one of the following conditions are met: * - The node is an overload - * - The node is marked async * - The node is exported from a TypeScript namespace + * - The node has decorators * * @param node The function node. */ @@ -2197,7 +2187,7 @@ namespace ts { * Visits a function expression node. * * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations * * @param node The function expression node. */ @@ -2216,10 +2206,6 @@ namespace ts { /*location*/ node ); - // Keep modifiers in case of async functions - const funcModifiers = visitNodes(node.modifiers, visitor, isModifier); - func.modifiers = createNodeArray(funcModifiers); - setOriginalNode(func, node); return func; @@ -2228,7 +2214,7 @@ namespace ts { /** * @remarks * This function will be called when one of the following conditions are met: - * - The node is marked async + * - The node has type annotations */ function visitArrowFunction(node: ArrowFunction) { const func = createArrowFunction( @@ -2368,23 +2354,6 @@ namespace ts { } } - /** - * Visits an await expression. - * - * This function will be called any time a ES2017 await expression is encountered. - * - * @param node The await expression node. - */ - function visitAwaitExpression(node: AwaitExpression): Expression { - return updateNode( - createAwait( - visitNode(node.expression, visitor, isExpression), - /*location*/ node - ), - node - ); - } - /** * Visits a parenthesized expression that contains either a type assertion or an `as` * expression. From 4284a749b45c441dab54f699e1aa5087527ffeac Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 11:32:26 +0200 Subject: [PATCH 40/74] Adjust some async conformance baselines --- .../reference/asyncFunctionDeclaration10_es2017.js | 1 + tests/baselines/reference/asyncFunctionDeclaration10_es5.js | 6 ++++++ tests/baselines/reference/asyncFunctionDeclaration10_es6.js | 3 +++ .../reference/asyncFunctionDeclaration12_es2017.js | 2 +- .../baselines/reference/asyncFunctionDeclaration5_es2017.js | 1 + tests/baselines/reference/asyncFunctionDeclaration5_es5.js | 5 +++++ tests/baselines/reference/asyncFunctionDeclaration5_es6.js | 3 +++ 7 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js index 0e687c1e0d5..f8a22204311 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es2017.js @@ -3,5 +3,6 @@ async function foo(a = await => await): Promise { } //// [asyncFunctionDeclaration10_es2017.js] +async function foo(a = await ) { } await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es5.js b/tests/baselines/reference/asyncFunctionDeclaration10_es5.js index 05ff9daa9da..758bdab5dc9 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration10_es5.js +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es5.js @@ -3,5 +3,11 @@ async function foo(a = await => await): Promise { } //// [asyncFunctionDeclaration10_es5.js] +function foo(a) { + if (a === void 0) { a = yield ; } + return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration10_es6.js b/tests/baselines/reference/asyncFunctionDeclaration10_es6.js index 141c0cbab55..1f175035bf0 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration10_es6.js +++ b/tests/baselines/reference/asyncFunctionDeclaration10_es6.js @@ -3,5 +3,8 @@ async function foo(a = await => await): Promise { } //// [asyncFunctionDeclaration10_es6.js] +function foo(a = yield ) { + return __awaiter(this, void 0, void 0, function* () { }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js index 69f5993f5c0..93fbb061023 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js +++ b/tests/baselines/reference/asyncFunctionDeclaration12_es2017.js @@ -2,4 +2,4 @@ var v = async function await(): Promise { } //// [asyncFunctionDeclaration12_es2017.js] -var v = , await = () => { }; +var v = async function () { }, await = () => { }; diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js index 13c04c5d5bc..904bbe62f0b 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es2017.js @@ -3,5 +3,6 @@ async function foo(await): Promise { } //// [asyncFunctionDeclaration5_es2017.js] +async function foo() { } await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es5.js b/tests/baselines/reference/asyncFunctionDeclaration5_es5.js index 22c18ff6ad4..5f8f8f42735 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration5_es5.js +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es5.js @@ -3,5 +3,10 @@ async function foo(await): Promise { } //// [asyncFunctionDeclaration5_es5.js] +function foo() { + return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { + return [2 /*return*/]; + }); }); +} await; Promise < void > {}; diff --git a/tests/baselines/reference/asyncFunctionDeclaration5_es6.js b/tests/baselines/reference/asyncFunctionDeclaration5_es6.js index 8d28c371465..9521b760415 100644 --- a/tests/baselines/reference/asyncFunctionDeclaration5_es6.js +++ b/tests/baselines/reference/asyncFunctionDeclaration5_es6.js @@ -3,5 +3,8 @@ async function foo(await): Promise { } //// [asyncFunctionDeclaration5_es6.js] +function foo() { + return __awaiter(this, void 0, void 0, function* () { }); +} await; Promise < void > {}; From 7df3fda2b36e6a1eda5478a9077074e57e35c925 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 12:03:53 +0200 Subject: [PATCH 41/74] Refactor createFunctionExpresson --- src/compiler/factory.ts | 17 +++++++++++------ src/compiler/transformers/es2017.ts | 3 +-- src/compiler/transformers/es6.ts | 5 ++++- src/compiler/transformers/generators.ts | 4 +++- src/compiler/transformers/module/module.ts | 1 + src/compiler/transformers/module/system.ts | 3 +++ src/compiler/transformers/ts.ts | 3 +++ src/compiler/visitor.ts | 3 ++- 8 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index d873c3ef877..519269ccfd0 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -524,9 +524,9 @@ namespace ts { return node; } - export function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) { + export function createFunctionExpression(modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags) { const node = createNode(SyntaxKind.FunctionExpression, location, flags); - node.modifiers = undefined; + node.modifiers = modifiers ? createNodeArray(modifiers) : undefined; node.asteriskToken = asteriskToken; node.name = typeof name === "string" ? createIdentifier(name) : name; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; @@ -536,9 +536,9 @@ namespace ts { return node; } - export function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) { - if (node.name !== name || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { - return updateNode(createFunctionExpression(node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); + export function updateFunctionExpression(node: FunctionExpression, modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block) { + if (node.name !== name || node.modifiers !== modifiers || node.typeParameters !== typeParameters || node.parameters !== parameters || node.type !== type || node.body !== body) { + return updateNode(createFunctionExpression(modifiers, node.asteriskToken, name, typeParameters, parameters, type, body, /*location*/ node, node.flags), node); } return node; } @@ -1735,6 +1735,7 @@ namespace ts { export function createAwaiterHelper(externalHelpersModuleName: Identifier | undefined, hasLexicalArguments: boolean, promiseConstructor: EntityName | Expression, body: Block) { const generatorFunc = createFunctionExpression( + /*modifiers*/ undefined, createNode(SyntaxKind.AsteriskToken), /*name*/ undefined, /*typeParameters*/ undefined, @@ -1908,6 +1909,7 @@ namespace ts { createCall( createParen( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2089,6 +2091,7 @@ namespace ts { const properties: ObjectLiteralElementLike[] = []; if (getAccessor) { const getterFunction = createFunctionExpression( + getAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2104,6 +2107,7 @@ namespace ts { if (setAccessor) { const setterFunction = createFunctionExpression( + setAccessor.modifiers, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2170,6 +2174,7 @@ namespace ts { createMemberAccessForPropertyName(receiver, method.name, /*location*/ method.name), setOriginalNode( createFunctionExpression( + method.modifiers, method.asteriskToken, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2909,4 +2914,4 @@ namespace ts { function tryGetModuleNameFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration, host: EmitHost, resolver: EmitResolver, compilerOptions: CompilerOptions) { return tryGetModuleNameFromFile(resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions); } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 7555c3bdd77..1d3c189110a 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -202,6 +202,7 @@ namespace ts { } const func = createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, node.name, /*typeParameters*/ undefined, @@ -211,8 +212,6 @@ namespace ts { /*location*/ node ); - node.modifiers = visitNodes(node.modifiers, visitor, isModifier); - setOriginalNode(func, node); return func; diff --git a/src/compiler/transformers/es6.ts b/src/compiler/transformers/es6.ts index 7fb0594a6cc..ba5f8a3fb77 100644 --- a/src/compiler/transformers/es6.ts +++ b/src/compiler/transformers/es6.ts @@ -681,6 +681,7 @@ namespace ts { const extendsClauseElement = getClassExtendsHeritageClauseElement(node); const classFunction = createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -1509,6 +1510,7 @@ namespace ts { const expression = setOriginalNode( createFunctionExpression( + /*modifiers*/ undefined, node.asteriskToken, name, /*typeParameters*/ undefined, @@ -2240,6 +2242,7 @@ namespace ts { /*type*/ undefined, setEmitFlags( createFunctionExpression( + /*modifiers*/ undefined, isAsyncBlockContainingAwait ? createToken(SyntaxKind.AsteriskToken) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -3256,4 +3259,4 @@ namespace ts { return isIdentifier(expression) && expression === parameter.name; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/generators.ts b/src/compiler/transformers/generators.ts index f3a47f037ca..88788022ef8 100644 --- a/src/compiler/transformers/generators.ts +++ b/src/compiler/transformers/generators.ts @@ -496,6 +496,7 @@ namespace ts { if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { node = setOriginalNode( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, @@ -2591,6 +2592,7 @@ namespace ts { createThis(), setEmitFlags( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -3080,4 +3082,4 @@ namespace ts { ); } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 3877169e6c3..9051f375bf9 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -179,6 +179,7 @@ namespace ts { // // function (require, exports, module1, module2) ... createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, diff --git a/src/compiler/transformers/module/system.ts b/src/compiler/transformers/module/system.ts index d4ee4f36b87..e7b441f4c9b 100644 --- a/src/compiler/transformers/module/system.ts +++ b/src/compiler/transformers/module/system.ts @@ -110,6 +110,7 @@ namespace ts { const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions); const dependencies = createArrayLiteral(map(dependencyGroups, getNameOfDependencyGroup)); const body = createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -244,6 +245,7 @@ namespace ts { ), createPropertyAssignment("execute", createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -430,6 +432,7 @@ namespace ts { setters.push( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 61f40e1ed80..77ab6a6ca0e 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -2197,6 +2197,7 @@ namespace ts { } const func = createFunctionExpression( + visitNodes(node.modifiers, visitor, isModifier), node.asteriskToken, node.name, /*typeParameters*/ undefined, @@ -2477,6 +2478,7 @@ namespace ts { const enumStatement = createStatement( createCall( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, @@ -2748,6 +2750,7 @@ namespace ts { const moduleStatement = createStatement( createCall( createFunctionExpression( + /*modifiers*/ undefined, /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, diff --git a/src/compiler/visitor.ts b/src/compiler/visitor.ts index e147eda8535..6910f5aac4d 100644 --- a/src/compiler/visitor.ts +++ b/src/compiler/visitor.ts @@ -807,6 +807,7 @@ namespace ts { case SyntaxKind.FunctionExpression: return updateFunctionExpression(node, + visitNodes((node).modifiers, visitor, isModifier), visitNode((node).name, visitor, isPropertyName), visitNodes((node).typeParameters, visitor, isTypeParameter), (context.startLexicalEnvironment(), visitNodes((node).parameters, visitor, isParameter)), @@ -1357,4 +1358,4 @@ namespace ts { } } } -} \ No newline at end of file +} From c5ddf27dc68d6dc49a3d6f01e1db35fa6b455b79 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 12:04:36 +0200 Subject: [PATCH 42/74] Remove constant substitution from ES2017 transformer --- src/compiler/transformers/es2017.ts | 32 +---------------------------- 1 file changed, 1 insertion(+), 31 deletions(-) diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 1d3c189110a..f9e8b539c6a 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -395,7 +395,7 @@ namespace ts { } } - return substituteConstantValue(node); + return node; } function substituteElementAccessExpression(node: ElementAccessExpression) { @@ -410,39 +410,9 @@ namespace ts { } } - return substituteConstantValue(node); - } - - function substituteConstantValue(node: PropertyAccessExpression | ElementAccessExpression): LeftHandSideExpression { - const constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - const substitute = createLiteral(constantValue); - setSourceMapRange(substitute, node); - setCommentRange(substitute, node); - if (!compilerOptions.removeComments) { - const propertyName = isPropertyAccessExpression(node) - ? declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - substitute.trailingComment = ` ${propertyName} `; - } - - setConstantValue(node, constantValue); - return substitute; - } - return node; } - function tryGetConstEnumValue(node: Node): number { - if (compilerOptions.isolatedModules) { - return undefined; - } - - return isPropertyAccessExpression(node) || isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } - function substituteCallExpression(node: CallExpression): Expression { const expression = node.expression; if (isSuperProperty(expression)) { From b871b5353c8a9ca6dedd6bc84706fd75ed86bae4 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Thu, 13 Oct 2016 13:32:00 +0200 Subject: [PATCH 43/74] Favor use of ES2015 instead of ES6 --- Jakefile.js | 8 +-- src/compiler/binder.ts | 62 +++++++++---------- src/compiler/checker.ts | 42 ++++++------- src/compiler/core.ts | 2 +- src/compiler/emitter.ts | 4 +- src/compiler/factory.ts | 2 +- src/compiler/program.ts | 4 +- src/compiler/transformer.ts | 10 +-- .../transformers/{es6.ts => es2015.ts} | 26 ++++---- src/compiler/transformers/es2017.ts | 4 +- .../transformers/module/{es6.ts => es2015.ts} | 4 +- src/compiler/transformers/module/module.ts | 2 +- src/compiler/transformers/ts.ts | 6 +- src/compiler/tsconfig.json | 4 +- src/compiler/types.ts | 10 +-- src/compiler/utilities.ts | 6 +- src/harness/harness.ts | 2 +- src/harness/tsconfig.json | 4 +- src/harness/unittests/moduleResolution.ts | 2 +- src/services/tsconfig.json | 4 +- src/services/utilities.ts | 2 +- 21 files changed, 105 insertions(+), 105 deletions(-) rename src/compiler/transformers/{es6.ts => es2015.ts} (97%) rename src/compiler/transformers/module/{es6.ts => es2015.ts} (96%) diff --git a/Jakefile.js b/Jakefile.js index 8d46368653c..6f86ef35b09 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -70,14 +70,14 @@ var compilerSources = [ "visitor.ts", "transformers/destructuring.ts", "transformers/ts.ts", - "transformers/module/es6.ts", + "transformers/module/es2015.ts", "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", "transformers/es2017.ts", "transformers/es2016.ts", + "transformers/es2015.ts", "transformers/generators.ts", - "transformers/es6.ts", "transformer.ts", "sourcemap.ts", "comments.ts", @@ -105,14 +105,14 @@ var servicesSources = [ "visitor.ts", "transformers/destructuring.ts", "transformers/ts.ts", - "transformers/module/es6.ts", + "transformers/module/es2015.ts", "transformers/module/system.ts", "transformers/module/module.ts", "transformers/jsx.ts", "transformers/es2017.ts", "transformers/es2016.ts", + "transformers/es2015.ts", "transformers/generators.ts", - "transformers/es6.ts", "transformer.ts", "sourcemap.ts", "comments.ts", diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 3f5db2ae7c5..970e481faaa 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1636,7 +1636,7 @@ namespace ts { } function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) { - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { // Report error if function is not top level function declaration if (blockScopeContainer.kind !== SyntaxKind.SourceFile && blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration && @@ -2376,7 +2376,7 @@ namespace ts { || isSuperOrSuperProperty(expression, expressionKind)) { // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 // node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2407,7 +2407,7 @@ namespace ts { && (leftKind === SyntaxKind.ObjectLiteralExpression || leftKind === SyntaxKind.ArrayLiteralExpression)) { // Destructuring assignments are ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.DestructuringAssignment; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.DestructuringAssignment; } else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken || operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) { @@ -2445,7 +2445,7 @@ namespace ts { // If a parameter has an initializer, a binding pattern or a dotDotDot token, then // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsDefaultValueAssignments; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2486,7 +2486,7 @@ namespace ts { } else { // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | TransformFlags.AssertES6; + transformFlags = subtreeFlags | TransformFlags.AssertES2015; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. @@ -2509,7 +2509,7 @@ namespace ts { function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) { // A ClassExpression is ES6 syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. @@ -2533,7 +2533,7 @@ namespace ts { switch (node.token) { case SyntaxKind.ExtendsKeyword: // An `extends` HeritageClause is ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.ImplementsKeyword: @@ -2553,7 +2553,7 @@ namespace ts { function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the // extends clause of a class. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; // If an ExpressionWithTypeArguments contains type arguments, then it // is TypeScript syntax. @@ -2580,7 +2580,7 @@ namespace ts { function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) { // A MethodDeclaration is ES6 syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; const modifierFlags = getModifierFlags(node); const body = node.body; const typeParameters = node.typeParameters; @@ -2656,7 +2656,7 @@ namespace ts { // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2015; } // An async function declaration is ES2017 syntax. @@ -2667,8 +2667,8 @@ namespace ts { // If a FunctionDeclaration's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES6; + if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES2015; } // If a FunctionDeclaration is generator function and is the body of a @@ -2698,8 +2698,8 @@ namespace ts { // If a FunctionExpression's subtree has marked the container as needing to capture the // lexical this, or the function contains parameters with initializers, then this node is // ES6 syntax. - if (subtreeFlags & TransformFlags.ES6FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES6; + if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { + transformFlags |= TransformFlags.AssertES2015; } // If a FunctionExpression is generator function and is the body of a @@ -2717,7 +2717,7 @@ namespace ts { function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. - let transformFlags = subtreeFlags | TransformFlags.AssertES6; + let transformFlags = subtreeFlags | TransformFlags.AssertES2015; const modifierFlags = getModifierFlags(node); // An async arrow function is ES2017 syntax. @@ -2755,7 +2755,7 @@ namespace ts { // A VariableDeclaration with a binding pattern is ES6 syntax. if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2776,11 +2776,11 @@ namespace ts { // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript; } if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } } @@ -2794,7 +2794,7 @@ namespace ts { // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding && isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2820,7 +2820,7 @@ namespace ts { // then we treat the statement as ES6 so that we can indicate that we do not // need to hold on to the right-hand side. if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2843,12 +2843,12 @@ namespace ts { let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; if (subtreeFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. if (node.flags & NodeFlags.BlockScoped) { - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBlockScopedBinding; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBlockScopedBinding; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; @@ -2897,7 +2897,7 @@ namespace ts { case SyntaxKind.ExportKeyword: // This node is both ES6 and TypeScript syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.AssertTypeScript; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript; break; case SyntaxKind.DefaultKeyword: @@ -2910,12 +2910,12 @@ namespace ts { case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.ForOfStatement: // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.YieldExpression: // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsYield; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsYield; break; case SyntaxKind.AnyKeyword: @@ -2976,7 +2976,7 @@ namespace ts { case SyntaxKind.SuperKeyword: // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; break; case SyntaxKind.ThisKeyword: @@ -2987,7 +2987,7 @@ namespace ts { case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; + transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; break; case SyntaxKind.Decorator: @@ -3000,7 +3000,7 @@ namespace ts { if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { @@ -3017,7 +3017,7 @@ namespace ts { if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { // If the this node contains a SpreadElementExpression, then it is an ES6 // node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; @@ -3028,14 +3028,14 @@ namespace ts { case SyntaxKind.ForInStatement: // A loop containing a block scoped binding *may* need to be transformed from ES6. if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; case SyntaxKind.SourceFile: if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) { - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } break; diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 0b5c3963079..cecf2964f3c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3189,7 +3189,7 @@ namespace ts { const elements = pattern.elements; const lastElement = lastOrUndefined(elements); if (elements.length === 0 || (!isOmittedExpression(lastElement) && lastElement.dotDotDotToken)) { - return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType; + return languageVersion >= ScriptTarget.ES2015 ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. const elementTypes = map(elements, e => isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors)); @@ -9059,7 +9059,7 @@ namespace ts { // can explicitly bound arguments objects if (symbol === argumentsSymbol) { const container = getContainingFunction(node); - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { if (container.kind === SyntaxKind.ArrowFunction) { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); } @@ -9084,7 +9084,7 @@ namespace ts { // Due to the emit for class decorators, any reference to the class from inside of the class body // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind // behavior of class names in ES6. - if (languageVersion === ScriptTarget.ES6 + if (languageVersion === ScriptTarget.ES2015 && declaration.kind === SyntaxKind.ClassDeclaration && nodeIsDecorated(declaration)) { let container = getContainingClass(node); @@ -9173,7 +9173,7 @@ namespace ts { } function checkNestedBlockScopedBinding(node: Identifier, symbol: Symbol): void { - if (languageVersion >= ScriptTarget.ES6 || + if (languageVersion >= ScriptTarget.ES2015 || (symbol.flags & (SymbolFlags.BlockScopedVariable | SymbolFlags.Class)) === 0 || symbol.valueDeclaration.parent.kind === SyntaxKind.CatchClause) { return; @@ -9339,7 +9339,7 @@ namespace ts { container = getThisContainer(container, /* includeArrowFunctions */ false); // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code - needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES6); + needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES2015); } switch (container.kind) { @@ -9447,7 +9447,7 @@ namespace ts { if (!isCallExpression) { while (container && container.kind === SyntaxKind.ArrowFunction) { container = getSuperContainer(container, /*stopOnFunctions*/ true); - needToCaptureLexicalThis = languageVersion < ScriptTarget.ES6; + needToCaptureLexicalThis = languageVersion < ScriptTarget.ES2015; } } @@ -9561,7 +9561,7 @@ namespace ts { } if (container.parent.kind === SyntaxKind.ObjectLiteralExpression) { - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher); return unknownType; } @@ -9929,7 +9929,7 @@ namespace ts { const index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) - || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); + || (languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); } return undefined; } @@ -10162,7 +10162,7 @@ namespace ts { // if there is no index type / iterated type. const restArrayType = checkExpression((e).expression, contextualMapper); const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || - (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); + (languageVersion >= ScriptTarget.ES2015 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } @@ -10909,7 +10909,7 @@ namespace ts { // - In a static member function or static member accessor // where this references the constructor function object of a derived class, // a super property access is permitted and must specify a public static member function of the base class. - if (languageVersion < ScriptTarget.ES6 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { + if (languageVersion < ScriptTarget.ES2015 && getDeclarationKindFromSymbol(prop) !== SyntaxKind.MethodDeclaration) { // `prop` refers to a *property* declared in the super class // rather than a *method*, so it does not satisfy the above criteria. @@ -14228,7 +14228,7 @@ namespace ts { } if (node.type) { - if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) { + if (languageVersion >= ScriptTarget.ES2015 && isSyntacticallyValidGenerator(node)) { const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); @@ -15189,7 +15189,7 @@ namespace ts { * callable `then` signature. */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { const returnType = getTypeFromTypeNode(node.type); return checkCorrectPromiseType(returnType, node.type, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type); } @@ -15722,7 +15722,7 @@ namespace ts { function checkCollisionWithRequireExportsInGeneratedCode(node: Node, name: Identifier) { // No need to check for require or exports for ES6 modules and later - if (modulekind >= ModuleKind.ES6) { + if (modulekind >= ModuleKind.ES2015) { return; } @@ -16214,7 +16214,7 @@ namespace ts { if (isTypeAny(inputType)) { return inputType; } - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { return checkElementTypeOfIterable(inputType, errorNode); } if (allowStringInput) { @@ -16392,7 +16392,7 @@ namespace ts { * 2. Some constituent is a string and target is less than ES5 (because in ES3 string is not indexable). */ function checkElementTypeOfArrayOrString(arrayOrStringType: Type, errorNode: Node): Type { - Debug.assert(languageVersion < ScriptTarget.ES6); + Debug.assert(languageVersion < ScriptTarget.ES2015); // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. @@ -17700,7 +17700,7 @@ namespace ts { } } else { - if (modulekind === ModuleKind.ES6 && !isInAmbientContext(node)) { + if (modulekind === ModuleKind.ES2015 && !isInAmbientContext(node)) { // Import equals declaration is deprecated in es6 or above grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead); } @@ -17788,7 +17788,7 @@ namespace ts { checkExternalModuleExports(container); if (node.isExportEquals && !isInAmbientContext(node)) { - if (modulekind === ModuleKind.ES6) { + if (modulekind === ModuleKind.ES2015) { // export assignment is not supported in es6 modules grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_2015_modules_Consider_using_export_default_or_another_module_format_instead); } @@ -19296,7 +19296,7 @@ namespace ts { getGlobalTemplateStringsArrayType = memoize(() => getGlobalType("TemplateStringsArray")); - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { getGlobalESSymbolType = memoize(() => getGlobalType("Symbol")); getGlobalIterableType = memoize(() => getGlobalType("Iterable", /*arity*/ 1)); getGlobalIteratorType = memoize(() => getGlobalType("Iterator", /*arity*/ 1)); @@ -19329,7 +19329,7 @@ namespace ts { // If we found the module, report errors if it does not have the necessary exports. if (helpersModule) { const exports = helpersModule.exports; - if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES6) { + if (requestedExternalEmitHelpers & NodeFlags.HasClassExtends && languageVersion < ScriptTarget.ES2015) { verifyHelperSymbol(exports, "__extends", SymbolFlags.Value); } if (requestedExternalEmitHelpers & NodeFlags.HasJsxSpreadAttributes && compilerOptions.jsx !== JsxEmit.Preserve) { @@ -19346,7 +19346,7 @@ namespace ts { } if (requestedExternalEmitHelpers & NodeFlags.HasAsyncFunctions) { verifyHelperSymbol(exports, "__awaiter", SymbolFlags.Value); - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { verifyHelperSymbol(exports, "__generator", SymbolFlags.Value); } } @@ -19923,7 +19923,7 @@ namespace ts { if (!node.body) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator); } - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { return grammarErrorOnNode(node.asteriskToken, Diagnostics.Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher); } } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 3f2cc619cb3..3f60ec62c2b 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1191,7 +1191,7 @@ namespace ts { export function getEmitModuleKind(compilerOptions: CompilerOptions) { return typeof compilerOptions.module === "number" ? compilerOptions.module : - getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.CommonJS; + getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2015 ? ModuleKind.ES2015 : ModuleKind.CommonJS; } /* @internal */ diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index a3f69e2fd4b..734fe2778e5 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -2165,7 +2165,7 @@ const _super = (function (geti, seti) { // Only Emit __extends function when target ES5. // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) { + if ((languageVersion < ScriptTarget.ES2015) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) { writeLines(extendsHelper); extendsEmitted = true; helpersEmitted = true; @@ -2197,7 +2197,7 @@ const _super = (function (geti, seti) { // For target ES2017 and above, we can emit async/await as is. if ((languageVersion < ScriptTarget.ES2017) && (!awaiterEmitted && node.flags & NodeFlags.HasAsyncFunctions)) { writeLines(awaiterHelper); - if (languageVersion < ScriptTarget.ES6) { + if (languageVersion < ScriptTarget.ES2015) { writeLines(generatorHelper); } diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 519269ccfd0..57007619c62 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -1985,7 +1985,7 @@ namespace ts { } else if (callee.kind === SyntaxKind.SuperKeyword) { thisArg = createThis(); - target = languageVersion < ScriptTarget.ES6 ? createIdentifier("_super", /*location*/ callee) : callee; + target = languageVersion < ScriptTarget.ES2015 ? createIdentifier("_super", /*location*/ callee) : callee; } else { switch (callee.kind) { diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 5d46038b2b1..dfe65fc0860 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1478,7 +1478,7 @@ namespace ts { const firstNonAmbientExternalModuleSourceFile = forEach(files, f => isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (options.isolatedModules) { - if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES6) { + if (options.module === ModuleKind.None && languageVersion < ScriptTarget.ES2015) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } @@ -1488,7 +1488,7 @@ namespace ts { programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } - else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && options.module === ModuleKind.None) { + else if (firstNonAmbientExternalModuleSourceFile && languageVersion < ScriptTarget.ES2015 && options.module === ModuleKind.None) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet const span = getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none)); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 55b83ea669d..fc656e08bf9 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -3,16 +3,16 @@ /// /// /// -/// +/// /// /// /// -/// +/// /* @internal */ namespace ts { const moduleTransformerMap = createMap({ - [ModuleKind.ES6]: transformES6Module, + [ModuleKind.ES2015]: transformES2015Module, [ModuleKind.System]: transformSystemModule, [ModuleKind.AMD]: transformModule, [ModuleKind.CommonJS]: transformModule, @@ -124,8 +124,8 @@ namespace ts { transformers.push(transformES2016); } - if (languageVersion < ScriptTarget.ES6) { - transformers.push(transformES6); + if (languageVersion < ScriptTarget.ES2015) { + transformers.push(transformES2015); transformers.push(transformGenerators); } diff --git a/src/compiler/transformers/es6.ts b/src/compiler/transformers/es2015.ts similarity index 97% rename from src/compiler/transformers/es6.ts rename to src/compiler/transformers/es2015.ts index ba5f8a3fb77..101c34a8199 100644 --- a/src/compiler/transformers/es6.ts +++ b/src/compiler/transformers/es2015.ts @@ -4,7 +4,7 @@ /*@internal*/ namespace ts { - const enum ES6SubstitutionFlags { + const enum ES2015SubstitutionFlags { /** Enables substitutions for captured `this` */ CapturedThis = 1 << 0, /** Enables substitutions for block-scoped bindings. */ @@ -163,7 +163,7 @@ namespace ts { ReplaceWithReturn, } - export function transformES6(context: TransformationContext) { + export function transformES2015(context: TransformationContext) { const { startLexicalEnvironment, endLexicalEnvironment, @@ -197,7 +197,7 @@ namespace ts { * They are persisted between each SourceFile transformation and should not * be reset. */ - let enabledSubstitutions: ES6SubstitutionFlags; + let enabledSubstitutions: ES2015SubstitutionFlags; return transformSourceFile; @@ -252,7 +252,7 @@ namespace ts { } function shouldCheckNode(node: Node): boolean { - return (node.transformFlags & TransformFlags.ES6) !== 0 || + return (node.transformFlags & TransformFlags.ES2015) !== 0 || node.kind === SyntaxKind.LabeledStatement || (isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatementBody(node)); } @@ -261,7 +261,7 @@ namespace ts { if (shouldCheckNode(node)) { return visitJavaScript(node); } - else if (node.transformFlags & TransformFlags.ContainsES6) { + else if (node.transformFlags & TransformFlags.ContainsES2015) { return visitEachChild(node, visitor, context); } else { @@ -3037,7 +3037,7 @@ namespace ts { function onEmitNode(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) { const savedEnclosingFunction = enclosingFunction; - if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis && isFunctionLike(node)) { + if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } @@ -3052,8 +3052,8 @@ namespace ts { * contains block-scoped bindings (e.g. `let` or `const`). */ function enableSubstitutionsForBlockScopedBindings() { - if ((enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) === 0) { - enabledSubstitutions |= ES6SubstitutionFlags.BlockScopedBindings; + if ((enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) === 0) { + enabledSubstitutions |= ES2015SubstitutionFlags.BlockScopedBindings; context.enableSubstitution(SyntaxKind.Identifier); } } @@ -3063,8 +3063,8 @@ namespace ts { * contains a captured `this`. */ function enableSubstitutionsForCapturedThis() { - if ((enabledSubstitutions & ES6SubstitutionFlags.CapturedThis) === 0) { - enabledSubstitutions |= ES6SubstitutionFlags.CapturedThis; + if ((enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis) === 0) { + enabledSubstitutions |= ES2015SubstitutionFlags.CapturedThis; context.enableSubstitution(SyntaxKind.ThisKeyword); context.enableEmitNotification(SyntaxKind.Constructor); context.enableEmitNotification(SyntaxKind.MethodDeclaration); @@ -3103,7 +3103,7 @@ namespace ts { function substituteIdentifier(node: Identifier) { // Only substitute the identifier if we have enabled substitutions for block-scoped // bindings. - if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { const original = getParseTreeNode(node, isIdentifier); if (original && isNameOfDeclarationWithCollidingName(original)) { return getGeneratedNameForNode(original); @@ -3156,7 +3156,7 @@ namespace ts { * @param node An Identifier node. */ function substituteExpressionIdentifier(node: Identifier): Identifier { - if (enabledSubstitutions & ES6SubstitutionFlags.BlockScopedBindings) { + if (enabledSubstitutions & ES2015SubstitutionFlags.BlockScopedBindings) { const declaration = resolver.getReferencedDeclarationWithCollidingName(node); if (declaration) { return getGeneratedNameForNode(declaration.name); @@ -3172,7 +3172,7 @@ namespace ts { * @param node The ThisKeyword node. */ function substituteThisKeyword(node: PrimaryExpression): PrimaryExpression { - if (enabledSubstitutions & ES6SubstitutionFlags.CapturedThis + if (enabledSubstitutions & ES2015SubstitutionFlags.CapturedThis && enclosingFunction && getEmitFlags(enclosingFunction) & EmitFlags.CapturesThis) { return createIdentifier("_this", /*location*/ node); diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index f9e8b539c6a..7800a41e147 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -263,7 +263,7 @@ namespace ts { function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody { const nodeType = node.original ? (node.original).type : node.type; - const promiseConstructor = languageVersion < ScriptTarget.ES6 ? getPromiseConstructor(nodeType) : undefined; + const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined; const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; @@ -292,7 +292,7 @@ namespace ts { // Minor optimization, emit `_super` helper to capture `super` access in an arrow. // This step isn't needed if we eventually transform this to ES5. - if (languageVersion >= ScriptTarget.ES6) { + if (languageVersion >= ScriptTarget.ES2015) { if (resolver.getNodeCheckFlags(node) & NodeCheckFlags.AsyncMethodWithSuperBinding) { enableSubstitutionForAsyncMethodsWithSuper(); setEmitFlags(block, EmitFlags.EmitAdvancedSuperHelper); diff --git a/src/compiler/transformers/module/es6.ts b/src/compiler/transformers/module/es2015.ts similarity index 96% rename from src/compiler/transformers/module/es6.ts rename to src/compiler/transformers/module/es2015.ts index 09a2890727c..b06acd2d091 100644 --- a/src/compiler/transformers/module/es6.ts +++ b/src/compiler/transformers/module/es2015.ts @@ -3,7 +3,7 @@ /*@internal*/ namespace ts { - export function transformES6Module(context: TransformationContext) { + export function transformES2015Module(context: TransformationContext) { const compilerOptions = context.getCompilerOptions(); const resolver = context.getEmitResolver(); @@ -141,4 +141,4 @@ namespace ts { return resolver.isReferencedAliasDeclaration(node) ? node : undefined; } } -} \ No newline at end of file +} diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index 9051f375bf9..989efbfd53f 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -416,7 +416,7 @@ namespace ts { ) ], /*location*/ undefined, - /*flags*/ languageVersion >= ScriptTarget.ES6 ? NodeFlags.Const : NodeFlags.None), + /*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None), /*location*/ node ) ); diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 77ab6a6ca0e..868c371e00f 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -1777,7 +1777,7 @@ namespace ts { return createIdentifier("Number"); case SyntaxKind.SymbolKeyword: - return languageVersion < ScriptTarget.ES6 + return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() : createIdentifier("Symbol"); @@ -1843,7 +1843,7 @@ namespace ts { return createIdentifier("Array"); case TypeReferenceSerializationKind.ESSymbolType: - return languageVersion < ScriptTarget.ES6 + return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() : createIdentifier("Symbol"); @@ -2592,7 +2592,7 @@ namespace ts { function isES6ExportedDeclaration(node: Node) { return isExternalModuleExport(node) - && moduleKind === ModuleKind.ES6; + && moduleKind === ModuleKind.ES2015; } /** diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index de710e74a46..da356c0b4d3 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -26,12 +26,12 @@ "transformers/jsx.ts", "transformers/es2017.ts", "transformers/es2016.ts", - "transformers/es6.ts", + "transformers/es2015.ts", "transformers/generators.ts", "transformers/destructuring.ts", "transformers/module/module.ts", "transformers/module/system.ts", - "transformers/module/es6.ts", + "transformers/module/es2015.ts", "transformer.ts", "comments.ts", "sourcemap.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index b89887cafa0..55200b29676 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3123,8 +3123,8 @@ namespace ts { ContainsES2017 = 1 << 5, ES2016 = 1 << 6, ContainsES2016 = 1 << 7, - ES6 = 1 << 8, - ContainsES6 = 1 << 9, + ES2015 = 1 << 8, + ContainsES2015 = 1 << 9, DestructuringAssignment = 1 << 10, Generator = 1 << 11, ContainsGenerator = 1 << 12, @@ -3153,13 +3153,13 @@ namespace ts { AssertJsx = Jsx | ContainsJsx, AssertES2017 = ES2017 | ContainsES2017, AssertES2016 = ES2016 | ContainsES2016, - AssertES6 = ES6 | ContainsES6, + AssertES2015 = ES2015 | ContainsES2015, AssertGenerator = Generator | ContainsGenerator, // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES6 | DestructuringAssignment | Generator | HasComputedFlags, + NodeExcludes = TypeScript | Jsx | ES2017 | ES2016 | ES2015 | DestructuringAssignment | Generator | HasComputedFlags, ArrowFunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, FunctionExcludes = NodeExcludes | ContainsDecorators | ContainsDefaultValueAssignments | ContainsCapturedLexicalThis | ContainsLexicalThis | ContainsParameterPropertyAssignments | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, ConstructorExcludes = NodeExcludes | ContainsDefaultValueAssignments | ContainsLexicalThis | ContainsCapturedLexicalThis | ContainsBlockScopedBinding | ContainsYield | ContainsHoistedDeclarationOrCompletion, @@ -3175,7 +3175,7 @@ namespace ts { // Masks // - Additional bitmasks TypeScriptClassSyntaxMask = ContainsParameterPropertyAssignments | ContainsPropertyInitializer | ContainsDecorators, - ES6FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, + ES2015FunctionSyntaxMask = ContainsCapturedLexicalThis | ContainsDefaultValueAssignments, } /* @internal */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 92ce6ecc6a4..e10ab6a8add 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -337,7 +337,7 @@ namespace ts { export function getLiteralText(node: LiteralLikeNode, sourceFile: SourceFile, languageVersion: ScriptTarget) { // Any template literal or string literal with an extended escape // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < ScriptTarget.ES6 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { + if (languageVersion < ScriptTarget.ES2015 && (isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { return getQuotedEscapedLiteralText('"', node.text, '"'); } @@ -345,7 +345,7 @@ namespace ts { // the node's parent reference, then simply get the text as it was originally written. if (!nodeIsSynthesized(node) && node.parent) { const text = getSourceTextOfNodeFromSourceFile(sourceFile, node); - if (languageVersion < ScriptTarget.ES6 && isBinaryOrOctalIntegerLiteral(node, text)) { + if (languageVersion < ScriptTarget.ES2015 && isBinaryOrOctalIntegerLiteral(node, text)) { return node.text; } return text; @@ -4146,7 +4146,7 @@ namespace ts { return "lib.es2017.d.ts"; case ScriptTarget.ES2016: return "lib.es2016.d.ts"; - case ScriptTarget.ES6: + case ScriptTarget.ES2015: return "lib.es2015.d.ts"; default: diff --git a/src/harness/harness.ts b/src/harness/harness.ts index c50f33a74c3..3b45d6d61e5 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -946,7 +946,7 @@ namespace Harness { return "lib.es2017.d.ts"; case ts.ScriptTarget.ES2016: return "lib.es2016.d.ts"; - case ts.ScriptTarget.ES6: + case ts.ScriptTarget.ES2015: return es2015DefaultLibFileName; default: diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index c8b90645ce2..5d7a81d1a74 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -28,12 +28,12 @@ "../compiler/transformers/jsx.ts", "../compiler/transformers/es2017.ts", "../compiler/transformers/es2016.ts", - "../compiler/transformers/es6.ts", + "../compiler/transformers/es2015.ts", "../compiler/transformers/generators.ts", "../compiler/transformers/destructuring.ts", "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", - "../compiler/transformers/module/es6.ts", + "../compiler/transformers/module/es2015.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", diff --git a/src/harness/unittests/moduleResolution.ts b/src/harness/unittests/moduleResolution.ts index 3e1ac171216..b2f7d0c224d 100644 --- a/src/harness/unittests/moduleResolution.ts +++ b/src/harness/unittests/moduleResolution.ts @@ -1017,7 +1017,7 @@ import b = require("./moduleB"); const files = [f1, f2, f3, f4]; const names = map(files, f => f.name); - const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES6)), f => f.fileName); + const sourceFiles = arrayToMap(map(files, f => createSourceFile(f.name, f.content, ScriptTarget.ES2015)), f => f.fileName); const compilerHost: CompilerHost = { fileExists : fileName => fileName in sourceFiles, getSourceFile: fileName => sourceFiles[fileName], diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 45e3c9036e0..c9428d9a082 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -27,12 +27,12 @@ "../compiler/transformers/jsx.ts", "../compiler/transformers/es2017.ts", "../compiler/transformers/es2016.ts", - "../compiler/transformers/es6.ts", + "../compiler/transformers/es2015.ts", "../compiler/transformers/generators.ts", "../compiler/transformers/destructuring.ts", "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", - "../compiler/transformers/module/es6.ts", + "../compiler/transformers/module/es2015.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 829048fc081..e61906b4f09 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1339,7 +1339,7 @@ namespace ts { const options: TranspileOptions = { fileName: "config.js", compilerOptions: { - target: ScriptTarget.ES6, + target: ScriptTarget.ES2015, removeComments: true }, reportDiagnostics: true From 7dd64d3ea26c9642ffa8e1f82bd0568b664403ae Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 06:29:34 -0700 Subject: [PATCH 44/74] Properly narrow union types containing string and number --- src/compiler/checker.ts | 32 ++++++++++++++++++++++++-------- src/compiler/types.ts | 2 +- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 6555710137a..dffe4244e39 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8461,6 +8461,28 @@ namespace ts { return f(type) ? type : neverType; } + function mapType(type: Type, f: (t: Type) => Type): Type { + return type.flags & TypeFlags.Union ? getUnionType(map((type).types, f)) : f(type); + } + + function extractTypesOfKind(type: Type, kind: TypeFlags) { + return filterType(type, t => (t.flags & kind) !== 0); + } + + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives: Type, typeWithLiterals: Type) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.StringLiteral) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, TypeFlags.NumberLiteral)) { + return mapType(typeWithPrimitives, t => + t.flags & TypeFlags.String ? extractTypesOfKind(typeWithLiterals, TypeFlags.String | TypeFlags.StringLiteral) : + t.flags & TypeFlags.Number ? extractTypesOfKind(typeWithLiterals, TypeFlags.Number | TypeFlags.NumberLiteral) : + t); + } + return typeWithPrimitives; + } + function isIncomplete(flowType: FlowType) { return flowType.flags === 0; } @@ -8791,16 +8813,12 @@ namespace ts { assumeTrue ? TypeFacts.EQUndefined : TypeFacts.NEUndefined; return getTypeWithFacts(type, facts); } - if (type.flags & TypeFlags.String && isTypeOfKind(valueType, TypeFlags.StringLiteral) || - type.flags & TypeFlags.Number && isTypeOfKind(valueType, TypeFlags.NumberLiteral)) { - return assumeTrue? valueType : type; - } if (type.flags & TypeFlags.NotUnionOrUnit) { return type; } if (assumeTrue) { const narrowedType = filterType(type, t => areTypesComparable(t, valueType)); - return narrowedType.flags & TypeFlags.Never ? type : narrowedType; + return narrowedType.flags & TypeFlags.Never ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { const regularType = getRegularTypeOfLiteralType(valueType); @@ -8849,9 +8867,7 @@ namespace ts { const discriminantType = getUnionType(clauseTypes); const caseType = discriminantType.flags & TypeFlags.Never ? neverType : - type.flags & TypeFlags.String && isTypeOfKind(discriminantType, TypeFlags.StringLiteral) ? discriminantType : - type.flags & TypeFlags.Number && isTypeOfKind(discriminantType, TypeFlags.NumberLiteral) ? discriminantType : - filterType(type, t => isTypeComparableTo(discriminantType, t)); + replacePrimitivesWithLiterals(filterType(type, t => isTypeComparableTo(discriminantType, t)), discriminantType); if (!hasDefaultClause) { return caseType; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 638504e613f..ba11b35459b 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2644,7 +2644,7 @@ namespace ts { // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol, - NotUnionOrUnit = Any | String | Number | ESSymbol | ObjectType, + NotUnionOrUnit = Any | ESSymbol | ObjectType, /* @internal */ RequiresWidening = ContainsWideningType | ContainsObjectLiteral, /* @internal */ From 57a9a6344a64f5a5a15fb1b98b2cef4acdcc620b Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 06:31:28 -0700 Subject: [PATCH 45/74] Accept new baselines --- .../reference/declFileTypeAnnotationStringLiteral.types | 2 +- tests/baselines/reference/literalTypes1.types | 8 ++++---- tests/baselines/reference/sourceMapValidationIfElse.types | 6 +++--- tests/baselines/reference/sourceMapValidationSwitch.types | 8 ++++---- tests/baselines/reference/sourceMapValidationWhile.types | 4 ++-- .../reference/stringLiteralTypesInUnionTypes02.types | 6 +++--- .../baselines/reference/throwInEnclosingStatements.types | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types b/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types index 6d9c17b4ab9..b1a85f3fc30 100644 --- a/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types +++ b/tests/baselines/reference/declFileTypeAnnotationStringLiteral.types @@ -23,7 +23,7 @@ function foo(a: string): string | number { return a.length; >a.length : number ->a : string +>a : "hello" >length : number } diff --git a/tests/baselines/reference/literalTypes1.types b/tests/baselines/reference/literalTypes1.types index faff485d45a..1baaad3ff88 100644 --- a/tests/baselines/reference/literalTypes1.types +++ b/tests/baselines/reference/literalTypes1.types @@ -129,7 +129,7 @@ function f4(x: 0 | 1 | true | string) { >"def" : "def" x; ->x : string +>x : "abc" | "def" break; case null: @@ -163,7 +163,7 @@ function f5(x: string | number | boolean) { >"abc" : "abc" x; ->x : string +>x : "abc" break; case 0: @@ -173,7 +173,7 @@ function f5(x: string | number | boolean) { >1 : 1 x; ->x : number +>x : 0 | 1 break; case true: @@ -190,7 +190,7 @@ function f5(x: string | number | boolean) { >123 : 123 x; ->x : string | number +>x : "hello" | 123 break; default: diff --git a/tests/baselines/reference/sourceMapValidationIfElse.types b/tests/baselines/reference/sourceMapValidationIfElse.types index b4a76d55647..87103b792e7 100644 --- a/tests/baselines/reference/sourceMapValidationIfElse.types +++ b/tests/baselines/reference/sourceMapValidationIfElse.types @@ -10,7 +10,7 @@ if (i == 10) { i++; >i++ : number ->i : number +>i : 10 } else { @@ -22,7 +22,7 @@ if (i == 10) { i++; >i++ : number ->i : number +>i : 10 } else if (i == 20) { >i == 20 : boolean @@ -31,7 +31,7 @@ else if (i == 20) { i--; >i-- : number ->i : number +>i : 20 } else if (i == 30) { >i == 30 : boolean diff --git a/tests/baselines/reference/sourceMapValidationSwitch.types b/tests/baselines/reference/sourceMapValidationSwitch.types index 9df86ee2132..359cabbfabe 100644 --- a/tests/baselines/reference/sourceMapValidationSwitch.types +++ b/tests/baselines/reference/sourceMapValidationSwitch.types @@ -11,7 +11,7 @@ switch (x) { x++; >x++ : number ->x : number +>x : 5 break; case 10: @@ -19,7 +19,7 @@ switch (x) { { x--; >x-- : number ->x : number +>x : 10 break; } @@ -39,7 +39,7 @@ switch (x) x++; >x++ : number ->x : number +>x : 5 break; case 10: @@ -47,7 +47,7 @@ switch (x) { x--; >x-- : number ->x : number +>x : 10 break; } diff --git a/tests/baselines/reference/sourceMapValidationWhile.types b/tests/baselines/reference/sourceMapValidationWhile.types index 71b50d86736..8769d98ef25 100644 --- a/tests/baselines/reference/sourceMapValidationWhile.types +++ b/tests/baselines/reference/sourceMapValidationWhile.types @@ -10,7 +10,7 @@ while (a == 10) { a++; >a++ : number ->a : number +>a : 10 } while (a == 10) >a == 10 : boolean @@ -19,5 +19,5 @@ while (a == 10) { a++; >a++ : number ->a : number +>a : 10 } diff --git a/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types b/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types index 0be891ade44..85378108298 100644 --- a/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types +++ b/tests/baselines/reference/stringLiteralTypesInUnionTypes02.types @@ -19,7 +19,7 @@ if (x === "foo") { let a = x; >a : string ->x : string +>x : "foo" } else if (x !== "bar") { >x !== "bar" : boolean @@ -35,7 +35,7 @@ else if (x !== "bar") { else { let c = x; >c : string ->x : string +>x : "bar" let d = y; >d : string @@ -43,7 +43,7 @@ else { let e: (typeof x) | (typeof y) = c || d; >e : string ->x : string +>x : "bar" >y : string >c || d : string >c : string diff --git a/tests/baselines/reference/throwInEnclosingStatements.types b/tests/baselines/reference/throwInEnclosingStatements.types index 4955b9243ae..2d99ac435ae 100644 --- a/tests/baselines/reference/throwInEnclosingStatements.types +++ b/tests/baselines/reference/throwInEnclosingStatements.types @@ -25,7 +25,7 @@ switch (y) { >'a' : "a" throw y; ->y : string +>y : "a" default: throw y; From 8bcb22c56d389ece0d1997d084ee50c7ac4d8b42 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 06:40:16 -0700 Subject: [PATCH 46/74] Add tests --- tests/baselines/reference/literalTypes3.js | 125 +++++++++++++ .../baselines/reference/literalTypes3.symbols | 137 ++++++++++++++ tests/baselines/reference/literalTypes3.types | 177 ++++++++++++++++++ .../types/literal/literalTypes3.ts | 66 +++++++ 4 files changed, 505 insertions(+) create mode 100644 tests/baselines/reference/literalTypes3.js create mode 100644 tests/baselines/reference/literalTypes3.symbols create mode 100644 tests/baselines/reference/literalTypes3.types create mode 100644 tests/cases/conformance/types/literal/literalTypes3.ts diff --git a/tests/baselines/reference/literalTypes3.js b/tests/baselines/reference/literalTypes3.js new file mode 100644 index 00000000000..1989bb1d5a1 --- /dev/null +++ b/tests/baselines/reference/literalTypes3.js @@ -0,0 +1,125 @@ +//// [literalTypes3.ts] + +function f1(s: string) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} + +function f2(s: string) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} + +function f3(s: string) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} + +function f4(x: number) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} + +function f5(x: number, y: 1 | 2) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} + +function f6(x: number, y: 1 | 2) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} + +//// [literalTypes3.js] +function f1(s) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} +function f2(s) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} +function f3(s) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} +function f4(x) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} +function f5(x, y) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} +function f6(x, y) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} +function f7(x, y) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} +function f8(x) { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} diff --git a/tests/baselines/reference/literalTypes3.symbols b/tests/baselines/reference/literalTypes3.symbols new file mode 100644 index 00000000000..6cc7ab007e6 --- /dev/null +++ b/tests/baselines/reference/literalTypes3.symbols @@ -0,0 +1,137 @@ +=== tests/cases/conformance/types/literal/literalTypes3.ts === + +function f1(s: string) { +>f1 : Symbol(f1, Decl(literalTypes3.ts, 0, 0)) +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + if (s === "foo") { +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + s; // "foo" +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + } + if (s === "foo" || s === "bar") { +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + + s; // "foo" | "bar" +>s : Symbol(s, Decl(literalTypes3.ts, 1, 12)) + } +} + +function f2(s: string) { +>f2 : Symbol(f2, Decl(literalTypes3.ts, 8, 1)) +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + switch (s) { +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + case "foo": + case "bar": + s; // "foo" | "bar" +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + case "baz": + s; // "foo" | "bar" | "baz" +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + + break; + default: + s; // string +>s : Symbol(s, Decl(literalTypes3.ts, 10, 12)) + } +} + +function f3(s: string) { +>f3 : Symbol(f3, Decl(literalTypes3.ts, 21, 1)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) + + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>s : Symbol(s, Decl(literalTypes3.ts, 23, 12)) +>undefined : Symbol(undefined) +} + +function f4(x: number) { +>f4 : Symbol(f4, Decl(literalTypes3.ts, 25, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + + if (x === 1 || x === 2) { +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + + return x; // 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 27, 12)) + } + throw new Error(); +>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --)) +} + +function f5(x: number, y: 1 | 2) { +>f5 : Symbol(f5, Decl(literalTypes3.ts, 32, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 34, 22)) + + if (x === 0 || x === y) { +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 34, 22)) + + x; // 0 | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 34, 12)) + } +} + +function f6(x: number, y: 1 | 2) { +>f6 : Symbol(f6, Decl(literalTypes3.ts, 38, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 40, 22)) + + if (y === x || 0 === x) { +>y : Symbol(y, Decl(literalTypes3.ts, 40, 22)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) + + x; // 0 | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 40, 12)) + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { +>f7 : Symbol(f7, Decl(literalTypes3.ts, 44, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 46, 38)) + + if (x === y) { +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) +>y : Symbol(y, Decl(literalTypes3.ts, 46, 38)) + + x; // "foo" | "bar" | 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 46, 12)) + } +} + +function f8(x: number | "foo" | "bar") { +>f8 : Symbol(f8, Decl(literalTypes3.ts, 50, 1)) +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + switch (x) { +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + case 1: + case 2: + x; // 1 | 2 +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + break; + case "foo": + x; // "foo" +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + + break; + default: + x; // number | "bar" +>x : Symbol(x, Decl(literalTypes3.ts, 52, 12)) + } +} diff --git a/tests/baselines/reference/literalTypes3.types b/tests/baselines/reference/literalTypes3.types new file mode 100644 index 00000000000..6161bc4b72a --- /dev/null +++ b/tests/baselines/reference/literalTypes3.types @@ -0,0 +1,177 @@ +=== tests/cases/conformance/types/literal/literalTypes3.ts === + +function f1(s: string) { +>f1 : (s: string) => void +>s : string + + if (s === "foo") { +>s === "foo" : boolean +>s : string +>"foo" : "foo" + + s; // "foo" +>s : "foo" + } + if (s === "foo" || s === "bar") { +>s === "foo" || s === "bar" : boolean +>s === "foo" : boolean +>s : string +>"foo" : "foo" +>s === "bar" : boolean +>s : string +>"bar" : "bar" + + s; // "foo" | "bar" +>s : "foo" | "bar" + } +} + +function f2(s: string) { +>f2 : (s: string) => void +>s : string + + switch (s) { +>s : string + + case "foo": +>"foo" : "foo" + + case "bar": +>"bar" : "bar" + + s; // "foo" | "bar" +>s : "foo" | "bar" + + case "baz": +>"baz" : "baz" + + s; // "foo" | "bar" | "baz" +>s : "foo" | "bar" | "baz" + + break; + default: + s; // string +>s : string + } +} + +function f3(s: string) { +>f3 : (s: string) => "foo" | "bar" | undefined +>s : string + + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +>s === "foo" || s === "bar" ? s : undefined : "foo" | "bar" | undefined +>s === "foo" || s === "bar" : boolean +>s === "foo" : boolean +>s : string +>"foo" : "foo" +>s === "bar" : boolean +>s : string +>"bar" : "bar" +>s : "foo" | "bar" +>undefined : undefined +} + +function f4(x: number) { +>f4 : (x: number) => 1 | 2 +>x : number + + if (x === 1 || x === 2) { +>x === 1 || x === 2 : boolean +>x === 1 : boolean +>x : number +>1 : 1 +>x === 2 : boolean +>x : number +>2 : 2 + + return x; // 1 | 2 +>x : 1 | 2 + } + throw new Error(); +>new Error() : Error +>Error : ErrorConstructor +} + +function f5(x: number, y: 1 | 2) { +>f5 : (x: number, y: 1 | 2) => void +>x : number +>y : 1 | 2 + + if (x === 0 || x === y) { +>x === 0 || x === y : boolean +>x === 0 : boolean +>x : number +>0 : 0 +>x === y : boolean +>x : number +>y : 1 | 2 + + x; // 0 | 1 | 2 +>x : 1 | 2 | 0 + } +} + +function f6(x: number, y: 1 | 2) { +>f6 : (x: number, y: 1 | 2) => void +>x : number +>y : 1 | 2 + + if (y === x || 0 === x) { +>y === x || 0 === x : boolean +>y === x : boolean +>y : 1 | 2 +>x : number +>0 === x : boolean +>0 : 0 +>x : number + + x; // 0 | 1 | 2 +>x : 1 | 2 | 0 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { +>f7 : (x: number | "foo" | "bar", y: string | 1 | 2) => void +>x : number | "foo" | "bar" +>y : string | 1 | 2 + + if (x === y) { +>x === y : boolean +>x : number | "foo" | "bar" +>y : string | 1 | 2 + + x; // "foo" | "bar" | 1 | 2 +>x : "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { +>f8 : (x: number | "foo" | "bar") => void +>x : number | "foo" | "bar" + + switch (x) { +>x : number | "foo" | "bar" + + case 1: +>1 : 1 + + case 2: +>2 : 2 + + x; // 1 | 2 +>x : 1 | 2 + + break; + case "foo": +>"foo" : "foo" + + x; // "foo" +>x : "foo" + + break; + default: + x; // number | "bar" +>x : number | "bar" + } +} diff --git a/tests/cases/conformance/types/literal/literalTypes3.ts b/tests/cases/conformance/types/literal/literalTypes3.ts new file mode 100644 index 00000000000..2aa3f1020e2 --- /dev/null +++ b/tests/cases/conformance/types/literal/literalTypes3.ts @@ -0,0 +1,66 @@ +// @strictNullChecks: true + +function f1(s: string) { + if (s === "foo") { + s; // "foo" + } + if (s === "foo" || s === "bar") { + s; // "foo" | "bar" + } +} + +function f2(s: string) { + switch (s) { + case "foo": + case "bar": + s; // "foo" | "bar" + case "baz": + s; // "foo" | "bar" | "baz" + break; + default: + s; // string + } +} + +function f3(s: string) { + return s === "foo" || s === "bar" ? s : undefined; // "foo" | "bar" | undefined +} + +function f4(x: number) { + if (x === 1 || x === 2) { + return x; // 1 | 2 + } + throw new Error(); +} + +function f5(x: number, y: 1 | 2) { + if (x === 0 || x === y) { + x; // 0 | 1 | 2 + } +} + +function f6(x: number, y: 1 | 2) { + if (y === x || 0 === x) { + x; // 0 | 1 | 2 + } +} + +function f7(x: number | "foo" | "bar", y: 1 | 2 | string) { + if (x === y) { + x; // "foo" | "bar" | 1 | 2 + } +} + +function f8(x: number | "foo" | "bar") { + switch (x) { + case 1: + case 2: + x; // 1 | 2 + break; + case "foo": + x; // "foo" + break; + default: + x; // number | "bar" + } +} \ No newline at end of file From 1dedca73d120e396fa710c782d2a3bf59252d732 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 09:43:55 -0700 Subject: [PATCH 47/74] Support 'unshift' and fix typo --- src/compiler/binder.ts | 2 +- src/compiler/checker.ts | 18 ++++++++++-------- src/compiler/types.ts | 2 +- src/compiler/utilities.ts | 4 ++++ 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 6926403d9bb..65d620f9233 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1217,7 +1217,7 @@ namespace ts { } if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { const propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && propertyAccess.name.text === "push") { + if (isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) { currentFlow = createFlowArrayMutation(currentFlow, node); } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9e2b7a31748..7bec343c91e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8405,8 +8405,10 @@ namespace ts { } function isEmptyArrayAssignment(node: VariableDeclaration | BindingElement | Expression) { - return node.kind === SyntaxKind.VariableDeclaration && (node).initializer && isEmptyArrayLiteral((node).initializer) || - node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && isEmptyArrayLiteral((node.parent).right); + return node.kind === SyntaxKind.VariableDeclaration && (node).initializer && + isEmptyArrayLiteral((node).initializer) || + node.kind !== SyntaxKind.BindingElement && node.parent.kind === SyntaxKind.BinaryExpression && + isEmptyArrayLiteral((node.parent).right); } function getReferenceCandidate(node: Expression): Expression { @@ -8562,12 +8564,12 @@ namespace ts { getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); } - // Return true if the given node is 'x' in an 'x.push(value)' operation. - function isPushCallTarget(node: Node) { + // Return true if the given node is 'x' in an 'x.push(value)' or 'x.unshift(value)' operation. + function isPushOrUnshiftCallTarget(node: Node) { const parent = getReferenceRoot(node).parent; return parent.kind === SyntaxKind.PropertyAccessExpression && - (parent).name.text === "push" && - parent.parent.kind === SyntaxKind.CallExpression; + parent.parent.kind === SyntaxKind.CallExpression && + isPushOrUnshiftIdentifier((parent).name); } // Return true if the given node is 'x' in an 'x[n] = value' operation, where 'n' is an @@ -8596,9 +8598,9 @@ namespace ts { const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; // When the reference is 'x' in an 'x.push(value)' or 'x[n] = value' operation, we give type - // 'any[]' to 'x' instead of using the type determed by control flow analysis such that new + // 'any[]' to 'x' instead of using the type determined by control flow analysis such that new // element types are not considered errors. - const isEvolvingArrayInferenceTarget = isEvolvingArrayType(evolvedType) && (isPushCallTarget(reference) || isElementAssignmentTarget(reference)); + const isEvolvingArrayInferenceTarget = isEvolvingArrayType(evolvedType) && (isPushOrUnshiftCallTarget(reference) || isElementAssignmentTarget(reference)); const resultType = isEvolvingArrayInferenceTarget ? anyArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 5c32649d97c..ff7618c8e37 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1953,7 +1953,7 @@ namespace ts { } // FlowArrayMutation represents a node potentially mutates an array, i.e. an - // operation of the form 'x.push(value)' or 'x[n] = value'. + // operation of the form 'x.push(value)', 'x.unshift(value)' or 'x[n] = value'. export interface FlowArrayMutation extends FlowNode { node: CallExpression | BinaryExpression; antecedent: FlowNode; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 558015bb0e3..6e7dd8702f7 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1895,6 +1895,10 @@ namespace ts { return node.kind === SyntaxKind.Identifier && (node).text === "Symbol"; } + export function isPushOrUnshiftIdentifier(node: Identifier) { + return node.text === "push" || node.text === "unshift"; + } + export function isModifierKind(token: SyntaxKind): boolean { switch (token) { case SyntaxKind.AbstractKeyword: From 620b3f91e11e00a65ad024127d8964988875922a Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 09:44:37 -0700 Subject: [PATCH 48/74] Fix test --- tests/baselines/reference/implicitAnyWidenToAny.errors.txt | 2 +- tests/baselines/reference/implicitAnyWidenToAny.js | 4 ++-- tests/cases/compiler/implicitAnyWidenToAny.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt index 7a9314d982f..4302211d9a0 100644 --- a/tests/baselines/reference/implicitAnyWidenToAny.errors.txt +++ b/tests/baselines/reference/implicitAnyWidenToAny.errors.txt @@ -8,7 +8,7 @@ tests/cases/compiler/implicitAnyWidenToAny.ts(4,5): error TS7005: Variable 'wide var widenArray = [null, undefined]; // error at "widenArray" ~~~~~~~~~~ !!! error TS7005: Variable 'widenArray' implicitly has an 'any[]' type. - var emptyArray = []; // error at "emptyArray" + var emptyArray = []; // these should not be error class AnimalObj { diff --git a/tests/baselines/reference/implicitAnyWidenToAny.js b/tests/baselines/reference/implicitAnyWidenToAny.js index 0779a166744..0d1c42ad9d0 100644 --- a/tests/baselines/reference/implicitAnyWidenToAny.js +++ b/tests/baselines/reference/implicitAnyWidenToAny.js @@ -3,7 +3,7 @@ var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error class AnimalObj { @@ -32,7 +32,7 @@ var obj1 = anyReturnFunc(); var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error var AnimalObj = (function () { function AnimalObj() { diff --git a/tests/cases/compiler/implicitAnyWidenToAny.ts b/tests/cases/compiler/implicitAnyWidenToAny.ts index b4f4b5eb312..dcbabd38b47 100644 --- a/tests/cases/compiler/implicitAnyWidenToAny.ts +++ b/tests/cases/compiler/implicitAnyWidenToAny.ts @@ -3,7 +3,7 @@ var x = null; // error at "x" var x1 = undefined; // error at "x1" var widenArray = [null, undefined]; // error at "widenArray" -var emptyArray = []; // error at "emptyArray" +var emptyArray = []; // these should not be error class AnimalObj { From a27a68f8eb67557a9a2eda50501aa0c40c20699f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 09:44:50 -0700 Subject: [PATCH 49/74] Add additional tests --- .../baselines/reference/controlFlowArrays.js | 30 +++++++++ .../reference/controlFlowArrays.symbols | 48 ++++++++++++++ .../reference/controlFlowArrays.types | 64 +++++++++++++++++++ tests/cases/compiler/controlFlowArrays.ts | 16 +++++ 4 files changed, 158 insertions(+) diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js index d6f387ab981..b2d3fa8a2f2 100644 --- a/tests/baselines/reference/controlFlowArrays.js +++ b/tests/baselines/reference/controlFlowArrays.js @@ -155,6 +155,22 @@ function f16() { (x.push("hello"), x).push(true); ((x))[3] = { a: 1 }; return x; // (string | number | boolean | { a: number })[] +} + +function f17() { + let x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} + +function f18() { + let x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] } //// [controlFlowArrays.js] @@ -299,3 +315,17 @@ function f16() { ((x))[3] = { a: 1 }; return x; // (string | number | boolean | { a: number })[] } +function f17() { + var x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} +function f18() { + var x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] +} diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols index 204a2171992..463fb522585 100644 --- a/tests/baselines/reference/controlFlowArrays.symbols +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -400,3 +400,51 @@ function f16() { return x; // (string | number | boolean | { a: number })[] >x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) } + +function f17() { +>f17 : Symbol(f17, Decl(controlFlowArrays.ts, 156, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) + + x.unshift(5); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x.unshift("hello"); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x.unshift(true); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +} + +function f18() { +>f18 : Symbol(f18, Decl(controlFlowArrays.ts, 164, 1)) + + let x = []; +>x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) + + x.push(5); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + + x.unshift("hello"); +>x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) + + x[2] = true; +>x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) + + return x; // (string | number | boolean)[] +>x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +} diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types index 3a91ce7e197..2299afd7d21 100644 --- a/tests/baselines/reference/controlFlowArrays.types +++ b/tests/baselines/reference/controlFlowArrays.types @@ -521,3 +521,67 @@ function f16() { return x; // (string | number | boolean | { a: number })[] >x : (string | number | boolean | { a: number; })[] } + +function f17() { +>f17 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.unshift(5); +>x.unshift(5) : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>5 : 5 + + x.unshift("hello"); +>x.unshift("hello") : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>"hello" : "hello" + + x.unshift(true); +>x.unshift(true) : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} + +function f18() { +>f18 : () => (string | number | boolean)[] + + let x = []; +>x : any[] +>[] : never[] + + x.push(5); +>x.push(5) : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>5 : 5 + + x.unshift("hello"); +>x.unshift("hello") : number +>x.unshift : (...items: any[]) => number +>x : any[] +>unshift : (...items: any[]) => number +>"hello" : "hello" + + x[2] = true; +>x[2] = true : true +>x[2] : any +>x : any[] +>2 : 2 +>true : true + + return x; // (string | number | boolean)[] +>x : (string | number | boolean)[] +} diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts index e89a2443753..160f0efed17 100644 --- a/tests/cases/compiler/controlFlowArrays.ts +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -156,4 +156,20 @@ function f16() { (x.push("hello"), x).push(true); ((x))[3] = { a: 1 }; return x; // (string | number | boolean | { a: number })[] +} + +function f17() { + let x = []; + x.unshift(5); + x.unshift("hello"); + x.unshift(true); + return x; // (string | number | boolean)[] +} + +function f18() { + let x = []; + x.push(5); + x.unshift("hello"); + x[2] = true; + return x; // (string | number | boolean)[] } \ No newline at end of file From 224582c4f31c2b25164f741ee750360ff9859a38 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Thu, 13 Oct 2016 10:19:18 -0700 Subject: [PATCH 50/74] Merge pull request #11577 from Microsoft/vladima/configure-typing-acquisition Disable automatic type acquisition with command line option, replace npm view with request to npm registry --- .../unittests/tsserverProjectSystem.ts | 16 ++-- src/harness/unittests/typingsInstaller.ts | 28 +++---- src/server/server.ts | 7 +- .../typingsInstaller/nodeTypingsInstaller.ts | 80 +++++++++++++++---- .../typingsInstaller/typingsInstaller.ts | 29 +++---- 5 files changed, 105 insertions(+), 55 deletions(-) diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 08e4bac7b2c..831dd6a7542 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -19,10 +19,8 @@ namespace ts.projectSystem { export interface PostExecAction { readonly requestKind: TI.RequestKind; - readonly error: Error; - readonly stdout: string; - readonly stderr: string; - readonly callback: (err: Error, stdout: string, stderr: string) => void; + readonly success: boolean; + readonly callback: TI.RequestCompletedAction; } export function notImplemented(): any { @@ -54,7 +52,7 @@ namespace ts.projectSystem { export class TestTypingsInstaller extends TI.TypingsInstaller implements server.ITypingsInstaller { protected projectService: server.ProjectService; constructor(readonly globalTypingsCacheLocation: string, throttleLimit: number, readonly installTypingHost: server.ServerHost, log?: TI.Log) { - super(globalTypingsCacheLocation, "npm", safeList.path, throttleLimit, log); + super(globalTypingsCacheLocation, safeList.path, throttleLimit, log); this.init(); } @@ -65,7 +63,7 @@ namespace ts.projectSystem { const actionsToRun = this.postExecActions; this.postExecActions = []; for (const action of actionsToRun) { - action.callback(action.error, action.stdout, action.stderr); + action.callback(action.success); } } @@ -85,7 +83,7 @@ namespace ts.projectSystem { return this.installTypingHost; } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: (err: Error, stdout: string, stderr: string) => void): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { switch (requestKind) { case TI.NpmViewRequest: case TI.NpmInstallRequest: @@ -108,9 +106,7 @@ namespace ts.projectSystem { addPostExecAction(requestKind: TI.RequestKind, stdout: string | string[], cb: TI.RequestCompletedAction) { const out = typeof stdout === "string" ? stdout : createNpmPackageJsonString(stdout); const action: PostExecAction = { - error: undefined, - stdout: out, - stderr: "", + success: !!out, callback: cb, requestKind }; diff --git a/src/harness/unittests/typingsInstaller.ts b/src/harness/unittests/typingsInstaller.ts index d79a1a7723c..ebd0f0ef792 100644 --- a/src/harness/unittests/typingsInstaller.ts +++ b/src/harness/unittests/typingsInstaller.ts @@ -31,11 +31,11 @@ namespace ts.projectSystem { function executeCommand(self: Installer, host: TestServerHost, installedTypings: string[], typingFiles: FileOrFolder[], requestKind: TI.RequestKind, cb: TI.RequestCompletedAction): void { switch (requestKind) { case TI.NpmInstallRequest: - self.addPostExecAction(requestKind, installedTypings, (err, stdout, stderr) => { + self.addPostExecAction(requestKind, installedTypings, success => { for (const file of typingFiles) { host.createFileOrFolder(file, /*createParentDirectory*/ true); } - cb(err, stdout, stderr); + cb(success); }); break; case TI.NpmViewRequest: @@ -81,7 +81,7 @@ namespace ts.projectSystem { constructor() { super(host); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jquery]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -125,7 +125,7 @@ namespace ts.projectSystem { constructor() { super(host); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jquery]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -221,7 +221,7 @@ namespace ts.projectSystem { enqueueIsCalled = true; super.enqueueInstallTypingsRequest(project, typingOptions); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/jquery"]; const typingFiles = [jquery]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -275,7 +275,7 @@ namespace ts.projectSystem { constructor() { super(host); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/lodash", "@types/react"]; const typingFiles = [lodash, react]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -323,7 +323,7 @@ namespace ts.projectSystem { enqueueIsCalled = true; super.enqueueInstallTypingsRequest(project, typingOptions); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings: string[] = []; const typingFiles: FileOrFolder[] = []; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -398,7 +398,7 @@ namespace ts.projectSystem { constructor() { super(host); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment"]; const typingFiles = [commander, express, jquery, moment]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -477,7 +477,7 @@ namespace ts.projectSystem { constructor() { super(host, { throttleLimit: 3 }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment", "@types/lodash"]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); } @@ -567,10 +567,10 @@ namespace ts.projectSystem { constructor() { super(host, { throttleLimit: 3 }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: TI.RequestCompletedAction): void { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void { if (requestKind === TI.NpmInstallRequest) { let typingFiles: (FileOrFolder & { typings: string}) [] = []; - if (command.indexOf("commander") >= 0) { + if (args.indexOf("@types/commander") >= 0) { typingFiles = [commander, jquery, lodash, cordova]; } else { @@ -655,7 +655,7 @@ namespace ts.projectSystem { constructor() { super(host, { globalTypingsCacheLocation: "/tmp" }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jqueryDTS]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -701,7 +701,7 @@ namespace ts.projectSystem { constructor() { super(host, { globalTypingsCacheLocation: "/tmp" }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { const installedTypings = ["@types/jquery"]; const typingFiles = [jqueryDTS]; executeCommand(this, host, installedTypings, typingFiles, requestKind, cb); @@ -766,7 +766,7 @@ namespace ts.projectSystem { constructor() { super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) }); } - runCommand(requestKind: TI.RequestKind, requestId: number, command: string, cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { + executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) { assert(false, "runCommand should not be invoked"); } })(); diff --git a/src/server/server.ts b/src/server/server.ts index d59100bb57c..e728d7e9d72 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -265,13 +265,16 @@ namespace ts.server { installerEventPort: number, canUseEvents: boolean, useSingleInferredProject: boolean, + disableAutomaticTypingAcquisition: boolean, globalTypingsCacheLocation: string, logger: server.Logger) { super( host, cancellationToken, useSingleInferredProject, - new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), + disableAutomaticTypingAcquisition + ? nullTypingsInstaller + : new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, @@ -512,12 +515,14 @@ namespace ts.server { } const useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; + const disableAutomaticTypingAcquisition = sys.args.indexOf("--disableAutomaticTypingAcquisition") >= 0; const ioSession = new IOSession( sys, cancellationToken, eventPort, /*canUseEvents*/ eventPort === undefined, useSingleInferredProject, + disableAutomaticTypingAcquisition, getGlobalTypingsCacheLocation(), logger); process.on("uncaughtException", function (err: Error) { diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index b73a8e4e79d..044935670f2 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -33,23 +33,38 @@ namespace ts.server.typingsInstaller { } } - export class NodeTypingsInstaller extends TypingsInstaller { - private readonly exec: { (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any }; + type HttpGet = { + (url: string, callback: (response: HttpResponse) => void): NodeJS.EventEmitter; + } + interface HttpResponse extends NodeJS.ReadableStream { + statusCode: number; + statusMessage: string; + destroy(): void; + } + + type Exec = { + (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any + } + + export class NodeTypingsInstaller extends TypingsInstaller { + private readonly exec: Exec; + private readonly httpGet: HttpGet; + private readonly npmPath: string; readonly installTypingHost: InstallTypingHost = sys; constructor(globalTypingsCacheLocation: string, throttleLimit: number, log: Log) { super( globalTypingsCacheLocation, - /*npmPath*/ getNPMLocation(process.argv[0]), toPath("typingSafeList.json", __dirname, createGetCanonicalFileName(sys.useCaseSensitiveFileNames)), throttleLimit, log); if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); } - const { exec } = require("child_process"); - this.exec = exec; + this.npmPath = getNPMLocation(process.argv[0]); + this.exec = require("child_process").exec; + this.httpGet = require("http").get; } init() { @@ -75,17 +90,54 @@ namespace ts.server.typingsInstaller { } } - protected runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void { + protected executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { if (this.log.isEnabled()) { - this.log.writeLine(`#${requestId} running command '${command}'.`); + this.log.writeLine(`#${requestId} executing ${requestKind}, arguments'${JSON.stringify(args)}'.`); + } + switch (requestKind) { + case NpmViewRequest: { + // const command = `${self.npmPath} view @types/${typing} --silent name`; + // use http request to global npm registry instead of running npm view + Debug.assert(args.length === 1); + const url = `http://registry.npmjs.org/@types%2f${args[0]}`; + const start = Date.now(); + this.httpGet(url, response => { + let ok = false; + if (this.log.isEnabled()) { + this.log.writeLine(`${requestKind} #${requestId} request to ${url}:: status code ${response.statusCode}, status message '${response.statusMessage}', took ${Date.now() - start} ms`); + } + switch (response.statusCode) { + case 200: // OK + case 301: // redirect - Moved - treat package as present + case 302: // redirect - Found - treat package as present + ok = true; + break; + } + response.destroy(); + onRequestCompleted(ok); + }).on("error", (err: Error) => { + if (this.log.isEnabled()) { + this.log.writeLine(`${requestKind} #${requestId} query to npm registry failed with error ${err.message}, stack ${err.stack}`); + } + onRequestCompleted(/*success*/ false); + }); + } + break; + case NpmInstallRequest: { + const command = `${this.npmPath} install ${args.join(" ")} --save-dev`; + const start = Date.now(); + this.exec(command, { cwd }, (err, stdout, stderr) => { + if (this.log.isEnabled()) { + this.log.writeLine(`${requestKind} #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout}${sys.newLine}stderr: ${stderr}`); + } + // treat any output on stdout as success + onRequestCompleted(!!stdout); + }); + } + break; + default: + Debug.assert(false, `Unknown request kind ${requestKind}`); } - this.exec(command, { cwd }, (err, stdout, stderr) => { - if (this.log.isEnabled()) { - this.log.writeLine(`${requestKind} #${requestId} stdout: ${stdout}`); - this.log.writeLine(`${requestKind} #${requestId} stderr: ${stderr}`); - } - onRequestCompleted(err, stdout, stderr); - }); } } diff --git a/src/server/typingsInstaller/typingsInstaller.ts b/src/server/typingsInstaller/typingsInstaller.ts index 0ed2ccce99d..f62f5fc4abe 100644 --- a/src/server/typingsInstaller/typingsInstaller.ts +++ b/src/server/typingsInstaller/typingsInstaller.ts @@ -65,11 +65,11 @@ namespace ts.server.typingsInstaller { export type RequestKind = typeof NpmViewRequest | typeof NpmInstallRequest; - export type RequestCompletedAction = (err: Error, stdout: string, stderr: string) => void; + export type RequestCompletedAction = (success: boolean) => void; type PendingRequest = { requestKind: RequestKind; requestId: number; - command: string; + args: string[]; cwd: string; onRequestCompleted: RequestCompletedAction }; @@ -88,7 +88,6 @@ namespace ts.server.typingsInstaller { constructor( readonly globalCachePath: string, - readonly npmPath: string, readonly safeListPath: Path, readonly throttleLimit: number, protected readonly log = nullLog) { @@ -331,13 +330,12 @@ namespace ts.server.typingsInstaller { let execInstallCmdCount = 0; const filteredTypings: string[] = []; for (const typing of typingsToInstall) { - execNpmViewTyping(this, typing); + filterExistingTypings(this, typing); } - function execNpmViewTyping(self: TypingsInstaller, typing: string) { - const command = `${self.npmPath} view @types/${typing} --silent name`; - self.execAsync(NpmViewRequest, requestId, command, cachePath, (err, stdout, stderr) => { - if (stdout) { + function filterExistingTypings(self: TypingsInstaller, typing: string) { + self.execAsync(NpmViewRequest, requestId, [typing], cachePath, ok => { + if (ok) { filteredTypings.push(typing); } execInstallCmdCount++; @@ -353,9 +351,8 @@ namespace ts.server.typingsInstaller { return; } const scopedTypings = filteredTypings.map(t => "@types/" + t); - const command = `${self.npmPath} install ${scopedTypings.join(" ")} --save-dev`; - self.execAsync(NpmInstallRequest, requestId, command, cachePath, (err, stdout, stderr) => { - postInstallAction(stdout ? scopedTypings : []); + self.execAsync(NpmInstallRequest, requestId, scopedTypings, cachePath, ok => { + postInstallAction(ok ? scopedTypings : []); }); } } @@ -403,8 +400,8 @@ namespace ts.server.typingsInstaller { }; } - private execAsync(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void { - this.pendingRunRequests.unshift({ requestKind, requestId, command, cwd, onRequestCompleted }); + private execAsync(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void { + this.pendingRunRequests.unshift({ requestKind, requestId, args, cwd, onRequestCompleted }); this.executeWithThrottling(); } @@ -412,15 +409,15 @@ namespace ts.server.typingsInstaller { while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) { this.inFlightRequestCount++; const request = this.pendingRunRequests.pop(); - this.runCommand(request.requestKind, request.requestId, request.command, request.cwd, (err, stdout, stderr) => { + this.executeRequest(request.requestKind, request.requestId, request.args, request.cwd, ok => { this.inFlightRequestCount--; - request.onRequestCompleted(err, stdout, stderr); + request.onRequestCompleted(ok); this.executeWithThrottling(); }); } } - protected abstract runCommand(requestKind: RequestKind, requestId: number, command: string, cwd: string, onRequestCompleted: RequestCompletedAction): void; + protected abstract executeRequest(requestKind: RequestKind, requestId: number, args: string[], cwd: string, onRequestCompleted: RequestCompletedAction): void; protected abstract sendResponse(response: SetTypings | InvalidateCachedTypings): void; } } \ No newline at end of file From 9c41e42d6265c97ae98d7974b6102086c5098fab Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Thu, 13 Oct 2016 10:29:01 -0700 Subject: [PATCH 51/74] fix linter issues --- src/server/typingsInstaller/nodeTypingsInstaller.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/server/typingsInstaller/nodeTypingsInstaller.ts b/src/server/typingsInstaller/nodeTypingsInstaller.ts index 044935670f2..ff643e885e4 100644 --- a/src/server/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/server/typingsInstaller/nodeTypingsInstaller.ts @@ -35,7 +35,7 @@ namespace ts.server.typingsInstaller { type HttpGet = { (url: string, callback: (response: HttpResponse) => void): NodeJS.EventEmitter; - } + }; interface HttpResponse extends NodeJS.ReadableStream { statusCode: number; @@ -45,7 +45,7 @@ namespace ts.server.typingsInstaller { type Exec = { (command: string, options: { cwd: string }, callback?: (error: Error, stdout: string, stderr: string) => void): any - } + }; export class NodeTypingsInstaller extends TypingsInstaller { private readonly exec: Exec; From 1c6fde67567b9d79d4ba51c68c3a8c12a22e3870 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Thu, 13 Oct 2016 13:03:25 -0700 Subject: [PATCH 52/74] Update issue template --- issue_template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/issue_template.md b/issue_template.md index 7799960ec78..fcd995317f5 100644 --- a/issue_template.md +++ b/issue_template.md @@ -2,7 +2,7 @@ -**TypeScript Version:** 1.8.0 / nightly (2.0.0-dev.201xxxxx) +**TypeScript Version:** 2.0.3 / nightly (2.1.0-dev.201xxxxx) **Code** From 5b4dfcc18f441f6af1bcd5485b86e9a3429019c1 Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 13 Oct 2016 13:22:58 -0700 Subject: [PATCH 53/74] Address PR: remove locales and options; use accent as default --- src/compiler/core.ts | 19 +++++++------------ src/services/navigateTo.ts | 5 +---- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 47eb66db07c..e8fadbff6e9 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -23,10 +23,6 @@ namespace ts { // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; - // This means "compare in a case insensitive manner but consider accentsor other diacritic marks" - // (e.g. a ≠ b, a ≠ á, a = A) - const accentSensitivity: Intl.CollatorOptions = { usage: "sort", sensitivity: "accent" }; - /** * Use this function instead of calling "String.prototype.localeCompre". This function will preform appropriate check to make sure that * "typeof Intl" is correct as there are reported issues #11110 nad #11339. @@ -1033,13 +1029,14 @@ namespace ts { return a < b ? Comparison.LessThan : Comparison.GreaterThan; } - export function compareStrings(a: string, b: string, locales?: string | string[], options?: Intl.CollatorOptions): Comparison { + export function compareStrings(a: string, b: string, ignoreCase?: boolean): Comparison { if (a === b) return Comparison.EqualTo; if (a === undefined) return Comparison.LessThan; if (b === undefined) return Comparison.GreaterThan; - if (options) { + if (ignoreCase) { if (collator && String.prototype.localeCompare) { - const result = a.localeCompare(b, locales, options); + // accent means a ≠ b, a ≠ á, a = A + const result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? Comparison.LessThan : result > 0 ? Comparison.GreaterThan : Comparison.EqualTo; } @@ -1052,7 +1049,7 @@ namespace ts { } export function compareStringsCaseInsensitive(a: string, b: string) { - return compareStrings(a, b, /*locales*/ undefined, accentSensitivity); + return compareStrings(a, b, /*ignoreCase*/ true); } function getDiagnosticFileName(diagnostic: Diagnostic): string { @@ -1422,8 +1419,7 @@ namespace ts { const bComponents = getNormalizedPathComponents(b, currentDirectory); const sharedLength = Math.min(aComponents.length, bComponents.length); for (let i = 0; i < sharedLength; i++) { - const result = compareStrings(aComponents[i], bComponents[i], - /*locales*/ undefined, /*options*/ ignoreCase ? accentSensitivity : undefined); + const result = compareStrings(aComponents[i], bComponents[i], ignoreCase); if (result !== Comparison.EqualTo) { return result; } @@ -1445,8 +1441,7 @@ namespace ts { } for (let i = 0; i < parentComponents.length; i++) { - const result = compareStrings(parentComponents[i], childComponents[i], - /*locales*/ undefined, /*options*/ ignoreCase ? accentSensitivity : undefined); + const result = compareStrings(parentComponents[i], childComponents[i], ignoreCase); if (result !== Comparison.EqualTo) { return false; } diff --git a/src/services/navigateTo.ts b/src/services/navigateTo.ts index 2433dbe9795..82f4dd49f2b 100644 --- a/src/services/navigateTo.ts +++ b/src/services/navigateTo.ts @@ -6,9 +6,6 @@ namespace ts.NavigateTo { const patternMatcher = createPatternMatcher(searchValue); let rawItems: RawNavigateToItem[] = []; - // This means "compare in a case insensitive manner." - const baseSensitivity: Intl.CollatorOptions = { sensitivity: "base" }; - // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] forEach(sourceFiles, sourceFile => { cancellationToken.throwIfCancellationRequested(); @@ -188,7 +185,7 @@ namespace ts.NavigateTo { // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - ts.compareStrings(i1.name, i2.name, /*locales*/ undefined, /*options*/ baseSensitivity) || + ts.compareStringsCaseInsensitive(i1.name, i2.name) || ts.compareStrings(i1.name, i2.name); } From bf301e9ccce09f7dcd36944d8941e2c26e5c73f7 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 13:28:58 -0700 Subject: [PATCH 54/74] Treat reference to empty evolving array as an implicit any[] --- src/compiler/checker.ts | 46 ++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7bec343c91e..9b2679adc59 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -8524,9 +8524,11 @@ namespace ts { } function createFinalArrayType(elementType: Type) { - return createArrayType(elementType !== neverType ? - elementType.flags & TypeFlags.Union ? getUnionType((elementType).types, /*subtypeReduction*/ true) : elementType : - strictNullChecks ? neverType : undefinedWideningType); + return elementType.flags & TypeFlags.Never ? + autoArrayType : + createArrayType(elementType.flags & TypeFlags.Union ? + getUnionType((elementType).types, /*subtypeReduction*/ true) : + elementType); } // We perform subtype reduction upon obtaining the final array type from an evolving array type. @@ -8564,26 +8566,22 @@ namespace ts { getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction); } - // Return true if the given node is 'x' in an 'x.push(value)' or 'x.unshift(value)' operation. - function isPushOrUnshiftCallTarget(node: Node) { - const parent = getReferenceRoot(node).parent; - return parent.kind === SyntaxKind.PropertyAccessExpression && - parent.parent.kind === SyntaxKind.CallExpression && - isPushOrUnshiftIdentifier((parent).name); - } - - // Return true if the given node is 'x' in an 'x[n] = value' operation, where 'n' is an - // expression of type any, undefined, or a number-like type. - function isElementAssignmentTarget(node: Node) { + // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or + // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type. + function isEvolvingArrayOperationTarget(node: Node) { const root = getReferenceRoot(node); const parent = root.parent; - return parent.kind === SyntaxKind.ElementAccessExpression && + const isLengthPushOrUnshift = parent.kind === SyntaxKind.PropertyAccessExpression && ( + (parent).name.text === "length" || + parent.parent.kind === SyntaxKind.CallExpression && isPushOrUnshiftIdentifier((parent).name)); + const isElementAssignment = parent.kind === SyntaxKind.ElementAccessExpression && (parent).expression === root && parent.parent.kind === SyntaxKind.BinaryExpression && (parent.parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent.parent).left === parent && !isAssignmentTarget(parent.parent) && isTypeAnyOrAllConstituentTypesHaveKind(checkExpression((parent).argumentExpression), TypeFlags.NumberLike | TypeFlags.Undefined); + return isLengthPushOrUnshift || isElementAssignment; } function getFlowTypeOfReference(reference: Node, declaredType: Type, assumeInitialized: boolean, flowContainer: Node) { @@ -8597,11 +8595,11 @@ namespace ts { const visitedFlowStart = visitedFlowCount; const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; - // When the reference is 'x' in an 'x.push(value)' or 'x[n] = value' operation, we give type - // 'any[]' to 'x' instead of using the type determined by control flow analysis such that new - // element types are not considered errors. - const isEvolvingArrayInferenceTarget = isEvolvingArrayType(evolvedType) && (isPushOrUnshiftCallTarget(reference) || isElementAssignmentTarget(reference)); - const resultType = isEvolvingArrayInferenceTarget ? anyArrayType : finalizeEvolvingArrayType(evolvedType); + // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation, + // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations + // on empty arrays are possible without implicit any errors and new element types can be inferred without + // type mismatch errors. + const resultType = isEvolvingArrayType(evolvedType) && isEvolvingArrayOperationTarget(reference) ? anyArrayType : finalizeEvolvingArrayType(evolvedType); if (reference.parent.kind === SyntaxKind.NonNullExpression && getTypeWithFacts(resultType, TypeFacts.NEUndefinedOrNull).flags & TypeFlags.Never) { return declaredType; } @@ -9355,12 +9353,12 @@ namespace ts { // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. if (type === autoType || type === autoArrayType) { - if (flowType === type) { + if (flowType === autoType || flowType === autoArrayType) { if (compilerOptions.noImplicitAny) { - error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(type)); - error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(type)); + error(declaration.name, Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType)); + error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType)); } - return convertAutoToAny(type); + return convertAutoToAny(flowType); } } else if (!assumeInitialized && !(getFalsyFlags(type) & TypeFlags.Undefined) && getFalsyFlags(flowType) & TypeFlags.Undefined) { From bfa4197ffe610354efb382a5ef772ed3bf70c3c1 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 13:29:08 -0700 Subject: [PATCH 55/74] Update tests --- tests/cases/compiler/controlFlowArrayErrors.ts | 10 +++++----- tests/cases/compiler/controlFlowArrays.ts | 10 ++++++++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/tests/cases/compiler/controlFlowArrayErrors.ts b/tests/cases/compiler/controlFlowArrayErrors.ts index aab3a974cd8..08107ff3659 100644 --- a/tests/cases/compiler/controlFlowArrayErrors.ts +++ b/tests/cases/compiler/controlFlowArrayErrors.ts @@ -3,16 +3,16 @@ declare function cond(): boolean; function f1() { - let x = []; - let y = x; // Implicit any[] error + let x = []; // Implicit any[] error in some locations + let y = x; // Implicit any[] error x.push(5); let z = x; } function f2() { - let x; + let x; // Implicit any[] error in some locations x = []; - let y = x; // Implicit any[] error + let y = x; // Implicit any[] error x.push(5); let z = x; } @@ -21,7 +21,7 @@ function f3() { let x = []; // Implicit any[] error in some locations x.push(5); function g() { - x; // Implicit any[] error + x; // Implicit any[] error } } diff --git a/tests/cases/compiler/controlFlowArrays.ts b/tests/cases/compiler/controlFlowArrays.ts index 160f0efed17..646c85f069f 100644 --- a/tests/cases/compiler/controlFlowArrays.ts +++ b/tests/cases/compiler/controlFlowArrays.ts @@ -115,13 +115,19 @@ function f10() { function f11() { let x = []; - return x; // never[] + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; } function f12() { let x; x = []; - return x; // never[] + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; } function f13() { From 79ed3a7ed83605f0230df160d8472de1b372d4f3 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 13 Oct 2016 13:29:42 -0700 Subject: [PATCH 56/74] Accept new baselines --- .../reference/arrayLiterals2ES5.types | 6 +- .../controlFlowArrayErrors.errors.txt | 28 +++-- .../reference/controlFlowArrayErrors.js | 14 +-- .../baselines/reference/controlFlowArrays.js | 20 +++- .../reference/controlFlowArrays.symbols | 108 +++++++++++------- .../reference/controlFlowArrays.types | 40 ++++++- .../genericTypeParameterEquivalence2.types | 2 +- .../reference/globalThisCapture.types | 4 +- 8 files changed, 144 insertions(+), 78 deletions(-) diff --git a/tests/baselines/reference/arrayLiterals2ES5.types b/tests/baselines/reference/arrayLiterals2ES5.types index 833966a6e48..c3256db925e 100644 --- a/tests/baselines/reference/arrayLiterals2ES5.types +++ b/tests/baselines/reference/arrayLiterals2ES5.types @@ -194,9 +194,9 @@ var d5 = [...temp3]; var d6 = [...temp4]; >d6 : any[] ->[...temp4] : undefined[] ->...temp4 : undefined ->temp4 : undefined[] +>[...temp4] : any[] +>...temp4 : any +>temp4 : any[] var d7 = [...[...temp1]]; >d7 : number[] diff --git a/tests/baselines/reference/controlFlowArrayErrors.errors.txt b/tests/baselines/reference/controlFlowArrayErrors.errors.txt index bc13de261e2..2ef009dc0e1 100644 --- a/tests/baselines/reference/controlFlowArrayErrors.errors.txt +++ b/tests/baselines/reference/controlFlowArrayErrors.errors.txt @@ -1,5 +1,7 @@ -tests/cases/compiler/controlFlowArrayErrors.ts(6,9): error TS7005: Variable 'y' implicitly has an 'any[]' type. -tests/cases/compiler/controlFlowArrayErrors.ts(14,9): error TS7005: Variable 'y' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(5,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(6,13): error TS7005: Variable 'x' implicitly has an 'any[]' type. +tests/cases/compiler/controlFlowArrayErrors.ts(12,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. +tests/cases/compiler/controlFlowArrayErrors.ts(14,13): error TS7005: Variable 'x' implicitly has an 'any[]' type. tests/cases/compiler/controlFlowArrayErrors.ts(20,9): error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. tests/cases/compiler/controlFlowArrayErrors.ts(23,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. tests/cases/compiler/controlFlowArrayErrors.ts(30,12): error TS2345: Argument of type 'true' is not assignable to parameter of type 'string | number'. @@ -10,25 +12,29 @@ tests/cases/compiler/controlFlowArrayErrors.ts(61,11): error TS7034: Variable 'x tests/cases/compiler/controlFlowArrayErrors.ts(64,9): error TS7005: Variable 'x' implicitly has an 'any[]' type. -==== tests/cases/compiler/controlFlowArrayErrors.ts (10 errors) ==== +==== tests/cases/compiler/controlFlowArrayErrors.ts (12 errors) ==== declare function cond(): boolean; function f1() { - let x = []; - let y = x; // Implicit any[] error + let x = []; // Implicit any[] error in some locations ~ -!!! error TS7005: Variable 'y' implicitly has an 'any[]' type. +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. x.push(5); let z = x; } function f2() { - let x; - x = []; - let y = x; // Implicit any[] error + let x; // Implicit any[] error in some locations ~ -!!! error TS7005: Variable 'y' implicitly has an 'any[]' type. +!!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. + x = []; + let y = x; // Implicit any[] error + ~ +!!! error TS7005: Variable 'x' implicitly has an 'any[]' type. x.push(5); let z = x; } @@ -39,7 +45,7 @@ tests/cases/compiler/controlFlowArrayErrors.ts(64,9): error TS7005: Variable 'x' !!! error TS7034: Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined. x.push(5); function g() { - x; // Implicit any[] error + x; // Implicit any[] error ~ !!! error TS7005: Variable 'x' implicitly has an 'any[]' type. } diff --git a/tests/baselines/reference/controlFlowArrayErrors.js b/tests/baselines/reference/controlFlowArrayErrors.js index 538addc31c0..59995eb3094 100644 --- a/tests/baselines/reference/controlFlowArrayErrors.js +++ b/tests/baselines/reference/controlFlowArrayErrors.js @@ -3,16 +3,16 @@ declare function cond(): boolean; function f1() { - let x = []; - let y = x; // Implicit any[] error + let x = []; // Implicit any[] error in some locations + let y = x; // Implicit any[] error x.push(5); let z = x; } function f2() { - let x; + let x; // Implicit any[] error in some locations x = []; - let y = x; // Implicit any[] error + let y = x; // Implicit any[] error x.push(5); let z = x; } @@ -21,7 +21,7 @@ function f3() { let x = []; // Implicit any[] error in some locations x.push(5); function g() { - x; // Implicit any[] error + x; // Implicit any[] error } } @@ -68,13 +68,13 @@ function f8() { //// [controlFlowArrayErrors.js] function f1() { - var x = []; + var x = []; // Implicit any[] error in some locations var y = x; // Implicit any[] error x.push(5); var z = x; } function f2() { - var x; + var x; // Implicit any[] error in some locations x = []; var y = x; // Implicit any[] error x.push(5); diff --git a/tests/baselines/reference/controlFlowArrays.js b/tests/baselines/reference/controlFlowArrays.js index b2d3fa8a2f2..3f119599495 100644 --- a/tests/baselines/reference/controlFlowArrays.js +++ b/tests/baselines/reference/controlFlowArrays.js @@ -114,13 +114,19 @@ function f10() { function f11() { let x = []; - return x; // never[] + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; } function f12() { let x; x = []; - return x; // never[] + if (x.length === 0) { // x.length ok on implicit any[] + x.push("hello"); + } + return x; } function f13() { @@ -278,12 +284,18 @@ function f10() { } function f11() { var x = []; - return x; // never[] + if (x.length === 0) { + x.push("hello"); + } + return x; } function f12() { var x; x = []; - return x; // never[] + if (x.length === 0) { + x.push("hello"); + } + return x; } function f13() { var x = []; diff --git a/tests/baselines/reference/controlFlowArrays.symbols b/tests/baselines/reference/controlFlowArrays.symbols index 463fb522585..184a813a05f 100644 --- a/tests/baselines/reference/controlFlowArrays.symbols +++ b/tests/baselines/reference/controlFlowArrays.symbols @@ -282,78 +282,98 @@ function f11() { let x = []; >x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) - return x; // never[] + if (x.length === 0) { // x.length ok on implicit any[] +>x.length : Symbol(Array.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +>length : Symbol(Array.length, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; >x : Symbol(x, Decl(controlFlowArrays.ts, 114, 7)) } function f12() { ->f12 : Symbol(f12, Decl(controlFlowArrays.ts, 116, 1)) +>f12 : Symbol(f12, Decl(controlFlowArrays.ts, 119, 1)) let x; ->x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) - return x; // never[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 119, 7)) + if (x.length === 0) { // x.length ok on implicit any[] +>x.length : Symbol(Array.length, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) +>length : Symbol(Array.length, Decl(lib.d.ts, --, --)) + + x.push("hello"); +>x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) +>push : Symbol(Array.push, Decl(lib.d.ts, --, --)) + } + return x; +>x : Symbol(x, Decl(controlFlowArrays.ts, 122, 7)) } function f13() { ->f13 : Symbol(f13, Decl(controlFlowArrays.ts, 122, 1)) +>f13 : Symbol(f13, Decl(controlFlowArrays.ts, 128, 1)) var x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) x.push(5); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) x.push("hello"); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) x.push(true); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) return x; // (string | number | boolean)[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 125, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 131, 7)) } function f14() { ->f14 : Symbol(f14, Decl(controlFlowArrays.ts, 130, 1)) +>f14 : Symbol(f14, Decl(controlFlowArrays.ts, 136, 1)) const x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) x.push(5); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) x.push("hello"); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) x.push(true); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) return x; // (string | number | boolean)[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 133, 9)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 139, 9)) } function f15() { ->f15 : Symbol(f15, Decl(controlFlowArrays.ts, 138, 1)) +>f15 : Symbol(f15, Decl(controlFlowArrays.ts, 144, 1)) let x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) while (cond()) { >cond : Symbol(cond, Decl(controlFlowArrays.ts, 0, 0)) @@ -363,88 +383,88 @@ function f15() { x.push("hello"); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) } return x; // string[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 141, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 147, 7)) } function f16() { ->f16 : Symbol(f16, Decl(controlFlowArrays.ts, 147, 1)) +>f16 : Symbol(f16, Decl(controlFlowArrays.ts, 153, 1)) let x; ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) let y; ->y : Symbol(y, Decl(controlFlowArrays.ts, 151, 7)) +>y : Symbol(y, Decl(controlFlowArrays.ts, 157, 7)) (x = [], x).push(5); >(x = [], x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) (x.push("hello"), x).push(true); >(x.push("hello"), x).push : Symbol(Array.push, Decl(lib.d.ts, --, --)) >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ((x))[3] = { a: 1 }; ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) ->a : Symbol(a, Decl(controlFlowArrays.ts, 154, 16)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) +>a : Symbol(a, Decl(controlFlowArrays.ts, 160, 16)) return x; // (string | number | boolean | { a: number })[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 150, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 156, 7)) } function f17() { ->f17 : Symbol(f17, Decl(controlFlowArrays.ts, 156, 1)) +>f17 : Symbol(f17, Decl(controlFlowArrays.ts, 162, 1)) let x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) x.unshift(5); >x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) >unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) x.unshift("hello"); >x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) >unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) x.unshift(true); >x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) >unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) return x; // (string | number | boolean)[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 159, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 165, 7)) } function f18() { ->f18 : Symbol(f18, Decl(controlFlowArrays.ts, 164, 1)) +>f18 : Symbol(f18, Decl(controlFlowArrays.ts, 170, 1)) let x = []; ->x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) x.push(5); >x.push : Symbol(Array.push, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) >push : Symbol(Array.push, Decl(lib.d.ts, --, --)) x.unshift("hello"); >x.unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) ->x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) >unshift : Symbol(Array.unshift, Decl(lib.d.ts, --, --)) x[2] = true; ->x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) return x; // (string | number | boolean)[] ->x : Symbol(x, Decl(controlFlowArrays.ts, 167, 7)) +>x : Symbol(x, Decl(controlFlowArrays.ts, 173, 7)) } diff --git a/tests/baselines/reference/controlFlowArrays.types b/tests/baselines/reference/controlFlowArrays.types index 2299afd7d21..2a27bbf10de 100644 --- a/tests/baselines/reference/controlFlowArrays.types +++ b/tests/baselines/reference/controlFlowArrays.types @@ -357,18 +357,32 @@ function f10() { } function f11() { ->f11 : () => never[] +>f11 : () => string[] let x = []; >x : any[] >[] : never[] - return x; // never[] ->x : never[] + if (x.length === 0) { // x.length ok on implicit any[] +>x.length === 0 : boolean +>x.length : number +>x : any[] +>length : number +>0 : 0 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; +>x : string[] } function f12() { ->f12 : () => never[] +>f12 : () => string[] let x; >x : any @@ -378,8 +392,22 @@ function f12() { >x : any >[] : never[] - return x; // never[] ->x : never[] + if (x.length === 0) { // x.length ok on implicit any[] +>x.length === 0 : boolean +>x.length : number +>x : any[] +>length : number +>0 : 0 + + x.push("hello"); +>x.push("hello") : number +>x.push : (...items: any[]) => number +>x : any[] +>push : (...items: any[]) => number +>"hello" : "hello" + } + return x; +>x : string[] } function f13() { diff --git a/tests/baselines/reference/genericTypeParameterEquivalence2.types b/tests/baselines/reference/genericTypeParameterEquivalence2.types index 51253764578..6ab297fe32c 100644 --- a/tests/baselines/reference/genericTypeParameterEquivalence2.types +++ b/tests/baselines/reference/genericTypeParameterEquivalence2.types @@ -105,7 +105,7 @@ function filter(f: (a: A) => boolean, ar: A[]): A[] { } ); return ret; ->ret : undefined[] +>ret : any[] } // length :: [a] -> Num diff --git a/tests/baselines/reference/globalThisCapture.types b/tests/baselines/reference/globalThisCapture.types index d17c899d1ed..063100ff78e 100644 --- a/tests/baselines/reference/globalThisCapture.types +++ b/tests/baselines/reference/globalThisCapture.types @@ -13,7 +13,7 @@ var parts = []; // Ensure that the generated code is correct parts[0]; ->parts[0] : undefined ->parts : undefined[] +>parts[0] : any +>parts : any[] >0 : 0 From 99e2219c4ef8c1f5580d873074aa17cdbedf2cac Mon Sep 17 00:00:00 2001 From: Kanchalai Tanglertsampan Date: Thu, 13 Oct 2016 15:09:26 -0700 Subject: [PATCH 57/74] Remove unused function --- src/compiler/core.ts | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index e8fadbff6e9..3ca4abc69da 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -23,21 +23,6 @@ namespace ts { // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. export const collator: { compare(a: string, b: string): number } = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; - /** - * Use this function instead of calling "String.prototype.localeCompre". This function will preform appropriate check to make sure that - * "typeof Intl" is correct as there are reported issues #11110 nad #11339. - * @param a reference string to compare - * @param b string to compare against - * @param locales string of BCP 47 language tag or an array of string of BCP 47 language tag - * @param options an object of Intl.CollatorOptions to specify localeCompare properties - */ - export function localeCompare(a: string, b: string, locales?: string | string[], options?: Intl.CollatorOptions): number | undefined { - if (collator && String.prototype.localeCompare) { - return a.localeCompare(b, locales, options); - } - return undefined; - } - export function createMap(template?: MapLike): Map { const map: Map = createObject(null); // tslint:disable-line:no-null-keyword From a6443e3e5a722bf7eb48b8b1f5c87b13efbc70c4 Mon Sep 17 00:00:00 2001 From: Zhengbo Li Date: Thu, 13 Oct 2016 15:39:09 -0700 Subject: [PATCH 58/74] Avoid watching non-existing directories and fix null-exception (#11601) * Avoid watching non-existing directories and fix null-exception * Add test * Move the fix to sys to cover tsc -w also --- src/compiler/sys.ts | 4 +++ .../unittests/tsserverProjectSystem.ts | 29 +++++++++++++++++++ src/server/editorServices.ts | 2 +- 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 7cf7d75bc02..1efa1e2b010 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -476,6 +476,10 @@ namespace ts { // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) let options: any; + if (!directoryExists(directoryName)) { + return; + } + if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 08e4bac7b2c..dc4cdd08520 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -2387,4 +2387,33 @@ namespace ts.projectSystem { assert.isTrue(errorResult.length === 0); }); }); + + describe("non-existing directories listed in config file input array", () => { + it("should be tolerated without crashing the server", () => { + const configFile = { + path: "/a/b/tsconfig.json", + content: `{ + "compilerOptions": {}, + "include": ["app/*", "test/**/*", "something"] + }` + }; + const file1 = { + path: "/a/b/file1.ts", + content: "let t = 10;" + }; + + const host = createServerHost([file1, configFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file1.path); + host.runQueuedTimeoutCallbacks(); + checkNumberOfConfiguredProjects(projectService, 1); + checkNumberOfInferredProjects(projectService, 1); + + const configuredProject = projectService.configuredProjects[0]; + assert.isTrue(configuredProject.getFileNames().length == 0); + + const inferredProject = projectService.inferredProjects[0]; + assert.isTrue(inferredProject.containsFile(file1.path)); + }); + }); } \ No newline at end of file diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 1a331c09320..91b9f90c88b 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -710,7 +710,7 @@ namespace ts.server { Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - errors.push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + (errors || (errors = [])).push(createCompilerDiagnostic(Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } From e9242b16811bba61daca883a940100210824d2fa Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 14 Oct 2016 01:23:14 +0200 Subject: [PATCH 59/74] fix typo in type definition (#11346) --- src/lib/es2015.core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/es2015.core.d.ts b/src/lib/es2015.core.d.ts index 5d570bb0866..356512ecf58 100644 --- a/src/lib/es2015.core.d.ts +++ b/src/lib/es2015.core.d.ts @@ -201,7 +201,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ From 7060f51fb2d7e439f22634ea352417de4f9d8e5a Mon Sep 17 00:00:00 2001 From: falsandtru Date: Fri, 14 Oct 2016 08:24:05 +0900 Subject: [PATCH 60/74] Fix the Function interface (#11269) (#11293) --- lib/lib.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 586b3675305..d8be920dc0a 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -260,6 +260,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of an object. */ + toString(): string; + prototype: any; readonly length: number; From dd26822cc0b4c2e6838d2523ab0b99f3a9b031b9 Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Thu, 13 Oct 2016 16:46:44 -0700 Subject: [PATCH 61/74] Merge pull request #11594 from Microsoft/vladima/fix-11590 return result from SetCompilerOptionsForInferredProject request --- src/server/session.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/server/session.ts b/src/server/session.ts index 111ba53a700..bd31277716f 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1590,7 +1590,8 @@ namespace ts.server { return this.requiredResponse(this.getDocumentHighlights(request.arguments, /*simplifiedResult*/ false)); }, [CommandNames.CompilerOptionsForInferredProjects]: (request: protocol.SetCompilerOptionsForInferredProjectsRequest) => { - return this.requiredResponse(this.setCompilerOptionsForInferredProjects(request.arguments)); + this.setCompilerOptionsForInferredProjects(request.arguments); + return this.requiredResponse(true); }, [CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => { return this.requiredResponse(this.getProjectInfo(request.arguments)); From 2920f8280452f38f2478c30976f6a5fa0c55ab96 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 16:54:09 -0700 Subject: [PATCH 62/74] Add error reporting for using `--noImplicitUseStrict` with `--options.alwaysStrict` --- src/compiler/program.ts | 4 +++ .../reference/alwaysStrictModule2.errors.txt | 22 ++++++++++++ .../reference/alwaysStrictModule2.js | 34 +++++++++++++++++++ ...alwaysStrictNoImplicitUseStrict.errors.txt | 2 ++ tests/cases/compiler/alwaysStrictModule2.ts | 16 +++++++++ 5 files changed, 78 insertions(+) create mode 100644 tests/baselines/reference/alwaysStrictModule2.errors.txt create mode 100644 tests/baselines/reference/alwaysStrictModule2.js create mode 100644 tests/cases/compiler/alwaysStrictModule2.ts diff --git a/src/compiler/program.ts b/src/compiler/program.ts index a52ffc85452..9404be2127e 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1473,6 +1473,10 @@ namespace ts { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } + const languageVersion = options.target || ScriptTarget.ES3; const outFile = options.outFile || options.out; diff --git a/tests/baselines/reference/alwaysStrictModule2.errors.txt b/tests/baselines/reference/alwaysStrictModule2.errors.txt new file mode 100644 index 00000000000..3980d24abfc --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule2.errors.txt @@ -0,0 +1,22 @@ +tests/cases/compiler/a.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. +tests/cases/compiler/b.ts(3,13): error TS1100: Invalid use of 'arguments' in strict mode. + + +==== tests/cases/compiler/a.ts (1 errors) ==== + + module M { + export function f() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } + +==== tests/cases/compiler/b.ts (1 errors) ==== + module M { + export function f2() { + var arguments = []; + ~~~~~~~~~ +!!! error TS1100: Invalid use of 'arguments' in strict mode. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/alwaysStrictModule2.js b/tests/baselines/reference/alwaysStrictModule2.js new file mode 100644 index 00000000000..54f179ff10b --- /dev/null +++ b/tests/baselines/reference/alwaysStrictModule2.js @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/alwaysStrictModule2.ts] //// + +//// [a.ts] + +module M { + export function f() { + var arguments = []; + } +} + +//// [b.ts] +module M { + export function f2() { + var arguments = []; + } +} + +//// [out.js] +"use strict"; +var M; +(function (M) { + function f() { + var arguments = []; + } + M.f = f; +})(M || (M = {})); +"use strict"; +var M; +(function (M) { + function f2() { + var arguments = []; + } + M.f2 = f2; +})(M || (M = {})); diff --git a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt index d677ec9b4cb..8df1d76e546 100644 --- a/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt +++ b/tests/baselines/reference/alwaysStrictNoImplicitUseStrict.errors.txt @@ -1,6 +1,8 @@ +error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'. tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts(4,13): error TS1100: Invalid use of 'arguments' in strict mode. +!!! error TS5053: Option 'noImplicitUseStrict' cannot be specified with option 'alwaysStrict'. ==== tests/cases/compiler/alwaysStrictNoImplicitUseStrict.ts (1 errors) ==== module M { diff --git a/tests/cases/compiler/alwaysStrictModule2.ts b/tests/cases/compiler/alwaysStrictModule2.ts new file mode 100644 index 00000000000..6afecb0e770 --- /dev/null +++ b/tests/cases/compiler/alwaysStrictModule2.ts @@ -0,0 +1,16 @@ +// @alwaysStrict: true +// @outFile: out.js + +// @fileName: a.ts +module M { + export function f() { + var arguments = []; + } +} + +// @fileName: b.ts +module M { + export function f2() { + var arguments = []; + } +} \ No newline at end of file From 80ef3486231000fab6d3a279e2ce9269ca5efedf Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 16:56:59 -0700 Subject: [PATCH 63/74] Add buildProtocol.js --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 4fff675801f..5e4bc0af5ea 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,7 @@ scripts/debug.bat scripts/run.bat scripts/word2md.js scripts/ior.js +scripts/buildProtocol.js scripts/*.js.map scripts/typings/ coverage/ From 97d40ab4329b4b0ef7083987762dc576c712198b Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 17:08:58 -0700 Subject: [PATCH 64/74] Update LKG --- lib/lib.d.ts | 406 +- lib/lib.dom.d.ts | 381 +- lib/lib.es2015.core.d.ts | 2 +- lib/lib.es5.d.ts | 24 + lib/lib.es6.d.ts | 405 +- lib/lib.webworker.d.ts | 12 +- lib/protocol.d.ts | 1848 +++++++ lib/tsc.js | 3575 ++++++------ lib/tsserver.js | 10126 +++++++++++++++++++++------------- lib/tsserverlibrary.d.ts | 2356 ++++++-- lib/tsserverlibrary.js | 9961 ++++++++++++++++++++------------- lib/typescript.d.ts | 480 +- lib/typescript.js | 4929 ++++++++++------- lib/typescriptServices.d.ts | 480 +- lib/typescriptServices.js | 4929 ++++++++++------- lib/typingsInstaller.js | 377 +- 16 files changed, 25228 insertions(+), 15063 deletions(-) create mode 100644 lib/protocol.d.ts diff --git a/lib/lib.d.ts b/lib/lib.d.ts index d8be920dc0a..87280fedba4 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -260,9 +260,6 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; - /** Returns a string representation of an object. */ - toString(): string; - prototype: any; readonly length: number; @@ -1219,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. @@ -11663,11 +11684,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -17239,7 +17261,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -17270,7 +17291,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -17297,13 +17318,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -17644,183 +17665,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -18750,6 +18771,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 4e45a38c17e..4c19c878064 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -7552,11 +7552,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -13128,7 +13129,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -13159,7 +13159,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13186,13 +13186,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13533,183 +13533,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -14638,4 +14638,5 @@ type ScrollBehavior = "auto" | "instant" | "smooth"; type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; -type MouseWheelEvent = WheelEvent; \ No newline at end of file +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; \ No newline at end of file diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 49a81a220ce..669c80944ec 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -217,7 +217,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 5df0d7d4068..d20c7d1e3a7 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1216,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index f6c7766ea9f..6067d810b44 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1216,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. @@ -4325,7 +4349,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ @@ -13361,11 +13385,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -18937,7 +18962,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -18968,7 +18992,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -18995,13 +19019,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -19342,183 +19366,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -20448,6 +20472,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 5b35d820dfe..6cb14c5b184 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -744,7 +744,7 @@ declare var Worker: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -770,13 +770,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts new file mode 100644 index 00000000000..2b57b5de644 --- /dev/null +++ b/lib/protocol.d.ts @@ -0,0 +1,1848 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type Implementation = "implementation"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type Navto = "navto"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type References = "references"; + type Reload = "reload"; + type Rename = "rename"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: string; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * Contains error message if success === false. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes?: number[]; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and character offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + /** + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + * Kind is taken from HighlightSpanKind type. + */ + interface HighlightSpan extends TextSpan { + kind: string; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + interface RenameInfo { + /** + * True if item can be renamed. + */ + canRename: boolean; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicity. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * Explicitly specified typing options for the project + */ + typingOptions?: TypingOptions; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + interface ExternalProjectCompilerOptions extends CompilerOptions { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * Contains information about current project version + */ + interface ProjectVersionInfo { + /** + * Project name + */ + projectName: string; + /** + * true if project is inferred or false if project is external or configured + */ + isInferred: boolean; + /** + * Project version + */ + version: number; + /** + * Current set of compiler options for project + */ + options: CompilerOptions; + } + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + } + /** + * Describes set of files in the project. + * info might be omitted in case of inferred projects + * if files is set - then this is the entire set of files in the project + * if changes is set - then this is the set of changes that should be applied to existing project + * otherwise - assume that nothing is changed + */ + interface ProjectFiles { + /** + * Information abount project verison + */ + info?: ProjectVersionInfo; + /** + * List of files in project (might be omitted if current state of project can be computed using only information from 'changes') + */ + files?: string[]; + /** + * Set of changes in project (omitted if the entire set of files in project should be replaced) + */ + changes?: ProjectChanges; + } + /** + * Combines project information with project level errors. + */ + interface ProjectFilesWithDiagnostics extends ProjectFiles { + /** + * List of errors in project + */ + projectErrors: DiagnosticWithLinePosition[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; + } + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Arguments to SynchronizeProjectListRequest + */ + interface SynchronizeProjectListRequestArgs { + /** + * List of last known projects + */ + knownProjects: protocol.ProjectVersionInfo[]; + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: string[]; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. If present, + * this span should be used instead of the default one. + */ + replacementSpan?: TextSpan; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The error code of the diagnostic message. + */ + code?: number; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * exact, substring, or prefix. + */ + matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The file in which the symbol is found. + */ + file: string; + /** + * The location within file at which the symbol is found. + */ + start: Location; + /** + * One past the last character of the symbol. + */ + end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: string; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; + } + + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } + + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + } + + interface TypingOptions { + enableAutoDiscovery?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind; + moduleResolution?: ModuleResolutionKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + traceResolution?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + + enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + + enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES6 = 5, + ES2015 = 5, + } + + enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + + enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + + interface MapLike { + [index: string]: T; + } + + enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + ES2015 = 2, + Latest = 2, + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; + + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } +} \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index aef54c957e6..7f46b1dddb4 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -145,6 +145,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -152,6 +153,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -528,16 +536,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -771,6 +785,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1007,10 +1071,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1384,6 +1483,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1475,7 +1582,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1488,9 +1594,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1508,30 +1614,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1562,6 +1645,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1755,8 +1896,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1881,6 +2028,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1992,19 +2142,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2329,7 +2503,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2490,7 +2664,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2723,6 +2897,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2747,6 +2923,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2776,7 +2953,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3686,7 +3870,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4810,10 +4994,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5061,6 +5245,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -5376,10 +5566,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -5977,14 +6163,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -6420,28 +6602,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -6458,7 +6628,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -6485,7 +6655,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -6501,7 +6671,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -6528,18 +6698,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -6547,7 +6718,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -6584,13 +6755,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -6904,14 +7094,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -7002,12 +7184,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7108,7 +7284,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -7177,7 +7353,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -7277,15 +7453,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -7424,12 +7601,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -7995,7 +8172,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -8027,7 +8204,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -8314,7 +8491,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -8322,7 +8499,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -8426,7 +8603,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -8519,7 +8696,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -9419,13 +9596,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -9539,8 +9716,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -9767,7 +9944,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -9779,6 +9956,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -10018,17 +10217,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11138,7 +11432,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -11466,7 +11760,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -11482,7 +11776,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -11493,8 +11787,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -13842,7 +14143,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15277,7 +15578,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -15307,6 +15608,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -15425,11 +15734,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -15494,7 +15809,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -15949,7 +16264,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -16082,7 +16399,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -16181,9 +16498,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -16715,7 +17035,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -16912,6 +17232,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -17050,8 +17373,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -17153,7 +17475,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -17198,7 +17520,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -17215,7 +17537,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -17456,6 +17778,560 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; @@ -17551,6 +18427,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -18108,7 +18985,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -18526,6 +19403,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -19010,9 +19888,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -19047,7 +19925,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -19064,7 +19942,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -19134,12 +20012,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -19528,12 +20406,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -19791,6 +20669,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -19813,6 +20695,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -19884,7 +20771,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -20353,7 +21240,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -20886,13 +21774,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -20931,6 +21830,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -20949,20 +21849,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -20973,22 +21873,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -20999,6 +21897,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -21371,7 +22273,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -21655,7 +22557,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -21754,7 +22657,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -22729,7 +23649,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23934,17 +24855,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -24221,6 +25135,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -24235,7 +25166,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -24297,10 +25230,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -24486,12 +25422,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -24529,7 +25465,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -24656,7 +25593,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -24779,14 +25716,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -24871,7 +25820,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -24936,7 +25885,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -25596,7 +26545,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -25647,7 +26597,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -26042,7 +26995,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -26083,7 +27036,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -26308,19 +27261,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -27223,7 +28176,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -27373,7 +28328,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28316,9 +29271,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -28529,7 +29484,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -28555,6 +29510,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -28568,7 +29524,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -29271,14 +30227,14 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { + var _loop_1 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { if (local.valueDeclaration && local.valueDeclaration.kind === 142) { var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -29293,9 +30249,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -29433,6 +30386,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -29536,6 +30492,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -29549,12 +30508,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -29572,7 +30531,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -29580,7 +30539,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -29955,7 +30914,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -30674,9 +31638,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -30915,9 +31881,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -31004,7 +31972,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -31489,6 +32458,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -31912,9 +32884,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -32023,9 +32995,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -32585,8 +33557,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -32695,8 +33667,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 || - name_24.kind === 140) { + if (name_24.kind === 140) { checkGrammarComputedPropertyName(name_24); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { @@ -32852,17 +33823,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -33222,8 +34184,7 @@ var ts; { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], - _a - )); + _a)); function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } @@ -33697,7 +34658,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -33721,7 +34682,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -33731,7 +34692,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -33955,10 +34916,10 @@ var ts; ? function (message) { return Debug.assert(false, message || "Node not optional."); } : function (message) { }; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."); }); } + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } : function (node, message) { }; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."); }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } : function (node, test, message) { }; function getFunctionName(func) { if (typeof func !== "function") { @@ -34006,7 +34967,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -34023,7 +34984,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -34047,7 +35008,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -34087,7 +35048,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -34132,8 +35093,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, undefined); } } @@ -34248,7 +35209,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -34257,10 +35218,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -34268,12 +35232,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -34427,11 +35398,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -34453,7 +35435,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -34483,7 +35465,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -34525,7 +35507,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -34546,7 +35528,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -34607,7 +35589,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -34626,9 +35608,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -34649,8 +35631,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -34660,8 +35642,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -34802,7 +35784,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -34820,12 +35802,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -34839,7 +35821,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -35004,10 +35986,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -35128,8 +36133,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -35141,8 +36146,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -35151,8 +36156,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -35247,11 +36252,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -35261,14 +36266,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -35317,12 +36322,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -35331,6 +36337,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -35342,7 +36349,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -35381,18 +36388,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -35402,13 +36423,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -35419,6 +36440,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -35435,15 +36457,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -35470,9 +36494,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -35495,7 +36520,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -35524,9 +36549,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -35547,7 +36572,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -35556,7 +36581,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -35573,8 +36598,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -35582,9 +36607,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -35646,7 +36671,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -35658,13 +36683,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -35674,14 +36699,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, node); + return ts.createPropertyAssignment(name_30, initializer, node); } - return ts.createPropertyAssignment(name_29, exportedName, node); + return ts.createPropertyAssignment(name_30, exportedName, node); } } return node; @@ -35690,16 +36715,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -35716,8 +36740,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -35726,7 +36750,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -35754,23 +36778,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -35794,6 +36843,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -35905,7 +36957,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -35934,6 +36986,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -35966,12 +37021,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -36215,11 +37270,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_30 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_30, undefined, node.parameters, undefined, node.body, node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_31, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -36230,13 +37285,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -36390,19 +37445,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -36436,7 +37491,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -36541,7 +37596,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -36574,7 +37629,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -36674,7 +37729,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -36688,9 +37743,8 @@ var ts; _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, - _a - )); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -36715,6 +37769,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -36740,7 +37797,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -36751,7 +37808,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -36778,7 +37835,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -36786,12 +37843,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -36854,7 +37911,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -36942,16 +37999,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -36969,7 +38026,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -37086,25 +38143,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -37145,7 +38202,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -37163,11 +38220,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -37182,7 +38239,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -37194,7 +38251,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -37206,12 +38263,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), node); + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), node); } } } @@ -37233,7 +38290,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -37261,7 +38318,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -37288,6 +38345,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37446,12 +38506,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -37733,6 +38793,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37797,10 +38860,9 @@ var ts; _a[4] = "yield", _a[5] = "yield*", _a[7] = "endfinally", - _a - )); + _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -37834,6 +38896,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -37940,7 +39005,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -37961,7 +39026,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -37992,6 +39057,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -38004,6 +39070,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -38022,6 +39089,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -38037,7 +39105,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -38705,9 +39773,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -38724,11 +39792,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -39122,7 +40190,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -39391,7 +40459,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -39411,6 +40479,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -39580,7 +40651,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -39717,15 +40788,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -39740,14 +40811,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -39758,7 +40829,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -39769,33 +40844,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -39820,34 +40960,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -39859,11 +40999,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -39871,21 +41011,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -39915,43 +41058,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -39970,7 +41113,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -40027,7 +41170,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -40038,10 +41181,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -40082,7 +41225,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -40105,13 +41248,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -40206,7 +41349,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -40241,14 +41384,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -40266,7 +41409,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -40355,7 +41498,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -40365,7 +41508,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -40393,8 +41536,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -40403,8 +41546,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -40582,7 +41725,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -40595,13 +41738,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -40721,12 +41883,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -40748,9 +41910,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -40800,7 +41962,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -40811,7 +41973,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -40819,7 +41981,7 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -40868,8 +42030,7 @@ var ts; _a[ts.ModuleKind.CommonJS] = ts.transformModule, _a[ts.ModuleKind.UMD] = ts.transformModule, _a[ts.ModuleKind.None] = ts.transformModule, - _a - )); + _a)); function getTransformers(compilerOptions) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -40888,18 +42049,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -40908,47 +42061,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -40960,75 +42090,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -41081,93 +42173,10 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -41175,42 +42184,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -41250,6 +42255,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -41257,38 +42265,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -41319,7 +42295,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -41344,84 +42320,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -41437,6 +42397,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -41449,6 +42412,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -41458,46 +42424,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -41547,20 +42474,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -41589,10 +42518,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -41614,7 +42545,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -41623,8 +42554,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -41732,16 +42665,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -41793,11 +42716,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -41833,7 +42756,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42018,7 +42941,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42030,7 +42953,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42223,7 +43146,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -42629,7 +43552,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43197,14 +44120,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43221,8 +44144,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43248,7 +44171,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -43256,7 +44181,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -43269,11 +44194,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -43290,14 +44215,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -43306,16 +44234,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -43331,8 +44263,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -43368,73 +44300,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -43461,7 +44381,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -43637,17 +44558,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -43663,7 +44579,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -43741,7 +44658,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -43956,7 +44873,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -43969,21 +44886,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -43994,15 +44908,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -44157,7 +45070,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -44332,11 +45245,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -44368,7 +45281,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -44423,7 +45336,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -44485,7 +45398,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -44682,8 +45595,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -44731,7 +45644,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -44837,31 +45750,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -44961,7 +45849,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -45003,27 +45891,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -45162,17 +46035,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -45382,581 +46250,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -46058,7 +46351,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -46126,33 +46419,6 @@ var ts; } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -46178,7 +46444,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -46186,15 +46452,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -46236,7 +46502,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -46283,6 +46550,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -46383,16 +46651,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -46413,7 +46684,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -46928,7 +47199,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -46940,7 +47210,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -46954,8 +47224,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -46966,8 +47236,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -47010,7 +47280,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -47021,7 +47291,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -47060,6 +47330,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -47136,11 +47409,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -47563,6 +47838,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -47764,10 +48044,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -47901,13 +48182,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -47916,7 +48199,7 @@ var ts; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = (extendedConfigPath + ".json"); + extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return; @@ -47985,6 +48268,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -47998,7 +48292,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -48294,8 +48590,7 @@ var ts; _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, - _a - )); + _a)); function formatAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } diff --git a/lib/tsserver.js b/lib/tsserver.js index 8bb071cf4a1..f5437988c1a 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -150,6 +149,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,6 +157,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -533,16 +540,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -776,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1012,10 +1075,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1389,6 +1487,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1480,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1649,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1886,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1997,19 +2146,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2334,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2495,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2728,6 +2901,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2752,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2781,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3691,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4334,11 +4517,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4761,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -4962,10 +5152,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5099,13 +5290,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -5183,6 +5376,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -5196,7 +5400,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -5395,6 +5601,937 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_7 in packageNameToTypingLocation) { + if (name_7 in inferredTypings && !inferredTypings[name_7]) { + inferredTypings[name_7] = packageNameToTypingLocation[name_7]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(server.LogLevel || (server.LogLevel = {})); + var LogLevel = server.LogLevel; + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typingOptions, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(), + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function throwLanguageServiceIsDisabledError() { + throw new Error("LanguageService is disabled"); + } + server.nullLanguageService = { + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError, + getCompletionEntrySymbol: throwLanguageServiceIsDisabledError, + getImplementationAtPosition: throwLanguageServiceIsDisabledError, + getSourceFile: throwLanguageServiceIsDisabledError, + getCodeFixesAtPosition: throwLanguageServiceIsDisabledError + }; + server.nullLanguageServiceHost = { + setCompilationSettings: function () { return undefined; }, + notifyFileRemoved: function () { return undefined; } + }; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_1 = ts.getDirectoryPath(currentDirectory); + if (parent_1 === currentDirectory) { + break; + } + currentDirectory = parent_1; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5877,10 +7014,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5943,23 +7080,23 @@ var ts; case 139: case 172: case 97: - var parent_1 = node.parent; - if (parent_1.kind === 158) { + var parent_2 = node.parent; + if (parent_2.kind === 158) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (154 <= parent_2.kind && parent_2.kind <= 166) { return true; } - switch (parent_1.kind) { + switch (parent_2.kind) { case 194: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); case 141: - return node === parent_1.constraint; + return node === parent_2.constraint; case 145: case 144: case 142: case 218: - return node === parent_1.type; + return node === parent_2.type; case 220: case 179: case 180: @@ -5968,16 +7105,16 @@ var ts; case 146: case 149: case 150: - return node === parent_1.type; + return node === parent_2.type; case 151: case 152: case 153: - return node === parent_1.type; + return node === parent_2.type; case 177: - return node === parent_1.type; + return node === parent_2.type; case 174: case 175: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + return parent_2.typeArguments && ts.indexOf(parent_2.typeArguments, node) >= 0; case 176: return false; } @@ -6030,9 +7167,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_7 = node.name; - if (name_7 && name_7.kind === 140) { - traverse(name_7.expression); + var name_8 = node.name; + if (name_8 && name_8.kind === 140) { + traverse(name_8.expression); return; } } @@ -6128,6 +7265,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6238,13 +7381,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 179 || func.kind === 180) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 178) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent_3 = func.parent; + while (parent_3.kind === 178) { + prev = parent_3; + parent_3 = parent_3.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { - return parent_2; + if (parent_3.kind === 174 && parent_3.expression === prev) { + return parent_3; } } } @@ -6390,8 +7533,8 @@ var ts; case 8: case 9: case 97: - var parent_3 = node.parent; - switch (parent_3.kind) { + var parent_4 = node.parent; + switch (parent_4.kind) { case 218: case 142: case 145: @@ -6399,7 +7542,7 @@ var ts; case 255: case 253: case 169: - return parent_3.initializer === node; + return parent_4.initializer === node; case 202: case 203: case 204: @@ -6410,32 +7553,32 @@ var ts; case 249: case 215: case 213: - return parent_3.expression === node; + return parent_4.expression === node; case 206: - var forStatement = parent_3; + var forStatement = parent_4; return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || forStatement.condition === node || forStatement.incrementor === node; case 207: case 208: - var forInStatement = parent_3; + var forInStatement = parent_4; return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || forInStatement.expression === node; case 177: case 195: - return node === parent_3.expression; + return node === parent_4.expression; case 197: - return node === parent_3.expression; + return node === parent_4.expression; case 140: - return node === parent_3.expression; + return node === parent_4.expression; case 143: case 248: case 247: return true; case 194: - return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); + return parent_4.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_4); default: - if (isPartOfExpression(parent_3)) { + if (isPartOfExpression(parent_4)) { return true; } } @@ -6443,10 +7586,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6650,17 +7789,17 @@ var ts; node.parent && node.parent.kind === 225) { result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var parent_5 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_5 && parent_5.parent && + parent_5.kind === 187 && + parent_5.operatorToken.kind === 56 && + parent_5.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5.parent, checkParentVariableStatement, getDocs, getTags)); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; + var isPropertyAssignmentExpression = parent_5 && parent_5.kind === 253; if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5, checkParentVariableStatement, getDocs, getTags)); } if (node.kind === 142) { var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); @@ -6693,8 +7832,8 @@ var ts; } } else if (param.name.kind === 69) { - var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + var name_9 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; }); if (paramTags) { return paramTags; } @@ -6765,20 +7904,20 @@ var ts; node = node.parent; } while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; + var parent_6 = node.parent; + if (parent_6.kind === 170 || parent_6.kind === 191) { + node = parent_6; continue; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; + if (parent_6.kind === 253 || parent_6.kind === 254) { + node = parent_6.parent; continue; } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + return parent_6.kind === 187 && + isAssignmentOperator(parent_6.operatorToken.kind) && + parent_6.left === node || + (parent_6.kind === 207 || parent_6.kind === 208) && + parent_6.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; @@ -7044,14 +8183,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -7487,28 +8622,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -7525,7 +8648,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -7552,7 +8675,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -7568,7 +8691,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7595,18 +8718,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +8738,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7651,13 +8775,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7971,14 +9114,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8069,12 +9204,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8163,9 +9292,9 @@ var ts; if (syntaxKindCache[kind]) { return syntaxKindCache[kind]; } - for (var name_9 in syntaxKindEnum) { - if (syntaxKindEnum[name_9] === kind) { - return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + for (var name_10 in syntaxKindEnum) { + if (syntaxKindEnum[name_10] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")"; } } } @@ -8175,7 +9304,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,7 +9373,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -8281,8 +9410,8 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + var name_11 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier); } } break; @@ -8344,15 +9473,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -8491,12 +9621,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -8827,7 +9957,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; @@ -9062,7 +10191,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9094,7 +10223,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9381,7 +10510,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,7 +10518,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -9493,7 +10622,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -9586,7 +10715,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -10486,13 +11615,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -10606,8 +11735,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -10834,7 +11963,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -10846,6 +11975,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -11085,17 +12236,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11122,8 +12368,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_11 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name_12 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } if (node.kind === 230 && node.importClause) { return getGeneratedNameForNode(node); @@ -12205,7 +13451,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -12533,7 +13779,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -12549,7 +13795,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -12560,8 +13806,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14822,8 +16075,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -14909,7 +16162,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15847,8 +17100,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15934,14 +17187,14 @@ var ts; } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(141, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 24) { @@ -16344,7 +17597,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +17627,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16492,11 +17753,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16561,7 +17828,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -17016,7 +18283,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17149,7 +18418,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -17248,9 +18517,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -17782,7 +19054,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -17794,12 +19066,12 @@ var ts; return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_7 = node.parent; + if (!ts.isExternalModule(parent_7)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_7.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17979,6 +19251,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -18117,8 +19392,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -18220,7 +19494,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18265,7 +19539,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -18282,7 +19556,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18618,6 +19892,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -19175,7 +20450,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -19335,28 +20610,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -19593,6 +20868,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -20077,9 +21353,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,7 +21390,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -20131,7 +21407,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -20201,12 +21477,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -20595,12 +21871,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -20787,19 +22063,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { + var name_17 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_17)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_16); + var text = getTextOfPropertyName(name_17); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17)); return unknownType; } } @@ -20858,6 +22134,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -20880,6 +22160,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -20951,7 +22236,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -21420,7 +22705,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21953,13 +23239,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -21998,6 +23295,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22016,20 +23314,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +23338,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,6 +23362,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -22438,7 +23738,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22722,7 +24022,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22821,7 +24122,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -23796,7 +25114,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -25001,17 +26320,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25288,6 +26600,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25302,7 +26631,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -25364,10 +26695,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -25553,12 +26887,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25596,7 +26930,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25723,7 +27058,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -25846,14 +27181,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -25938,7 +27285,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -26003,7 +27350,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -26222,11 +27569,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_18 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_18)) { + var text = getTextOfPropertyName(name_18); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26663,7 +28010,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -26714,7 +28062,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -27109,7 +28460,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -27150,7 +28501,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -27266,15 +28617,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); + var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_19 !== undefined) { + var prop = getPropertyOfType(objectType, name_19); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol)); return unknownType; } } @@ -27375,19 +28726,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -28290,7 +29641,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28440,7 +29793,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28690,14 +30043,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + var name_20 = property.name; + if (name_20.kind === 140) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -28712,7 +30065,7 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } else { @@ -29361,9 +30714,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29383,9 +30736,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -29395,15 +30748,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 69 && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 168 || + name_22.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -29596,7 +30949,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29622,6 +30975,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29635,7 +30989,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -30345,7 +31699,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -30360,9 +31714,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -30500,6 +31851,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -30547,8 +31901,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -30603,6 +31957,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -30616,12 +31973,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24)); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -30639,7 +31996,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -30647,7 +32004,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -31022,7 +32379,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -31741,9 +33103,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31818,9 +33182,9 @@ var ts; break; case 169: case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -31982,9 +33346,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32071,7 +33437,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32556,6 +33923,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -32670,9 +34040,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -32979,9 +34349,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33090,9 +34460,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -33652,8 +35022,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33761,10 +35131,9 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + var name_27 = prop.name; + if (name_27.kind === 140) { + checkGrammarComputedPropertyName(name_27); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -33780,8 +35149,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (name_27.kind === 8) { + checkGrammarNumericLiteral(name_27); } currentKind = Property; } @@ -33797,7 +35166,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27); if (effectiveName === undefined) { continue; } @@ -33807,18 +35176,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33831,12 +35200,12 @@ var ts; continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_28 = jsxAttr.name; + if (!seen[name_28.text]) { + seen[name_28.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -33919,17 +35288,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -34763,7 +36123,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -34787,7 +36147,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -34797,7 +36157,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -35072,7 +36432,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -35089,7 +36449,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -35113,7 +36473,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -35153,7 +36513,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -35197,10 +36557,10 @@ var ts; emitArrayLiteralAssignment(target, value, location); } else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); + var name_29 = ts.getMutableClone(target); + ts.setSourceMapRange(name_29, target); + ts.setCommentRange(name_29, target); + emitAssignment(name_29, value, location, undefined); } } function emitObjectLiteralAssignment(target, value, location) { @@ -35314,7 +36674,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,10 +36683,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -35334,12 +36697,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -35493,11 +36863,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -35519,7 +36900,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -35549,7 +36930,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -35591,7 +36972,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -35612,7 +36993,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -35673,7 +37054,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +37073,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35715,8 +37096,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -35726,8 +37107,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -35868,7 +37249,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -35886,12 +37267,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -35905,7 +37286,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -36070,10 +37451,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -36117,14 +37521,14 @@ var ts; function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + var name_30 = ts.getMutableClone(node); + name_30.flags &= ~8; + name_30.original = undefined; + name_30.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30); } - return name_29; + return name_30; case 139: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -36194,8 +37598,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -36207,8 +37611,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36217,8 +37621,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36313,11 +37717,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -36327,14 +37731,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -36383,12 +37787,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -36397,6 +37802,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36408,7 +37814,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -36447,18 +37853,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_31 = node.symbol && node.symbol.name; + if (name_31) { + return currentScopeFirstDeclarationsOfName[name_31] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -36468,13 +37888,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -36485,6 +37905,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36501,15 +37922,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -36536,9 +37959,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -36561,7 +37985,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -36590,9 +38014,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -36613,7 +38037,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -36622,7 +38046,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -36639,8 +38063,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_32 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -36648,9 +38072,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); + ts.setEmitFlags(name_32, emitFlags); } - return name_30; + return name_32; } else { return ts.getGeneratedNameForNode(node); @@ -36712,7 +38136,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -36724,13 +38148,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,14 +38164,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_33 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_33); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_33, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_33, exportedName, node); } } return node; @@ -36756,16 +38180,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -36782,8 +38205,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -36792,7 +38215,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -36820,23 +38243,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -36860,6 +38308,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37018,12 +38469,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_34 = node.tagName; + if (ts.isIdentifier(name_34) && ts.isIntrinsicJsxName(name_34.text)) { + return ts.createLiteral(name_34.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_34); } } } @@ -37305,6 +38756,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37364,7 +38818,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37384,6 +38838,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -37553,7 +39010,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -37690,15 +39147,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37713,14 +39170,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -37731,7 +39188,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -37742,33 +39203,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -37793,34 +39319,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_35 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_35)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_35, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_35, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -37832,11 +39358,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -37844,21 +39370,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -37888,43 +39417,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37943,7 +39472,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -38000,7 +39529,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -38011,10 +39540,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -38055,7 +39584,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -38078,13 +39607,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38179,7 +39708,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -38214,14 +39743,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38239,7 +39768,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38328,7 +39857,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -38338,7 +39867,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -38366,8 +39895,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +39905,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38555,7 +40084,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,13 +40097,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -38694,12 +40242,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -38721,9 +40269,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38773,7 +40321,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -38783,8 +40331,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_36 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -38792,9 +40340,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); + ts.setEmitFlags(name_36, emitFlags); } - return name_35; + return name_36; } return ts.getGeneratedNameForNode(node); } @@ -38842,7 +40390,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,6 +40424,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -38982,7 +40533,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39003,7 +40554,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39034,6 +40585,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +40598,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39064,6 +40617,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39079,7 +40633,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39747,9 +41301,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,11 +41320,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_8 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_8, node); + ts.setCommentRange(clone_8, node); return clone_8; } } @@ -40164,7 +41718,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -40439,7 +41993,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40464,6 +42018,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -40489,7 +42046,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -40500,7 +42057,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -40527,7 +42084,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -40535,12 +42092,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -40603,7 +42160,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -40691,16 +42248,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); + var name_38 = names_1[_i]; + addExportMemberAssignments(statements, name_38); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); + var name_39 = node.name; + if (ts.isIdentifier(name_39)) { + names.push(name_39); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -40718,7 +42275,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -40835,25 +42392,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40894,7 +42451,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40912,11 +42469,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -40931,7 +42488,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -40943,7 +42500,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -40955,12 +42512,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + var name_40 = declaration.propertyName || declaration.name; + if (name_40.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); } } } @@ -40982,7 +42539,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -41010,7 +42567,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -41032,7 +42589,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -41061,6 +42618,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -41093,12 +42653,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -41342,11 +42902,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + var name_41 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); + recordExportName(name_41); } ts.setOriginalNode(newNode, node); node = newNode; @@ -41357,13 +42917,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); + var name_42 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); + hoistVariableDeclaration(name_42); } return [ node, - createExportStatement(name_41, name_41) + createExportStatement(name_42, name_42) ]; } return node; @@ -41517,19 +43077,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -41563,7 +43123,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -41668,7 +43228,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -41701,7 +43261,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -41801,7 +43361,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -41815,6 +43375,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -41951,18 +43514,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -41971,47 +43526,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,75 +43555,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -42144,54 +43638,6 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +43648,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42242,7 +43688,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42427,7 +43873,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,7 +43885,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42612,9 +44058,9 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_43 = baseName + "_" + count; + if (!(name_43 in currentIdentifiers)) { + return name_43; } } } @@ -42632,7 +44078,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -43038,7 +44484,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43606,14 +45052,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43630,8 +45076,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +45103,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +45110,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +45181,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +45191,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +45221,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +45246,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,6 +45323,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -43973,6 +45338,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +45350,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44071,20 +45400,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -44113,10 +45444,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,7 +45471,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -44147,8 +45480,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44256,16 +45591,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,7 +45636,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -44319,7 +45646,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -44332,11 +45659,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44353,14 +45680,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +45699,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44394,8 +45728,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -44431,73 +45765,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -44524,7 +45846,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -44700,17 +46023,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -44726,7 +46044,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -44804,7 +46123,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -45019,7 +46338,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +46351,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45057,15 +46373,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45220,7 +46535,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -45395,11 +46710,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -45431,7 +46746,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -45486,7 +46801,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45548,7 +46863,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45745,8 +47060,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45794,7 +47109,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -45900,31 +47215,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +47314,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +47356,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46225,17 +47500,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +47525,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_44 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_44)) { tempFlags |= flags; - return name_43; + return name_44; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_45 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_45)) { + return name_45; } } } @@ -46445,581 +47715,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +47816,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47181,41 +47876,14 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + var name_46 = names_2[_i]; + var result = name_46 in cache + ? cache[name_46] + : cache[name_46] = loader(name_46, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47241,7 +47909,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,15 +47917,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -47299,7 +47967,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -47346,6 +48015,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -47446,16 +48116,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +48149,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47991,7 +48664,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -48003,7 +48675,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48017,8 +48689,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +48701,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +48745,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +48756,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +48795,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48685,7 +49360,7 @@ var ts; case 97: return true; case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142; default: return false; } @@ -49258,7 +49933,6 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; @@ -49481,7 +50155,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +50166,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -50701,8 +51378,7 @@ var ts; return; case 142: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,13 +51419,13 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -50773,17 +51449,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_47 in nameTable) { + if (nameTable[name_47] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_47]) { + uniqueNames[name_47] = name_47; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50833,7 +51509,9 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 253 && + node.parent.parent.kind === 171 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { @@ -50856,7 +51534,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -50872,7 +51550,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +51560,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +51571,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50934,6 +51612,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +51643,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +51807,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +51820,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51347,7 +52028,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51399,6 +52080,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51429,10 +52111,12 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 || node.kind === 139 || node.kind === 172) { @@ -51483,6 +52167,7 @@ var ts; var attrsType = void 0; if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -51842,8 +52527,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_48 = element.propertyName || element.name; + existingImportsOrExports[name_48.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51927,7 +52612,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +59140,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58605,7 +59169,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +59179,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +59190,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +59228,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58842,7 +59406,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58940,11 +59504,116 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 174) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(69, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -59167,15 +59836,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -59249,7 +59919,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59406,6 +60076,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +60114,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59583,7 +60281,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +60318,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59878,12 +60583,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +60599,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59957,14 +60662,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60020,34 +60737,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60159,6 +60902,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +60912,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60233,43 +60978,2344 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { + if (isOpen === void 0) { isOpen = false; } + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.isOpen = isOpen; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = server.ScriptVersionCache.fromString(host, content); + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); } - return spaceCache[n]; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + ts.Debug.assert(this.containingProjects.length !== 0); + return this.containingProjects[0]; + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.svc.latestVersion().toString(); + }; + ScriptInfo.prototype.reload = function (script) { + this.svc.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.snap(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function () { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.svc.reloadFromFile(this.fileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + var index = this.snap().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (primaryResult.resolvedModule) { + if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { + return primaryResult; + } + } + var secondaryLookupFailedLookupLocations = []; + var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; + if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { + var traceEnabled = ts.isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; + var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); + if (resolvedName) { + return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); + } + } + if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { + primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); + } + return primaryResult; + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_52 = names_3[_i]; + var resolution = newResolutions[name_52]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this); + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) { + return false; + } + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: function () { }, + attach: function (projectService) { }, + onProjectClosed: function (p) { }, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typingOptionsChanged(opt1, opt2) { + return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function toTypingsArray(arr) { + arr.sort(); + return arr; + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + typings: result, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typingOptions); } return result; + }; + TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions.enableAutoDiscovery) { + return; + } + this.installer.enqueueInstallTypingsRequest(project, typingOptions); + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typingOptions: typingOptions, + typings: toTypingsArray(newTypings), + poisoned: false + }; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var crypto = require("crypto"); + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 225 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return crypto.createHash("md5") + .update(text) + .digest("base64"); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + this.fileInfos = ts.createFileMap(); + } + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.fileInfos.get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.fileInfos.getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.fileInfos.set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.fileInfos.remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.fileInfos.forEachValue(function (path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(server.ProjectKind || (server.ProjectKind = {})); + var ProjectKind = server.ProjectKind; + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var Project = (function () { + function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.languageServiceEnabled = languageServiceEnabled; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + if (languageServiceEnabled) { + this.enableLanguageService(); + } + else { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); + this.lsHost = lsHost; + this.languageServiceEnabled = true; + }; + Project.prototype.disableLanguageService = function () { + this.languageService = server.nullLanguageService; + this.lsHost = server.nullLanguageServiceHost; + this.languageServiceEnabled = false; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + result.push(f.fileName); + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function () { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isOpen || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.updateGraph = function () { + if (!this.languageServiceEnabled) { + return true; + } + var hasChanges = this.updateGraphWorker(); + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + this.builder.onProjectUpdateGraph(); + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + this.compilerOptions = compilerOptions; + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions() + }; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.directoriesWatchedForTsconfig = []; + _this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); + InferredProject.NextId++; + return _this; + } + InferredProject.prototype.getProjectName = function () { + return this.inferredProjectName; + }; + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypingOptions = function () { + return { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.NextId = 1; + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.configFileName = configFileName; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + return _this; + } + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.configFileName); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { + this.typingOptions = newTypingOptions; + }; + ConfiguredProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ConfiguredProject.prototype.getProjectName = function () { + return this.configFileName; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.configFileName); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.configFileName); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); + }; + ExternalProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { + if (!newTypingOptions) { + newTypingOptions = { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypingOptions.enableAutoDiscovery === undefined) { + newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); + } + if (!newTypingOptions.include) { + newTypingOptions.include = []; + } + if (!newTypingOptions.exclude) { + newTypingOptions.exclude = []; + } + } + this.typingOptions = newTypingOptions; + }; + ExternalProject.prototype.getProjectName = function () { + return this.externalProjectName; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (_) { return false; } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return x.scriptKind; }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host" + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case "set": + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); + project.updateGraph(); + break; + case "invalidate": + this.typingsCache.invalidateCachedTypingsForProject(project); + break; + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(projectCompilerOptions); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isOpen)) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isOpen) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + this.logger.info("Config file changed: " + project.configFileName); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.reloadFromFile(); + server.removeItemFromSet(this.openFiles, info); + info.isOpen = false; + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + return findProjectByName(configFileName, this.configuredProjects); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typingOptions: parsedCommandLine.typingOptions, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypingOptions(typingOptions); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isOpen && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypingOptions(newTypingOptions); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.configFileName)) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + if (!project.languageServiceEnabled) { + project.enableLanguageService(); + } + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); + } + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (!info.isOpen && !hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + if (info) { + if (fileContent !== undefined) { + info.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(args.formatOptions); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.logger.info("Format host information updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var _a = this.findContainingExternalProject(fileName) + ? {} + : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_3 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_3(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { + var file = changedFiles_1[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProject = function (proj) { + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); + } + this.refreshInferredProjects(); + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +63334,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +63350,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,73 +63361,166 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { + var proj = _a[_i]; + _this.projectService.openExternalProject(proj); + } + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -60397,34 +63539,81 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function (request) { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,72 +63630,94 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function (request) { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; case "configFileDiag": @@ -60515,26 +63726,23 @@ var ts; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60559,7 +63767,7 @@ var ts; }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -60576,17 +63784,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +63799,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +63809,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +63827,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +63838,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,78 +63854,133 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var p = projects_4[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -60732,115 +63989,142 @@ var ts; }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +64145,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; - var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +64200,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options || this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +64353,106 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +64461,34 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +64498,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,26 +64609,64 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -61263,8 +64675,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -61283,10 +64695,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +64705,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +64723,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +64759,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +64776,6 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { - lineIndex = lineIndex || this.getLineIndex(filename); - var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - LSHost.prototype.getLineIndex = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - if (!languageServiceDiabled) { - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); - } - } - Project.prototype.enableLanguageService = function () { - if (this.languageServiceDiabled) { - this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); - } - this.languageServiceDiabled = false; - }; - Project.prototype.disableLanguageService = function () { - this.languageServiceDiabled = true; - }; - Project.prototype.addOpenRef = function () { - this.openRefCount++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - return this.projectService.openFile(filename, false); - }; - Project.prototype.getRootFiles = function () { - if (this.languageServiceDiabled) { - return this.projectOptions ? this.projectOptions.files : undefined; - } - return this.compilerService.host.roots.map(function (info) { return info.fileName; }); - }; - Project.prototype.getFileNames = function () { - if (this.languageServiceDiabled) { - if (!this.projectOptions) { - return undefined; - } - var fileNames = []; - if (this.projectOptions && this.projectOptions.compilerOptions) { - fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); - } - ts.addRange(fileNames, this.projectOptions.files); - return fileNames; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); - }; - Project.prototype.getSourceFile = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.filenameToSourceFile[info.fileName]; - }; - Project.prototype.getSourceFileFromName = function (filename, requireOpen) { - if (this.languageServiceDiabled) { - return undefined; - } - var info = this.projectService.getScriptInfo(filename); - if (info) { - if ((!requireOpen) || info.isOpen) { - return this.getSourceFile(info); - } - } - }; - Project.prototype.isRoot = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.compilerService.host.roots.some(function (root) { return root === info; }); - }; - Project.prototype.removeReferencedFile = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeReferencedFile(info); - this.updateGraph(); - }; - Project.prototype.updateFileMap = function () { - if (this.languageServiceDiabled) { - return; - } - this.filenameToSourceFile = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - Project.prototype.finishGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.updateGraph(); - this.compilerService.languageService.getNavigateToItems(".*"); - }; - Project.prototype.updateGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.program = this.compilerService.languageService.getProgram(); - this.updateFileMap(); - }; - Project.prototype.isConfiguredProject = function () { - return this.projectFilename; - }; - Project.prototype.addRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.addRoot(info); - }; - Project.prototype.removeRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeRoot(info); - }; - Project.prototype.filesToString = function () { - if (this.languageServiceDiabled) { - if (this.projectOptions) { - var strBuilder_1 = ""; - ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); - return strBuilder_1; - } - } - var strBuilder = ""; - ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { - var fileName = fileNames_3[_b]; - var info = this.getScriptInfo(fileName); - if (info.defaultProject == project) { - info.defaultProject = undefined; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { - var totalNonTsFileSize = 0; - if (!this.host.getFileSize) { - return false; - } - for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { - var fileName = fileNames_4[_i]; - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { - var _this = this; - var parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.projectOptions; - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - if (project.languageServiceDiabled) { - project.setProjectOptions(projectOptions); - project.enableLanguageService(); - project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, false); - project.addRoot(info); - } - } - project.finishGraph(); - return errors; - } - var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); - var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); - var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); - var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { - var fileName = fileNamesToRemove_1[_c]; - var info = this.getScriptInfo(fileName); - if (info) { - project.removeRoot(info); - } - } - for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { - var fileName = fileNamesToAdd_1[_d]; - var info = this.getScriptInfo(fileName); - if (!info) { - info = this.openFile(fileName, false); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62605,16 +64797,17 @@ var ts; var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62801,10 +64994,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +65016,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +65024,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +65056,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +65069,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -63011,7 +65207,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +65220,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63404,12 +65600,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63431,6 +65621,25 @@ var ts; (function (ts) { var server; (function (server) { + var net = require("net"); + var childProcess = require("child_process"); + var os = require("os"); + function getGlobalTypingsCacheLocation() { + var basePath; + switch (process.platform) { + case "win32": + basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir(); + break; + case "linux": + basePath = os.homedir(); + break; + case "darwin": + basePath = ts.combinePaths(os.homedir(), "Library/Application Support/"); + break; + } + ts.Debug.assert(basePath !== undefined); + return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + } var readline = require("readline"); var fs = require("fs"); var rl = readline.createInterface({ @@ -63439,8 +65648,9 @@ var ts; terminal: false }); var Logger = (function () { - function Logger(logFilename, level) { + function Logger(logFilename, traceToConsole, level) { this.logFilename = logFilename; + this.traceToConsole = traceToConsole; this.level = level; this.fd = -1; this.seq = 0; @@ -63455,11 +65665,14 @@ var ts; fs.close(this.fd); } }; + Logger.prototype.getLogFileName = function () { + return this.logFilename; + }; Logger.prototype.perftrc = function (s) { - this.msg(s, "Perf"); + this.msg(s, server.Msg.Perf); }; Logger.prototype.info = function (s) { - this.msg(s, "Info"); + this.msg(s, server.Msg.Info); }; Logger.prototype.startGroup = function () { this.inGroup = true; @@ -63471,19 +65684,19 @@ var ts; this.firstInGroup = true; }; Logger.prototype.loggingEnabled = function () { - return !!this.logFilename; + return !!this.logFilename || this.traceToConsole; }; - Logger.prototype.isVerbose = function () { - return this.loggingEnabled() && (this.level == "verbose"); + Logger.prototype.hasLevel = function (level) { + return this.loggingEnabled() && this.level >= level; }; Logger.prototype.msg = function (s, type) { - if (type === void 0) { type = "Err"; } + if (type === void 0) { type = server.Msg.Err; } if (this.fd < 0) { if (this.logFilename) { this.fd = fs.openSync(this.logFilename, "w"); } } - if (this.fd >= 0) { + if (this.fd >= 0 || this.traceToConsole) { s = s + "\n"; var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { @@ -63494,19 +65707,88 @@ var ts; this.seq++; this.firstInGroup = true; } - var buf = new Buffer(s); - fs.writeSync(this.fd, buf, 0, buf.length, null); + if (this.fd >= 0) { + var buf = new Buffer(s); + fs.writeSync(this.fd, buf, 0, buf.length, null); + } + if (this.traceToConsole) { + console.warn(s); + } } }; return Logger; }()); + var NodeTypingsInstaller = (function () { + function NodeTypingsInstaller(logger, eventPort, globalTypingsCacheLocation, newLine) { + var _this = this; + this.logger = logger; + this.eventPort = eventPort; + this.globalTypingsCacheLocation = globalTypingsCacheLocation; + this.newLine = newLine; + if (eventPort) { + var s_1 = net.connect({ port: eventPort }, function () { + _this.socket = s_1; + }); + } + } + NodeTypingsInstaller.prototype.attach = function (projectService) { + var _this = this; + this.projectService = projectService; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + this.logger.info("Binding..."); + } + var args = ["--globalTypingsCacheLocation", this.globalTypingsCacheLocation]; + if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { + args.push("--logFile", ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log")); + } + var execArgv = []; + { + for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { + var arg = _a[_i]; + var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); + if (match) { + var currentPort = match[3] !== undefined + ? +match[3] + : match[1] === "debug" ? 5858 : 9229; + execArgv.push("--" + match[1] + "=" + (currentPort + 1)); + break; + } + } + } + this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); + this.installer.on("message", function (m) { return _this.handleMessage(m); }); + process.on("exit", function () { + _this.installer.kill(); + }); + }; + NodeTypingsInstaller.prototype.onProjectClosed = function (p) { + this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typingOptions) { + var request = server.createInstallTypingsRequest(project, typingOptions); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Sending request: " + JSON.stringify(request)); + } + this.installer.send(request); + }; + NodeTypingsInstaller.prototype.handleMessage = function (response) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Received response: " + JSON.stringify(response)); + } + this.projectService.updateTypingsForProject(response); + if (response.kind == "set" && this.socket) { + this.socket.write(server.formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8"); + } + }; + return NodeTypingsInstaller; + }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(host, logger) { - _super.call(this, host, Buffer.byteLength, process.hrtime, logger); + function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, globalTypingsCacheLocation, logger) { + return _super.call(this, host, cancellationToken, useSingleInferredProject, new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents) || this; } IOSession.prototype.exit = function () { - this.projectService.log("Exiting...", "Info"); + this.logger.info("Exiting..."); this.projectService.closeLog(); process.exit(0); }; @@ -63523,7 +65805,7 @@ var ts; return IOSession; }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { - var logEnv = {}; + var logEnv = { logToFile: true }; var args = logEnvStr.split(" "); for (var i = 0, len = args.length; i < (len - 1); i += 2) { var option = args[i]; @@ -63531,10 +65813,17 @@ var ts; if (option && value) { switch (option) { case "-file": - logEnv.file = value; + logEnv.file = ts.stripQuotes(value); break; case "-level": - logEnv.detailLevel = value; + var level = server.LogLevel[value]; + logEnv.detailLevel = typeof level === "number" ? level : server.LogLevel.normal; + break; + case "-traceToConsole": + logEnv.traceToConsole = value.toLowerCase() === "true"; + break; + case "-logToFile": + logEnv.logToFile = value.toLowerCase() === "true"; break; } } @@ -63543,21 +65832,25 @@ var ts; } function createLoggerFromEnv() { var fileName = undefined; - var detailLevel = "normal"; + var detailLevel = server.LogLevel.normal; + var traceToConsole = false; var logEnvStr = process.env["TSS_LOG"]; if (logEnvStr) { var logEnv = parseLoggingEnvironmentString(logEnvStr); - if (logEnv.file) { - fileName = logEnv.file; - } - else { - fileName = __dirname + "/.log" + process.pid.toString(); + if (logEnv.logToFile) { + if (logEnv.file) { + fileName = logEnv.file; + } + else { + fileName = __dirname + "/.log" + process.pid.toString(); + } } if (logEnv.detailLevel) { detailLevel = logEnv.detailLevel; } + traceToConsole = logEnv.traceToConsole; } - return new Logger(fileName, detailLevel); + return new Logger(fileName, traceToConsole, detailLevel); } function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } @@ -63629,13 +65922,13 @@ var ts; var logger = createLoggerFromEnv(); var pending = []; var canWrite = true; - function writeMessage(s) { + function writeMessage(buf) { if (!canWrite) { - pending.push(s); + pending.push(buf); } else { canWrite = false; - process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary); + process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); } } function setCanWriteFlagAndWriteMessageIfNecessary() { @@ -63645,7 +65938,7 @@ var ts; } } var sys = ts.sys; - sys.write = function (s) { return writeMessage(s); }; + sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); return { @@ -63654,14 +65947,42 @@ var ts; }; sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; - var ioSession = new IOSession(sys, logger); + sys.setImmediate = setImmediate; + sys.clearImmediate = clearImmediate; + if (typeof global !== "undefined" && global.gc) { + sys.gc = function () { return global.gc(); }; + } + var cancellationToken; + try { + var factory = require("./cancellationToken"); + cancellationToken = factory(sys.args); + } + catch (e) { + cancellationToken = { + isCancellationRequested: function () { return false; } + }; + } + ; + var eventPort; + { + var index = sys.args.indexOf("--eventPort"); + if (index >= 0 && index < sys.args.length - 1) { + var v = parseInt(sys.args[index + 1]); + if (!isNaN(v)) { + eventPort = v; + } + } + } + var useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; + var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, getGlobalTypingsCacheLocation(), logger); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); + process.noAsar = true; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63739,6 +66060,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63932,11 +66259,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -64115,6 +66443,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -64139,10 +66471,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -64164,10 +66497,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 7ed6595bc80..c23bccf0a68 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,4 +1,700 @@ -/// +/// +/// +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceFull = "brace-full"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionsFull = "completions-full"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type DefinitionFull = "definition-full"; + type Implementation = "implementation"; + type ImplementationFull = "implementation-full"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type FormatFull = "format-full"; + type FormatonkeyFull = "formatonkey-full"; + type FormatRangeFull = "formatRange-full"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type NavBarFull = "navbar-full"; + type Navto = "navto"; + type NavtoFull = "navto-full"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type DocumentHighlightsFull = "documentHighlights-full"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type QuickinfoFull = "quickinfo-full"; + type References = "references"; + type ReferencesFull = "references-full"; + type Reload = "reload"; + type Rename = "rename"; + type RenameInfoFull = "rename-full"; + type RenameLocationsFull = "renameLocations-full"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type SignatureHelpFull = "signatureHelp-full"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type SynchronizeProjectList = "synchronizeProjectList"; + type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + type Cleanup = "cleanup"; + type OutliningSpans = "outliningSpans"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + type BreakpointStatement = "breakpointStatement"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetCodeFixesFull = "getCodeFixes-full"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + interface Message { + seq: number; + type: string; + } + interface Request extends Message { + command: string; + arguments?: any; + } + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + interface Event extends Message { + event: string; + body?: any; + } + interface Response extends Message { + request_seq: number; + success: boolean; + command: string; + message?: string; + body?: any; + } + interface FileRequestArgs { + file: string; + projectFileName?: string; + } + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + interface TodoCommentRequestArgs extends FileRequestArgs { + descriptors: TodoCommentDescriptor[]; + } + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + interface IndentationResponse extends Response { + body?: IndentationResult; + } + interface IndentationResult { + position: number; + indentation: number; + } + interface IndentationRequestArgs extends FileLocationRequestArgs { + options?: EditorSettings; + } + interface ProjectInfoRequestArgs extends FileRequestArgs { + needFileNameList: boolean; + } + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + interface CompilerOptionsDiagnosticsRequestArgs { + projectFileName: string; + } + interface ProjectInfo { + configFileName: string; + fileNames?: string[]; + languageServiceDisabled?: boolean; + } + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + interface FileLocationRequestArgs extends FileRequestArgs { + line: number; + offset: number; + position?: number; + } + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface CodeFixRequestArgs extends FileRequestArgs { + startLine: number; + startOffset: number; + startPosition?: number; + endLine: number; + endOffset: number; + endPosition?: number; + errorCodes?: number[]; + } + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + interface GetSupportedCodeFixesResponse extends Response { + body?: string[]; + } + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + start: number; + length: number; + } + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + filesToSearch: string[]; + } + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + interface Location { + line: number; + offset: number; + } + interface TextSpan { + start: Location; + end: Location; + } + interface FileSpan extends TextSpan { + file: string; + } + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + openingBrace: string; + } + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + interface HighlightSpan extends TextSpan { + kind: string; + } + interface DocumentHighlightsItem { + file: string; + highlightSpans: HighlightSpan[]; + } + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + lineText: string; + isWriteAccess: boolean; + isDefinition: boolean; + } + interface ReferencesResponseBody { + refs: ReferencesResponseItem[]; + symbolName: string; + symbolStartOffset: number; + symbolDisplayString: string; + } + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface RenameRequestArgs extends FileLocationRequestArgs { + findInComments?: boolean; + findInStrings?: boolean; + } + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage?: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + } + interface SpanGroup { + file: string; + locs: TextSpan[]; + } + interface RenameResponseBody { + info: RenameInfo; + locs: SpanGroup[]; + } + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + interface ExternalFile { + fileName: string; + scriptKind?: ScriptKind; + hasMixedContent?: boolean; + content?: string; + } + interface ExternalProject { + projectFileName: string; + rootFiles: ExternalFile[]; + options: ExternalProjectCompilerOptions; + typingOptions?: TypingOptions; + } + interface ExternalProjectCompilerOptions extends CompilerOptions { + compileOnSave?: boolean; + } + interface ProjectVersionInfo { + projectName: string; + isInferred: boolean; + version: number; + options: CompilerOptions; + } + interface ProjectChanges { + added: string[]; + removed: string[]; + } + interface ProjectFiles { + info?: ProjectVersionInfo; + files?: string[]; + changes?: ProjectChanges; + } + interface ProjectFilesWithDiagnostics extends ProjectFiles { + projectErrors: DiagnosticWithLinePosition[]; + } + interface ChangedOpenFile { + fileName: string; + changes: ts.TextChange[]; + } + interface ConfigureRequestArguments { + hostInfo?: string; + file?: string; + formatOptions?: FormatCodeSettings; + } + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + interface ConfigureResponse extends Response { + } + interface OpenRequestArgs extends FileRequestArgs { + fileContent?: string; + scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; + } + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + type OpenExternalProjectArgs = ExternalProject; + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + interface OpenExternalProjectsArgs { + projects: ExternalProject[]; + } + interface OpenExternalProjectResponse extends Response { + } + interface OpenExternalProjectsResponse extends Response { + } + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + interface CloseExternalProjectRequestArgs { + projectFileName: string; + } + interface CloseExternalProjectResponse extends Response { + } + interface SynchronizeProjectListRequest extends Request { + arguments: SynchronizeProjectListRequestArgs; + } + interface SynchronizeProjectListRequestArgs { + knownProjects: protocol.ProjectVersionInfo[]; + } + interface ApplyChangedToOpenFilesRequest extends Request { + arguments: ApplyChangedToOpenFilesRequestArgs; + } + interface ApplyChangedToOpenFilesRequestArgs { + openFiles?: ExternalFile[]; + changedFiles?: ChangedOpenFile[]; + closedFiles?: string[]; + } + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + interface SetCompilerOptionsForInferredProjectsArgs { + options: ExternalProjectCompilerOptions; + } + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + interface CompileOnSaveAffectedFileListSingleProject { + projectFileName: string; + fileNames: string[]; + } + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + forced?: boolean; + } + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + interface QuickInfoResponseBody { + kind: string; + kindModifiers: string; + start: Location; + end: Location; + displayString: string; + documentation: string; + } + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + interface FormatRequestArgs extends FileLocationRequestArgs { + endLine: number; + endOffset: number; + endPosition?: number; + options?: FormatCodeSettings; + } + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + interface CodeEdit { + start: Location; + end: Location; + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + body?: CodeAction[]; + } + interface CodeAction { + description: string; + changes: FileCodeEdits[]; + } + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + key: string; + options?: FormatCodeSettings; + } + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + interface CompletionsRequestArgs extends FileLocationRequestArgs { + prefix?: string; + } + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + entryNames: string[]; + } + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + replacementSpan?: TextSpan; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface GeterrForProjectRequestArgs { + file: string; + delay: number; + } + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + interface GeterrRequestArgs { + files: string[]; + delay: number; + } + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + interface Diagnostic { + start: Location; + end: Location; + text: string; + code?: number; + } + interface DiagnosticEventBody { + file: string; + diagnostics: Diagnostic[]; + } + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + triggerFile: string; + configFile: string; + diagnostics: Diagnostic[]; + } + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + interface ReloadRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + interface ReloadResponse extends Response { + } + interface SavetoRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + interface NavtoRequestArgs extends FileRequestArgs { + searchValue: string; + maxResultCount?: number; + currentFileOnly?: boolean; + projectFileName?: string; + } + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + interface NavtoItem { + name: string; + kind: string; + matchKind?: string; + isCaseSensitive?: boolean; + kindModifiers?: string; + file: string; + start: Location; + end: Location; + containerName?: string; + containerKind?: string; + } + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + interface ChangeRequestArgs extends FormatRequestArgs { + insertString?: string; + } + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + interface BraceResponse extends Response { + body?: TextSpan[]; + } + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers?: string; + spans: TextSpan[]; + childItems?: NavigationBarItem[]; + indent: number; + } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } +} declare namespace ts { interface MapLike { [index: string]: T; @@ -15,6 +711,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -374,7 +1071,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; const enum ModifierFlags { None = 0, Export = 1, @@ -421,19 +1117,24 @@ declare namespace ts { nextContainer?: Node; localSymbol?: Symbol; flowNode?: FlowNode; - transformId?: number; - emitFlags?: NodeEmitFlags; - sourceMapRange?: TextRange; - commentRange?: TextRange; + emitNode?: EmitNode; } interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; const enum GeneratedIdentifierKind { None = 0, Auto = 1, @@ -442,6 +1143,7 @@ declare namespace ts { Node = 4, } interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; autoGenerateKind?: GeneratedIdentifierKind; @@ -451,6 +1153,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -462,15 +1165,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -482,40 +1188,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -526,22 +1240,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -552,96 +1267,119 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; textSourceNode?: Identifier | StringLiteral; } interface Expression extends Node { @@ -649,9 +1387,10 @@ declare namespace ts { contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; expression: Expression; } interface UnaryExpression extends Expression { @@ -660,13 +1399,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -680,42 +1423,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -727,137 +1511,192 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; multiLine?: boolean; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; multiLine?: boolean; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; multiLine?: boolean; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -866,68 +1705,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -939,9 +1795,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -950,85 +1808,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1040,95 +1921,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; postParameterName?: Identifier; @@ -1154,7 +2061,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1183,8 +2090,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1239,7 +2147,7 @@ declare namespace ts { interface Program extends ScriptReferenceHost { getRootFileNames(): string[]; getSourceFiles(): SourceFile[]; - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1248,6 +2156,7 @@ declare namespace ts { getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; getDiagnosticsProducingTypeChecker(): TypeChecker; + dropDiagnosticsProducingTypeChecker(): void; getClassifiableNames(): Map; getNodeCount(): number; getIdentifierCount(): number; @@ -1379,6 +2288,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } const enum SymbolFormatFlags { None = 0, @@ -1399,9 +2309,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1457,8 +2368,8 @@ declare namespace ts { getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile; getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; - isLiteralConstDeclaration(node: VariableDeclaration): boolean; - writeLiteralConstValue(node: VariableDeclaration, writer: SymbolWriter): void; + isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; + writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: SymbolWriter): void; } const enum SymbolFlags { None = 0, @@ -1556,7 +2467,8 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; - hasCommonType?: boolean; + hasNonUniformType?: boolean; + isPartial?: boolean; isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; @@ -1641,8 +2553,6 @@ declare namespace ts { ContainsWideningType = 33554432, ContainsObjectLiteral = 67108864, ContainsAnyFunctionType = 134217728, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Nullable = 6144, Literal = 480, StringOrNumberLiteral = 96, @@ -1659,7 +2569,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, RequiresWidening = 100663296, PropagatingFlags = 234881024, } @@ -1687,6 +2597,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1743,6 +2654,7 @@ declare namespace ts { target?: TypeParameter; mapper?: TypeMapper; resolvedApparentType: Type; + isThisType?: boolean; } const enum SignatureKind { Call = 0, @@ -1830,16 +2742,14 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowNonTsExtensions?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; configFilePath?: string; @@ -1884,14 +2794,14 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; pretty?: DiagnosticStyle; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1974,6 +2884,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } const enum WatchDirectoryFlags { None = 0, @@ -2221,7 +3132,15 @@ declare namespace ts { TypeScriptClassSyntaxMask = 137216, ES6FunctionSyntaxMask = 81920, } - const enum NodeEmitFlags { + interface EmitNode { + flags?: EmitFlags; + commentRange?: TextRange; + sourceMapRange?: TextRange; + tokenSourceMapRanges?: Map; + annotatedNodes?: Node[]; + constantValue?: number; + } + const enum EmitFlags { EmitEmitHelpers = 1, EmitExportStar = 2, EmitSuperHelper = 4, @@ -2250,6 +3169,12 @@ declare namespace ts { ReuseTempVariableScope = 4194304, CustomPrologue = 8388608, } + const enum EmitContext { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + Unspecified = 3, + } interface LexicalEnvironment { startLexicalEnvironment(): void; endLexicalEnvironment(): Statement[]; @@ -2327,7 +3252,7 @@ declare namespace ts { function singleOrUndefined(array: T[]): T; function singleOrMany(array: T[]): T | T[]; function lastOrUndefined(array: T[]): T; - function binarySearch(array: number[], value: number): number; + function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number; function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T; function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; @@ -2354,6 +3279,8 @@ declare namespace ts { function multiMapRemove(map: Map, key: string, value: V): void; function isArray(value: any): value is any[]; function memoize(callback: () => T): () => T; + function chain(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U; + function compose(...args: ((t: T) => T)[]): (t: T) => T; let localizedDiagnosticMessages: Map; function getLocaleSpecificMessage(message: DiagnosticMessage): string; function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; @@ -2375,7 +3302,12 @@ declare namespace ts { function getDirectoryPath(path: Path): Path; function getDirectoryPath(path: string): string; function isUrl(path: string): boolean; + function isExternalModuleNameRelative(moduleName: string): boolean; + function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; + function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; + function hasZeroOrOneAsteriskCharacter(str: string): boolean; function isRootedDiskPath(path: string): boolean; + function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNormalizedPathComponents(path: string, currentDirectory: string): string[]; function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string; function getNormalizedPathFromPathComponents(pathComponents: string[]): string; @@ -2409,6 +3341,8 @@ declare namespace ts { const supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; + function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; const enum ExtensionPriority { TypeScriptFiles = 0, @@ -2427,9 +3361,9 @@ declare namespace ts { function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; - getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; + getTokenConstructor(): new (kind: TKind, pos?: number, end?: number) => Token; + getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos?: number, end?: number) => Identifier; + getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; @@ -2442,15 +3376,21 @@ declare namespace ts { VeryAggressive = 3, } namespace Debug { + let currentAssertionLevel: AssertionLevel; function shouldAssert(level: AssertionLevel): boolean; function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void; function fail(message?: string): void; } - function getEnvironmentVariable(name: string, host?: CompilerHost): string; function orderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItem(array: T[], item: T): void; function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string; + function matchPatternOrExact(patternStrings: string[], candidate: string): string | Pattern | undefined; + function patternText({prefix, suffix}: Pattern): string; + function matchedText(pattern: Pattern, candidate: string): string; + function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; + function tryParsePattern(pattern: string): Pattern | undefined; + function positionIsSynthesized(pos: number): boolean; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2493,10 +3433,10 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { - var Diagnostics: { + const Diagnostics: { Unterminated_string_literal: { code: number; category: DiagnosticCategory; @@ -4417,7 +5357,7 @@ declare namespace ts { key: string; message: string; }; - All_symbols_within_a_with_block_will_be_resolved_to_any: { + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: number; category: DiagnosticCategory; key: string; @@ -5383,7 +6323,7 @@ declare namespace ts { key: string; message: string; }; - Identifier_0_must_be_imported_from_a_module: { + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: number; category: DiagnosticCategory; key: string; @@ -6781,6 +7721,18 @@ declare namespace ts { key: string; message: string; }; + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6925,6 +7877,12 @@ declare namespace ts { key: string; message: string; }; + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; You_cannot_rename_this_element: { code: number; category: DiagnosticCategory; @@ -7105,6 +8063,48 @@ declare namespace ts { key: string; message: string; }; + Add_missing_super_call: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Make_super_call_the_first_statement_in_the_constructor: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Change_extends_to_implements: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Remove_unused_identifiers: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_reference: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_inherited_abstract_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; }; } declare namespace ts { @@ -7174,6 +8174,7 @@ declare namespace ts { function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { + const compileOnSaveCommandLineOption: CommandLineOption; const optionDeclarations: CommandLineOption[]; let typingOptionDeclarations: CommandLineOption[]; interface OptionNameMap { @@ -7190,7 +8191,7 @@ declare namespace ts { config?: any; error?: Diagnostic; }; - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -7198,15 +8199,136 @@ declare namespace ts { compilerOptions: Map; }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } +declare namespace ts.JsTyping { + interface TypingResolutionHost { + directoryExists: (path: string) => boolean; + fileExists: (fileName: string) => boolean; + readFile: (path: string, encoding?: string) => string; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; + } + function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { + cachedTypingPaths: string[]; + newTypingNames: string[]; + filesToWatch: string[]; + }; +} +declare namespace ts.server { + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3, + } + const emptyArray: ReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg.Types): void; + getLogFileName(): string; + } + namespace Msg { + type Err = "Err"; + const Err: Err; + type Info = "Info"; + const Info: Info; + type Perf = "Perf"; + const Perf: Perf; + type Types = Err | Info | Perf; + } + function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings; + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; + function mergeMaps(target: MapLike, source: MapLike): void; + function removeItemFromSet(items: T[], itemToRemove: T): void; + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + interface NormalizedPathMap { + get(path: NormalizedPath): T; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function createNormalizedPathMap(): NormalizedPathMap; + const nullLanguageService: LanguageService; + interface ServerLanguageServiceHost { + setCompilationSettings(options: CompilerOptions): void; + notifyFileRemoved(info: ScriptInfo): void; + } + const nullLanguageServiceHost: ServerLanguageServiceHost; + interface ProjectOptions { + configHasFilesProperty?: boolean; + files?: string[]; + wildcardDirectories?: Map; + compilerOptions?: CompilerOptions; + typingOptions?: TypingOptions; + compileOnSave?: boolean; + } + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + class ThrottledOperations { + private readonly host; + private pendingTimeouts; + constructor(host: ServerHost); + schedule(operationId: string, delay: number, cb: () => void): void; + private static run(self, operationId, cb); + } + class GcTimer { + private readonly host; + private readonly delay; + private readonly logger; + private timerId; + constructor(host: ServerHost, delay: number, logger: Logger); + scheduleCollect(): void; + private static run(self); + } +} +declare namespace ts { + function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; + function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean; + function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations; + interface ModuleResolutionState { + host: ModuleResolutionHost; + compilerOptions: CompilerOptions; + traceEnabled: boolean; + skipTsx: boolean; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function directoryProbablyExists(directoryName: string, host: { + directoryExists?: (directoryName: string) => boolean; + }): boolean; + function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} declare namespace ts { const externalHelpersModuleNameText = "tslib"; interface ReferencePathMatchResult { @@ -7231,7 +8353,7 @@ declare namespace ts { function getSingleLineStringWriter(): StringSymbolWriter; function releaseStringWriter(writer: StringSymbolWriter): void; function getFullWidth(node: Node): number; - function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean; + function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean; function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean; function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule; function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void; @@ -7280,7 +8402,7 @@ declare namespace ts { function isConstEnumDeclaration(node: Node): boolean; function isConst(node: Node): boolean; function isLet(node: Node): boolean; - function isSuperCallExpression(n: Node): boolean; + function isSuperCall(n: Node): n is SuperCall; function isPrologueDirective(node: Node): boolean; function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[]; function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[]; @@ -7301,6 +8423,7 @@ declare namespace ts { function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; function isFunctionBlock(node: Node): boolean; function isObjectLiteralMethod(node: Node): node is MethodDeclaration; + function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration; function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate; function isThisTypePredicate(predicate: TypePredicate): predicate is ThisTypePredicate; function getContainingFunction(node: Node): FunctionLikeDeclaration; @@ -7308,7 +8431,7 @@ declare namespace ts { function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; - function isSuperProperty(node: Node): node is (PropertyAccessExpression | ElementAccessExpression); + function isSuperProperty(node: Node): node is SuperProperty; function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; function isCallLikeExpression(node: Node): node is CallLikeExpression; function getInvokedExpression(node: CallLikeExpression): Expression; @@ -7318,7 +8441,6 @@ declare namespace ts { function childIsDecorated(node: Node): boolean; function isJSXTagName(node: Node): boolean; function isPartOfExpression(node: Node): boolean; - function isExternalModuleNameRelative(moduleName: string): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; function isExternalModuleImportEqualsDeclaration(node: Node): boolean; function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression; @@ -7330,7 +8452,7 @@ declare namespace ts { function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; - function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): NamespaceImport; + function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport; function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean; function hasQuestionToken(node: Node): boolean; function isJSDocConstructSignature(node: Node): boolean; @@ -7373,7 +8495,6 @@ declare namespace ts { function getRootDeclaration(node: Node): Node; function nodeStartsNewLexicalEnvironment(node: Node): boolean; function nodeIsSynthesized(node: TextRange): boolean; - function positionIsSynthesized(pos: number): boolean; function getOriginalNode(node: Node): Node; function isParseTreeNode(node: Node): boolean; function getParseTreeNode(node: Node): Node; @@ -7387,7 +8508,7 @@ declare namespace ts { function getExpressionAssociativity(expression: Expression): Associativity; function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity; function getExpressionPrecedence(expression: Expression): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; - function getOperator(expression: Expression): SyntaxKind; + function getOperator(expression: Expression): SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.NumericLiteral | SyntaxKind.StringLiteral | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.Identifier | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.LetKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.StaticKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AbstractKeyword | SyntaxKind.AsKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.GetKeyword | SyntaxKind.IsKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.NumberKeyword | SyntaxKind.SetKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.TypeKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.FromKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.OfKeyword | SyntaxKind.QualifiedName | SyntaxKind.ComputedPropertyName | SyntaxKind.TypeParameter | SyntaxKind.Parameter | SyntaxKind.Decorator | SyntaxKind.PropertySignature | SyntaxKind.PropertyDeclaration | SyntaxKind.MethodSignature | SyntaxKind.MethodDeclaration | SyntaxKind.Constructor | SyntaxKind.GetAccessor | SyntaxKind.SetAccessor | SyntaxKind.CallSignature | SyntaxKind.ConstructSignature | SyntaxKind.IndexSignature | SyntaxKind.TypePredicate | SyntaxKind.TypeReference | SyntaxKind.FunctionType | SyntaxKind.ConstructorType | SyntaxKind.TypeQuery | SyntaxKind.TypeLiteral | SyntaxKind.ArrayType | SyntaxKind.TupleType | SyntaxKind.UnionType | SyntaxKind.IntersectionType | SyntaxKind.ParenthesizedType | SyntaxKind.ThisType | SyntaxKind.LiteralType | SyntaxKind.ObjectBindingPattern | SyntaxKind.ArrayBindingPattern | SyntaxKind.BindingElement | SyntaxKind.ArrayLiteralExpression | SyntaxKind.ObjectLiteralExpression | SyntaxKind.PropertyAccessExpression | SyntaxKind.ElementAccessExpression | SyntaxKind.CallExpression | SyntaxKind.NewExpression | SyntaxKind.TaggedTemplateExpression | SyntaxKind.TypeAssertionExpression | SyntaxKind.ParenthesizedExpression | SyntaxKind.FunctionExpression | SyntaxKind.ArrowFunction | SyntaxKind.DeleteExpression | SyntaxKind.TypeOfExpression | SyntaxKind.VoidExpression | SyntaxKind.AwaitExpression | SyntaxKind.ConditionalExpression | SyntaxKind.TemplateExpression | SyntaxKind.YieldExpression | SyntaxKind.SpreadElementExpression | SyntaxKind.ClassExpression | SyntaxKind.OmittedExpression | SyntaxKind.ExpressionWithTypeArguments | SyntaxKind.AsExpression | SyntaxKind.NonNullExpression | SyntaxKind.TemplateSpan | SyntaxKind.SemicolonClassElement | SyntaxKind.Block | SyntaxKind.VariableStatement | SyntaxKind.EmptyStatement | SyntaxKind.ExpressionStatement | SyntaxKind.IfStatement | SyntaxKind.DoStatement | SyntaxKind.WhileStatement | SyntaxKind.ForStatement | SyntaxKind.ForInStatement | SyntaxKind.ForOfStatement | SyntaxKind.ContinueStatement | SyntaxKind.BreakStatement | SyntaxKind.ReturnStatement | SyntaxKind.WithStatement | SyntaxKind.SwitchStatement | SyntaxKind.LabeledStatement | SyntaxKind.ThrowStatement | SyntaxKind.TryStatement | SyntaxKind.DebuggerStatement | SyntaxKind.VariableDeclaration | SyntaxKind.VariableDeclarationList | SyntaxKind.FunctionDeclaration | SyntaxKind.ClassDeclaration | SyntaxKind.InterfaceDeclaration | SyntaxKind.TypeAliasDeclaration | SyntaxKind.EnumDeclaration | SyntaxKind.ModuleDeclaration | SyntaxKind.ModuleBlock | SyntaxKind.CaseBlock | SyntaxKind.NamespaceExportDeclaration | SyntaxKind.ImportEqualsDeclaration | SyntaxKind.ImportDeclaration | SyntaxKind.ImportClause | SyntaxKind.NamespaceImport | SyntaxKind.NamedImports | SyntaxKind.ImportSpecifier | SyntaxKind.ExportAssignment | SyntaxKind.ExportDeclaration | SyntaxKind.NamedExports | SyntaxKind.ExportSpecifier | SyntaxKind.MissingDeclaration | SyntaxKind.ExternalModuleReference | SyntaxKind.JsxElement | SyntaxKind.JsxSelfClosingElement | SyntaxKind.JsxOpeningElement | SyntaxKind.JsxText | SyntaxKind.JsxClosingElement | SyntaxKind.JsxAttribute | SyntaxKind.JsxSpreadAttribute | SyntaxKind.JsxExpression | SyntaxKind.CaseClause | SyntaxKind.DefaultClause | SyntaxKind.HeritageClause | SyntaxKind.CatchClause | SyntaxKind.PropertyAssignment | SyntaxKind.ShorthandPropertyAssignment | SyntaxKind.EnumMember | SyntaxKind.SourceFile | SyntaxKind.JSDocTypeExpression | SyntaxKind.JSDocAllType | SyntaxKind.JSDocUnknownType | SyntaxKind.JSDocArrayType | SyntaxKind.JSDocUnionType | SyntaxKind.JSDocTupleType | SyntaxKind.JSDocNullableType | SyntaxKind.JSDocNonNullableType | SyntaxKind.JSDocRecordType | SyntaxKind.JSDocRecordMember | SyntaxKind.JSDocTypeReference | SyntaxKind.JSDocOptionalType | SyntaxKind.JSDocFunctionType | SyntaxKind.JSDocVariadicType | SyntaxKind.JSDocConstructorType | SyntaxKind.JSDocThisType | SyntaxKind.JSDocComment | SyntaxKind.JSDocTag | SyntaxKind.JSDocParameterTag | SyntaxKind.JSDocReturnTag | SyntaxKind.JSDocTypeTag | SyntaxKind.JSDocTemplateTag | SyntaxKind.JSDocTypedefTag | SyntaxKind.JSDocPropertyTag | SyntaxKind.JSDocTypeLiteral | SyntaxKind.JSDocLiteralType | SyntaxKind.JSDocNullKeyword | SyntaxKind.JSDocUndefinedKeyword | SyntaxKind.JSDocNeverKeyword | SyntaxKind.SyntaxList | SyntaxKind.NotEmittedStatement | SyntaxKind.PartiallyEmittedExpression | SyntaxKind.Count; function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; function createDiagnosticCollection(): DiagnosticCollection; function escapeString(s: string): string; @@ -7413,26 +8534,28 @@ declare namespace ts { function getIndentSize(): number; function createTextWriter(newLine: String): EmitTextWriter; function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; - function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; + function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string; function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string; function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; - function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; - function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; interface EmitFileNames { jsFilePath: string; sourceMapFilePath: string; declarationFilePath: string; } function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): SourceFile[]; - function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void): void; - function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void; + function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, emitOnlyDtsFiles?: boolean): void; + function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean, emitOnlyDtsFiles: boolean) => void, targetSourceFile?: SourceFile, emitOnlyDtsFiles?: boolean): void; function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void; function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number; function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number): number; function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration; - function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode; + function getSetAccessorTypeAnnotationNode(accessor: SetAccessorDeclaration): TypeNode; + function getThisParameter(signature: SignatureDeclaration): ParameterDeclaration | undefined; + function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean; + function isThisIdentifier(node: Node | undefined): boolean; + function identifierIsThisKeyword(id: Identifier): boolean; interface AllAccessorDeclarations { firstAccessor: AccessorDeclaration; secondAccessor: AccessorDeclaration; @@ -7463,12 +8586,9 @@ declare namespace ts { function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; - function hasJavaScriptFileExtension(fileName: string): boolean; - function hasTypeScriptFileExtension(fileName: string): boolean; function tryExtractTypeScriptExtension(fileName: string): string | undefined; const stringify: (value: any) => string; function convertToBase64(input: string): string; - function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNewLineCharacter(options: CompilerOptions): string; function isSimpleExpression(node: Expression): boolean; function formatSyntaxKind(kind: SyntaxKind): string; @@ -7504,7 +8624,8 @@ declare namespace ts { function isTextualLiteralKind(kind: SyntaxKind): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; function isTemplateLiteralKind(kind: SyntaxKind): boolean; - function isTemplateLiteralFragment(node: Node): node is TemplateLiteralFragment; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; function isIdentifier(node: Node): node is Identifier; function isGeneratedIdentifier(node: Node): boolean; function isModifier(node: Node): node is Modifier; @@ -7529,7 +8650,7 @@ declare namespace ts { function isBinaryExpression(node: Node): node is BinaryExpression; function isConditionalExpression(node: Node): node is ConditionalExpression; function isCallExpression(node: Node): node is CallExpression; - function isTemplate(node: Node): node is Template; + function isTemplateLiteral(node: Node): node is TemplateLiteral; function isSpreadElementExpression(node: Node): node is SpreadElementExpression; function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; @@ -7613,24 +8734,25 @@ declare namespace ts { function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral; function createLiteral(value: string, location?: TextRange): StringLiteral; function createLiteral(value: number, location?: TextRange): NumericLiteral; + function createLiteral(value: boolean, location?: TextRange): BooleanLiteral; function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression; function createIdentifier(text: string, location?: TextRange): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, location?: TextRange): Identifier; function createLoopVariable(location?: TextRange): Identifier; function createUniqueName(text: string, location?: TextRange): Identifier; function getGeneratedNameForNode(node: Node, location?: TextRange): Identifier; - function createToken(token: SyntaxKind): Node; + function createToken(token: TKind): Token; function createSuper(): PrimaryExpression; function createThis(location?: TextRange): PrimaryExpression; function createNull(): PrimaryExpression; function createComputedPropertyName(expression: Expression, location?: TextRange): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; function createParameter(name: string | Identifier | BindingPattern, initializer?: Expression, location?: TextRange): ParameterDeclaration; - function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: Node, name: string | Identifier | BindingPattern, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; + function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; function updateParameterDeclaration(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression): ParameterDeclaration; - function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; + function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, type: TypeNode, initializer: Expression): PropertyDeclaration; - function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; + function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): MethodDeclaration; function createConstructor(decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block, location?: TextRange, flags?: NodeFlags): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block): ConstructorDeclaration; @@ -7642,7 +8764,7 @@ declare namespace ts { function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[], location?: TextRange): ArrayBindingPattern; function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; - function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: Node, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; + function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: DotDotDotToken, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression): BindingElement; function createArrayLiteral(elements?: Expression[], location?: TextRange, multiLine?: boolean): ArrayLiteralExpression; function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; @@ -7656,13 +8778,13 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): CallExpression; function createNew(expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[], location?: TextRange, flags?: NodeFlags): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): NewExpression; - function createTaggedTemplate(tag: Expression, template: Template, location?: TextRange): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: Template): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, template: TemplateLiteral, location?: TextRange): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createParen(expression: Expression, location?: TextRange): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; + function createFunctionExpression(asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: Node, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; + function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression, location?: TextRange): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): Expression; @@ -7672,17 +8794,17 @@ declare namespace ts { function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; function createAwait(expression: Expression, location?: TextRange): AwaitExpression; function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; - function createPrefix(operator: SyntaxKind, operand: Expression, location?: TextRange): PrefixUnaryExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression, location?: TextRange): PrefixUnaryExpression; function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; - function createPostfix(operand: Expression, operator: SyntaxKind, location?: TextRange): PostfixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator, location?: TextRange): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; - function createBinary(left: Expression, operator: SyntaxKind | Node, right: Expression, location?: TextRange): BinaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression, location?: TextRange): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; - function createConditional(condition: Expression, questionToken: Node, whenTrue: Expression, colonToken: Node, whenFalse: Expression, location?: TextRange): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; - function createTemplateExpression(head: TemplateLiteralFragment, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateLiteralFragment, templateSpans: TemplateSpan[]): TemplateExpression; - function createYield(asteriskToken: Node, expression: Expression, location?: TextRange): YieldExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createYield(asteriskToken: AsteriskToken, expression: Expression, location?: TextRange): YieldExpression; function updateYield(node: YieldExpression, expression: Expression): YieldExpression; function createSpread(expression: Expression, location?: TextRange): SpreadElementExpression; function updateSpread(node: SpreadElementExpression, expression: Expression): SpreadElementExpression; @@ -7691,8 +8813,8 @@ declare namespace ts { function createOmittedExpression(location?: TextRange): OmittedExpression; function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression, location?: TextRange): ExpressionWithTypeArguments; function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function createTemplateSpan(expression: Expression, literal: TemplateLiteralFragment, location?: TextRange): TemplateSpan; - function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateLiteralFragment): TemplateSpan; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail, location?: TextRange): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function createBlock(statements: Statement[], location?: TextRange, multiLine?: boolean, flags?: NodeFlags): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[], declarationList: VariableDeclarationList | VariableDeclaration[], location?: TextRange, flags?: NodeFlags): VariableStatement; @@ -7715,9 +8837,9 @@ declare namespace ts { function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function createForOf(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForOfStatement; - function updateForOf(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createContinue(label?: Identifier, location?: TextRange): BreakStatement; - function updateContinue(node: ContinueStatement, label: Identifier): BreakStatement; + function updateForOf(node: ForOfStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: Identifier, location?: TextRange): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier): ContinueStatement; function createBreak(label?: Identifier, location?: TextRange): BreakStatement; function updateBreak(node: BreakStatement, label: Identifier): BreakStatement; function createReturn(expression?: Expression, location?: TextRange): ReturnStatement; @@ -7734,7 +8856,7 @@ declare namespace ts { function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause, finallyBlock: Block): TryStatement; function createCaseBlock(clauses: CaseOrDefaultClause[], location?: TextRange): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; - function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; + function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; @@ -7828,6 +8950,7 @@ declare namespace ts { function createExpressionForPropertyName(memberName: PropertyName): Expression; function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression; function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; + function ensureUseStrict(node: SourceFile): SourceFile; function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression): Expression; function parenthesizeForNew(expression: Expression): LeftHandSideExpression; function parenthesizeForAccess(expression: Expression): LeftHandSideExpression; @@ -7852,6 +8975,17 @@ declare namespace ts { function skipPartiallyEmittedExpressions(node: Node): Node; function startOnNewLine(node: T): T; function setOriginalNode(node: T, original: Node): T; + function disposeEmitNodes(sourceFile: SourceFile): void; + function getEmitFlags(node: Node): EmitFlags; + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + function setSourceMapRange(node: T, range: TextRange): T; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; + function setCommentRange(node: T, range: TextRange): T; + function getCommentRange(node: Node): TextRange; + function getSourceMapRange(node: Node): TextRange; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; function setTextRange(node: T, location: TextRange): T; function setNodeFlags(node: T, flags: NodeFlags): T; function setMultiLine(node: T, multiLine: boolean): T; @@ -7940,34 +9074,22 @@ declare namespace ts { } declare namespace ts { interface TransformationResult { - getSourceFiles(): SourceFile[]; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - isSubstitutionEnabled(node: Node): boolean; - isEmitNotificationEnabled(node: Node): boolean; - onSubstituteNode(node: Node, isExpression: boolean): Node; - onEmitNode(node: Node, emitCallback: (node: Node) => void): void; - dispose(): void; + transformed: SourceFile[]; + emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; } interface TransformationContext extends LexicalEnvironment { getCompilerOptions(): CompilerOptions; getEmitResolver(): EmitResolver; getEmitHost(): EmitHost; - getNodeEmitFlags(node: Node): NodeEmitFlags; - setNodeEmitFlags(node: T, flags: NodeEmitFlags): T; - getSourceMapRange(node: Node): TextRange; - setSourceMapRange(node: T, range: TextRange): T; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; - getCommentRange(node: Node): TextRange; - setCommentRange(node: T, range: TextRange): T; hoistFunctionDeclaration(node: FunctionDeclaration): void; hoistVariableDeclaration(node: Identifier): void; enableSubstitution(kind: SyntaxKind): void; isSubstitutionEnabled(node: Node): boolean; - onSubstituteNode?: (node: Node, isExpression: boolean) => Node; + onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node; enableEmitNotification(kind: SyntaxKind): void; isEmitNotificationEnabled(node: Node): boolean; - onEmitNode?: (node: Node, emit: (node: Node) => void) => void; + onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; } type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; function getTransformers(compilerOptions: CompilerOptions): Transformer[]; @@ -7975,63 +9097,40 @@ declare namespace ts { } declare namespace ts { function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[]; - function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean; + function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean): boolean; } declare namespace ts { interface SourceMapWriter { initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void; reset(): void; - getSourceMapData(): SourceMapData; setSourceFile(sourceFile: SourceFile): void; emitPos(pos: number): void; - emitStart(range: TextRange): void; - emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitEnd(range: TextRange): void; - emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitTokenStart(token: SyntaxKind, tokenStartPos: number): number; - emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - changeEmitSourcePos(): void; - stopOverridingSpan(): void; + emitNodeWithSourceMap(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitTokenWithSourceMap(node: Node, token: SyntaxKind, tokenStartPos: number, emitCallback: (token: SyntaxKind, tokenStartPos: number) => number): number; getText(): string; getSourceMappingURL(): string; + getSourceMapData(): SourceMapData; } function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter; - function getNullSourceMapWriter(): SourceMapWriter; } declare namespace ts { interface CommentWriter { reset(): void; setSourceFile(sourceFile: SourceFile): void; - emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void; + emitNodeWithComments(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; emitTrailingCommentsOfPosition(pos: number): void; } function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter; } declare namespace ts { - function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult; + function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult; } declare namespace ts { const version = "2.1.0"; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string; - function hasZeroOrOneAsteriskCharacter(str: string): boolean; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; - function tryParsePattern(pattern: string): Pattern | undefined; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function directoryProbablyExists(directoryName: string, host: { - directoryExists?: (directoryName: string) => boolean; - }): boolean; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; interface FormatDiagnosticsHost { @@ -8041,7 +9140,6 @@ declare namespace ts { } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -8135,6 +9233,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -8165,18 +9264,20 @@ declare namespace ts { findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; getNonBoundSourceFile(fileName: string): SourceFile; getSourceFile(fileName: string): SourceFile; @@ -8200,6 +9301,13 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -8213,6 +9321,14 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + description: string; + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; caretOffset: number; @@ -8257,6 +9373,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -8265,10 +9386,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -8284,7 +9408,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -8367,6 +9505,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; isNewIdentifierLocation: boolean; entries: CompletionEntry[]; @@ -8628,7 +9767,7 @@ declare namespace ts { function stripQuotes(name: string): string; function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; - function parseAndReEmitConfigJSONFile(content: string): { + function sanitizeConfigFile(configFileName: string, content: string): { configJsonObject: any; diagnostics: Diagnostic[]; }; @@ -8686,24 +9825,12 @@ declare namespace ts.JsDoc { function getAllJsDocCompletionEntries(): CompletionEntry[]; function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion; } -declare namespace ts.JsTyping { - interface TypingResolutionHost { - directoryExists: (path: string) => boolean; - fileExists: (fileName: string) => boolean; - readFile: (path: string, encoding?: string) => string; - readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; - } - function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { - cachedTypingPaths: string[]; - newTypingNames: string[]; - filesToWatch: string[]; - }; -} declare namespace ts.NavigateTo { - function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; + function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[]; } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; + function getNavigationTree(sourceFile: SourceFile): NavigationTree; } declare namespace ts.OutliningElementsCollector { function collectElements(sourceFile: SourceFile): OutliningSpan[]; @@ -9148,7 +10275,7 @@ declare namespace ts.formatting { getRuleName(rule: Rule): string; getRuleByName(name: string): Rule; getRulesMap(): RulesMap; - ensureUpToDate(options: ts.FormatCodeOptions): void; + ensureUpToDate(options: ts.FormatCodeSettings): void; private createActiveRules(options); } } @@ -9161,35 +10288,58 @@ declare namespace ts.formatting { token: TextRangeWithKind; trailingTrivia: TextRangeWithKind[]; } - function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function getIndentationString(indentation: number, options: FormatCodeOptions): string; + function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function getIndentationString(indentation: number, options: EditorSettings): string; } declare namespace ts.formatting { namespace SmartIndenter { - function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number; - function getBaseIndentation(options: EditorOptions): number; - function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number; + function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number; + function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number; + function getBaseIndentation(options: EditorSettings): number; function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean; - function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): { + function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): { column: number; character: number; }; - function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): number; + function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): number; function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean): boolean; function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean; } } +declare namespace ts { + interface CodeFix { + errorCodes: number[]; + getCodeActions(context: CodeFixContext): CodeAction[] | undefined; + } + interface CodeFixContext { + errorCode: number; + sourceFile: SourceFile; + span: TextSpan; + program: Program; + newLineCharacter: string; + } + namespace codefix { + function registerCodeFix(action: CodeFix): void; + function getSupportedErrorCodes(): string[]; + function getFixes(context: CodeFixContext): CodeAction[]; + } +} +declare namespace ts.codefix { +} declare namespace ts { const servicesVersion = "0.5"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; @@ -9198,101 +10348,516 @@ declare namespace ts { function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { - function generateSpaces(n: number): string; - function generateIndentString(n: number, editorOptions: EditorOptions): string; + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + isOpen: boolean; + hasMixedContent: boolean; + readonly containingProjects: Project[]; + private formatCodeSettings; + readonly path: Path; + private fileWatcher; + private svc; + constructor(host: ServerHost, fileName: NormalizedPath, content: string, scriptKind: ScriptKind, isOpen?: boolean, hasMixedContent?: boolean); + getFormatCodeSettings(): FormatCodeSettings; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + setFormatOptions(formatSettings: FormatCodeSettings): void; + setWatcher(watcher: FileWatcher): void; + stopWatcher(): void; + getLatestVersion(): string; + reload(script: string): void; + saveTo(fileName: string): void; + reloadFromFile(): void; + snap(): LineIndexSnapshot; + getLineInfo(line: number): ILineInfo; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + lineToTextSpan(line: number): TextSpan; + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): ILineInfo; + } +} +declare namespace ts.server { + class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost { + private readonly host; + private readonly project; + private readonly cancellationToken; + private compilationSettings; + private readonly resolvedModuleNames; + private readonly resolvedTypeReferenceDirectives; + private readonly getCanonicalFileName; + private readonly resolveModuleName; + readonly trace: (s: string) => void; + constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); + private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); + getProjectVersion(): string; + getCompilationSettings(): CompilerOptions; + useCaseSensitiveFileNames(): boolean; + getCancellationToken(): HostCancellationToken; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; + getDefaultLibFileName(): string; + getScriptSnapshot(filename: string): ts.IScriptSnapshot; + getScriptFileNames(): string[]; + getTypeRootsVersion(): number; + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getCurrentDirectory(): string; + resolvePath(path: string): string; + fileExists(path: string): boolean; + readFile(fileName: string): string; + directoryExists(path: string): boolean; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + getDirectories(path: string): string[]; + notifyFileRemoved(info: ScriptInfo): void; + setCompilationSettings(opt: ts.CompilerOptions): void; + } +} +declare namespace ts.server { + interface ITypingsInstaller { + enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string; + } + const nullTypingsInstaller: ITypingsInstaller; + interface TypingsArray extends ReadonlyArray { + " __typingsArrayBrand": any; + } + class TypingsCache { + private readonly installer; + private readonly perProjectCache; + constructor(installer: ITypingsInstaller); + getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray; + invalidateCachedTypingsForProject(project: Project): void; + updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]): void; + onProjectClosed(project: Project): void; + } +} +declare namespace ts.server { + function shouldEmitFile(scriptInfo: ScriptInfo): boolean; + class BuilderFileInfo { + readonly scriptInfo: ScriptInfo; + readonly project: Project; + private lastCheckedShapeSignature; + constructor(scriptInfo: ScriptInfo, project: Project); + isExternalModuleOrHasOnlyAmbientExternalModules(): boolean; + private containsOnlyAmbientModules(sourceFile); + private computeHash(text); + private getSourceFile(); + updateShapeSignature(): boolean; + } + interface Builder { + readonly project: Project; + getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; + onProjectUpdateGraph(): void; + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + } + function createBuilder(project: Project): Builder; +} +declare namespace ts.server { + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2, + } + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { + projectErrors: Diagnostic[]; + } + abstract class Project { + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + languageServiceEnabled: boolean; + private compilerOptions; + compileOnSaveEnabled: boolean; + private rootFiles; + private rootFilesMap; + private lsHost; + private program; + private languageService; + builder: Builder; + private lastReportedFileNames; + private lastReportedVersion; + private projectStructureVersion; + private projectStateVersion; + private typingFiles; + protected projectErrors: Diagnostic[]; + typesVersion: number; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + constructor(projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + getProjectErrors(): Diagnostic[]; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + getProjectVersion(): string; + enableLanguageService(): void; + disableLanguageService(): void; + abstract getProjectName(): string; + abstract getProjectRootPath(): string | undefined; + abstract getTypingOptions(): TypingOptions; + getSourceFile(path: Path): SourceFile; + updateTypes(): void; + close(): void; + getCompilerOptions(): CompilerOptions; + hasRoots(): boolean; + getRootFiles(): NormalizedPath[]; + getRootFilesLSHost(): string[]; + getRootScriptInfos(): ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; + getFileNames(): NormalizedPath[]; + getAllEmittableFiles(): string[]; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo): void; + removeFile(info: ScriptInfo, detachFromProject?: boolean): void; + markAsDirty(): void; + updateGraph(): boolean; + private setTypings(typings); + private updateGraphWorker(); + getScriptInfoLSHost(fileName: string): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + filesToString(): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + reloadScript(filename: NormalizedPath): boolean; + getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; + getReferencedFiles(path: Path): Path[]; + private removeRootFileIfNecessary(info); + } + class InferredProject extends Project { + compileOnSaveEnabled: boolean; + private static NextId; + private readonly inferredProjectName; + directoriesWatchedForTsconfig: string[]; + constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + getProjectName(): string; + getProjectRootPath(): string; + close(): void; + getTypingOptions(): TypingOptions; + } + class ConfiguredProject extends Project { + readonly configFileName: NormalizedPath; + private wildcardDirectories; + compileOnSaveEnabled: boolean; + private typingOptions; + private projectFileWatcher; + private directoryWatcher; + private directoriesWatchedForWildcards; + private typeRootsWatchers; + openRefCount: number; + constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); + getProjectRootPath(): string; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypingOptions(newTypingOptions: TypingOptions): void; + getTypingOptions(): TypingOptions; + getProjectName(): NormalizedPath; + watchConfigFile(callback: (project: ConfiguredProject) => void): void; + watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; + watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; + watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void; + stopWatchingDirectory(): void; + close(): void; + addOpenRef(): void; + deleteOpenRef(): number; + getEffectiveTypeRoots(): string[]; + } + class ExternalProject extends Project { + readonly externalProjectName: string; + compileOnSaveEnabled: boolean; + private readonly projectFilePath; + private typingOptions; + constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); + getProjectRootPath(): string; + getTypingOptions(): TypingOptions; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypingOptions(newTypingOptions: TypingOptions): void; + getProjectName(): string; + } +} +declare namespace ts.server { + const maxProgramSizeForNonTsFiles: number; + type ProjectServiceEvent = { + eventName: "context"; + data: { + project: Project; + fileName: NormalizedPath; + }; + } | { + eventName: "configFileDiag"; + data: { + triggerFile?: string; + configFileName: string; + diagnostics: Diagnostic[]; + }; + }; + interface ProjectServiceEventHandler { + (event: ProjectServiceEvent): void; + } + function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + hostInfo: string; + } + interface OpenConfiguredProjectResult { + configFileName?: string; + configFileErrors?: Diagnostic[]; + } + class ProjectService { + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly eventHandler; + readonly typingsCache: TypingsCache; + private readonly documentRegistry; + private readonly filenameToScriptInfo; + private readonly externalProjectToConfiguredProjectMap; + readonly externalProjects: ExternalProject[]; + readonly inferredProjects: InferredProject[]; + readonly configuredProjects: ConfiguredProject[]; + readonly openFiles: ScriptInfo[]; + private compilerOptionsForInferredProjects; + private compileOnSaveForInferredProjects; + private readonly directoryWatchers; + private readonly throttledOperations; + private readonly hostConfiguration; + private changedFiles; + private toCanonicalFileName; + lastDeletedFile: ScriptInfo; + constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler); + getChangedFiles_TestOnly(): ScriptInfo[]; + ensureInferredProjectsUpToDate_TestOnly(): void; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; + stopWatchingDirectory(directory: string): void; + findProject(projectName: string): Project; + getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; + private ensureInferredProjectsUpToDate(); + private findContainingExternalProject(fileName); + getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; + private updateProjectGraphs(projects); + private onSourceFileChanged(fileName); + private handleDeletedFile(info); + private onTypeRootFileChanged(project, fileName); + private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName); + private handleChangeInSourceFileForConfiguredProject(project); + private onConfigChangedForConfiguredProject(project); + private onConfigFileAddedForInferredProject(fileName); + private getCanonicalFileName(fileName); + private removeProject(project); + private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); + private closeOpenFile(info); + private openOrUpdateConfiguredProjectForFile(fileName); + private findConfigFile(searchPath); + private printProjects(); + private findConfiguredProjectByProjectName(configFileName); + private findExternalProjectByProjectName(projectFileName); + private convertConfigFileContentToProjectOptions(configFilename); + private exceededTotalSizeLimitForNonTsFiles(options, fileNames, propertyReader); + private createAndAddExternalProject(projectFileName, files, options, typingOptions); + private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile?); + private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); + private watchConfigDirectoryForProject(project, options); + private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typingOptions, configFileErrors); + private openConfigFile(configFileName, clientFileName?); + private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors); + private updateConfiguredProject(project); + createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; + getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfoForPath(fileName: Path): ScriptInfo; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + reloadProjects(): void; + refreshInferredProjects(): void; + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): OpenConfiguredProjectResult; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult; + closeClientFile(uncheckedFileName: string): void; + private collectChanges(lastKnownProjectVersions, currentProjects, result); + synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[]; + applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void; + private closeConfiguredProject(configFile); + closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; + openExternalProject(proj: protocol.ExternalProject): void; + } +} +declare namespace ts.server { interface PendingErrorCheck { - fileName: string; + fileName: NormalizedPath; project: Project; } namespace CommandNames { - const Brace = "brace"; - const Change = "change"; - const Close = "close"; - const Completions = "completions"; - const CompletionDetails = "completionEntryDetails"; - const Configure = "configure"; - const Definition = "definition"; - const Exit = "exit"; - const Format = "format"; - const Formatonkey = "formatonkey"; - const Geterr = "geterr"; - const GeterrForProject = "geterrForProject"; - const Implementation = "implementation"; - const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - const NavBar = "navbar"; - const Navto = "navto"; - const Occurrences = "occurrences"; - const DocumentHighlights = "documentHighlights"; - const Open = "open"; - const Quickinfo = "quickinfo"; - const References = "references"; - const Reload = "reload"; - const Rename = "rename"; - const Saveto = "saveto"; - const SignatureHelp = "signatureHelp"; - const TypeDefinition = "typeDefinition"; - const ProjectInfo = "projectInfo"; - const ReloadProjects = "reloadProjects"; - const Unknown = "unknown"; - } - interface ServerHost extends ts.System { - setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout(timeoutId: any): void; + const Brace: protocol.CommandTypes.Brace; + const BraceFull: protocol.CommandTypes.BraceFull; + const BraceCompletion: protocol.CommandTypes.BraceCompletion; + const Change: protocol.CommandTypes.Change; + const Close: protocol.CommandTypes.Close; + const Completions: protocol.CommandTypes.Completions; + const CompletionsFull: protocol.CommandTypes.CompletionsFull; + const CompletionDetails: protocol.CommandTypes.CompletionDetails; + const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList; + const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile; + const Configure: protocol.CommandTypes.Configure; + const Definition: protocol.CommandTypes.Definition; + const DefinitionFull: protocol.CommandTypes.DefinitionFull; + const Exit: protocol.CommandTypes.Exit; + const Format: protocol.CommandTypes.Format; + const Formatonkey: protocol.CommandTypes.Formatonkey; + const FormatFull: protocol.CommandTypes.FormatFull; + const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull; + const FormatRangeFull: protocol.CommandTypes.FormatRangeFull; + const Geterr: protocol.CommandTypes.Geterr; + const GeterrForProject: protocol.CommandTypes.GeterrForProject; + const Implementation: protocol.CommandTypes.Implementation; + const ImplementationFull: protocol.CommandTypes.ImplementationFull; + const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync; + const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync; + const NavBar: protocol.CommandTypes.NavBar; + const NavBarFull: protocol.CommandTypes.NavBarFull; + const NavTree: protocol.CommandTypes.NavTree; + const NavTreeFull: protocol.CommandTypes.NavTreeFull; + const Navto: protocol.CommandTypes.Navto; + const NavtoFull: protocol.CommandTypes.NavtoFull; + const Occurrences: protocol.CommandTypes.Occurrences; + const DocumentHighlights: protocol.CommandTypes.DocumentHighlights; + const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull; + const Open: protocol.CommandTypes.Open; + const Quickinfo: protocol.CommandTypes.Quickinfo; + const QuickinfoFull: protocol.CommandTypes.QuickinfoFull; + const References: protocol.CommandTypes.References; + const ReferencesFull: protocol.CommandTypes.ReferencesFull; + const Reload: protocol.CommandTypes.Reload; + const Rename: protocol.CommandTypes.Rename; + const RenameInfoFull: protocol.CommandTypes.RenameInfoFull; + const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull; + const Saveto: protocol.CommandTypes.Saveto; + const SignatureHelp: protocol.CommandTypes.SignatureHelp; + const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull; + const TypeDefinition: protocol.CommandTypes.TypeDefinition; + const ProjectInfo: protocol.CommandTypes.ProjectInfo; + const ReloadProjects: protocol.CommandTypes.ReloadProjects; + const Unknown: protocol.CommandTypes.Unknown; + const OpenExternalProject: protocol.CommandTypes.OpenExternalProject; + const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects; + const CloseExternalProject: protocol.CommandTypes.CloseExternalProject; + const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList; + const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles; + const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull; + const Cleanup: protocol.CommandTypes.Cleanup; + const OutliningSpans: protocol.CommandTypes.OutliningSpans; + const TodoComments: protocol.CommandTypes.TodoComments; + const Indentation: protocol.CommandTypes.Indentation; + const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate; + const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull; + const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan; + const BreakpointStatement: protocol.CommandTypes.BreakpointStatement; + const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; + const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; + const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull; + const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; } + function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; class Session { private host; + protected readonly typingsInstaller: ITypingsInstaller; private byteLength; private hrtime; - private logger; + protected logger: Logger; + protected readonly canUseEvents: boolean; + private readonly gcTimer; protected projectService: ProjectService; private errorTimer; private immediateId; private changeSeq; - constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger); - private handleEvent(event); + private eventHander; + constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean, eventHandler?: ProjectServiceEventHandler); + private defaultEventHandler(event); logError(err: Error, cmd: string): void; - private sendLineToClient(line); send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; event(info: any, eventName: string): void; - private response(info, cmdName, reqSeq?, errorMsg?); - output(body: any, commandName: string, requestSequence?: number, errorMessage?: string): void; + output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); - private reloadProjects(); private updateProjectStructure(seq, matchSeq, ms?); private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?); - private getDefinition(line, offset, fileName); - private getTypeDefinition(line, offset, fileName); - private getImplementation(line, offset, fileName); - private getOccurrences(line, offset, fileName); - private getDiagnosticsWorker(args, selector); + private cleanProjects(caption, projects); + private cleanup(); + private getEncodedSemanticClassifications(args); + private getProject(projectFileName); + private getCompilerOptionsDiagnostics(args); + private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); + private getDiagnosticsWorker(args, selector, includeLinePosition); + private getDefinition(args, simplifiedResult); + private getTypeDefinition(args); + private getImplementation(args, simplifiedResult); + private getOccurrences(args); private getSyntacticDiagnosticsSync(args); private getSemanticDiagnosticsSync(args); - private getDocumentHighlights(line, offset, fileName, filesToSearch); - private getProjectInfo(fileName, needFileNameList); - private getRenameLocations(line, offset, fileName, findInComments, findInStrings); - private getReferences(line, offset, fileName); + private getDocumentHighlights(args, simplifiedResult); + private setCompilerOptionsForInferredProjects(args); + private getProjectInfo(args); + private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList); + private getRenameInfo(args); + private getProjects(args); + private getRenameLocations(args, simplifiedResult); + private getReferences(args, simplifiedResult); private openClientFile(fileName, fileContent?, scriptKind?); - private getQuickInfo(line, offset, fileName); - private getFormattingEditsForRange(line, offset, endLine, endOffset, fileName); - private getFormattingEditsAfterKeystroke(line, offset, key, fileName); - private getCompletions(line, offset, prefix, fileName); - private getCompletionEntryDetails(line, offset, entryNames, fileName); - private getSignatureHelpItems(line, offset, fileName); + private getPosition(args, scriptInfo); + private getFileAndProject(args, errorOnMissingProject?); + private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?); + private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject); + private getOutliningSpans(args); + private getTodoComments(args); + private getDocCommentTemplate(args); + private getIndentation(args); + private getBreakpointStatement(args); + private getNameOrDottedNameSpan(args); + private isValidBraceCompletion(args); + private getQuickInfoWorker(args, simplifiedResult); + private getFormattingEditsForRange(args); + private getFormattingEditsForRangeFull(args); + private getFormattingEditsForDocumentFull(args); + private getFormattingEditsAfterKeystrokeFull(args); + private getFormattingEditsAfterKeystroke(args); + private getCompletions(args, simplifiedResult); + private getCompletionEntryDetails(args); + private getCompileOnSaveAffectedFileList(args); + private emitFile(args); + private getSignatureHelpItems(args, simplifiedResult); private getDiagnostics(delay, fileNames); - private change(line, offset, endLine, endOffset, insertString, fileName); - private reload(fileName, tempFileName, reqSeq?); + private change(args); + private reload(args, reqSeq); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items, lineIndex); - private getNavigationBarItems(fileName); - private getNavigateToItems(searchValue, fileName, maxResultCount?, currentFileOnly?); - private getBraceMatching(line, offset, fileName); + private decorateNavigationBarItems(items, scriptInfo); + private getNavigationBarItems(args, simplifiedResult); + private decorateNavigationTree(tree, scriptInfo); + private decorateSpan(span, scriptInfo); + private getNavigationTree(args, simplifiedResult); + private getNavigateToItems(args, simplifiedResult); + private getSupportedCodeFixes(); + private getCodeFixes(args, simplifiedResult); + private mapCodeAction(codeAction, scriptInfo); + private convertTextChangeToCodeEdit(change, scriptInfo); + private getBraceMatching(args, simplifiedResult); getDiagnosticsForProject(delay: number, fileName: string): void; getCanonicalFileName(fileName: string): string; exit(): void; + private notRequired(); private requiredResponse(response); private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => { @@ -9307,227 +10872,6 @@ declare namespace ts.server { } } declare namespace ts.server { - interface Logger { - close(): void; - isVerbose(): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: string): void; - } - const maxProgramSizeForNonTsFiles: number; - class ScriptInfo { - private host; - fileName: string; - isOpen: boolean; - svc: ScriptVersionCache; - children: ScriptInfo[]; - defaultProject: Project; - fileWatcher: FileWatcher; - formatCodeOptions: FormatCodeOptions; - path: Path; - scriptKind: ScriptKind; - constructor(host: ServerHost, fileName: string, content: string, isOpen?: boolean); - setFormatOptions(formatOptions: protocol.FormatOptions): void; - close(): void; - addChild(childInfo: ScriptInfo): void; - snap(): LineIndexSnapshot; - getText(): string; - getLineInfo(line: number): ILineInfo; - editContent(start: number, end: number, newText: string): void; - getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange; - getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange; - } - class LSHost implements ts.LanguageServiceHost { - host: ServerHost; - project: Project; - ls: ts.LanguageService; - compilationSettings: ts.CompilerOptions; - filenameToScript: ts.FileMap; - roots: ScriptInfo[]; - private resolvedModuleNames; - private resolvedTypeReferenceDirectives; - private moduleResolutionHost; - private getCanonicalFileName; - constructor(host: ServerHost, project: Project); - private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; - getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): ts.IScriptSnapshot; - setCompilationSettings(opt: ts.CompilerOptions): void; - lineAffectsRefs(filename: string, line: number): boolean; - getCompilationSettings(): CompilerOptions; - getScriptFileNames(): string[]; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(filename: string): string; - getCurrentDirectory(): string; - getScriptIsOpen(filename: string): boolean; - removeReferencedFile(info: ScriptInfo): void; - getScriptInfo(filename: string): ScriptInfo; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - saveTo(filename: string, tmpfilename: string): void; - reloadScript(filename: string, tmpfilename: string, cb: () => any): void; - editScript(filename: string, start: number, end: number, newText: string): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile(path: string, encoding?: string): string; - lineToTextSpan(filename: string, line: number): ts.TextSpan; - lineOffsetToPosition(filename: string, line: number, offset: number): number; - positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; - getLineIndex(filename: string): LineIndex; - } - interface ProjectOptions { - files?: string[]; - wildcardDirectories?: ts.MapLike; - compilerOptions?: ts.CompilerOptions; - } - class Project { - projectService: ProjectService; - projectOptions: ProjectOptions; - languageServiceDiabled: boolean; - compilerService: CompilerService; - projectFilename: string; - projectFileWatcher: FileWatcher; - directoryWatcher: FileWatcher; - directoriesWatchedForWildcards: Map; - directoriesWatchedForTsconfig: string[]; - program: ts.Program; - filenameToSourceFile: Map; - updateGraphSeq: number; - openRefCount: number; - constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); - enableLanguageService(): void; - disableLanguageService(): void; - addOpenRef(): void; - deleteOpenRef(): number; - openReferencedFile(filename: string): ScriptInfo; - getRootFiles(): string[]; - getFileNames(): string[]; - getSourceFile(info: ScriptInfo): SourceFile; - getSourceFileFromName(filename: string, requireOpen?: boolean): SourceFile; - isRoot(info: ScriptInfo): boolean; - removeReferencedFile(info: ScriptInfo): void; - updateFileMap(): void; - finishGraph(): void; - updateGraph(): void; - isConfiguredProject(): string; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - filesToString(): string; - setProjectOptions(projectOptions: ProjectOptions): void; - } - interface ProjectOpenResult { - success?: boolean; - errorMsg?: string; - project?: Project; - } - function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; - type ProjectServiceEvent = { - eventName: "context"; - data: { - project: Project; - fileName: string; - }; - } | { - eventName: "configFileDiag"; - data: { - triggerFile?: string; - configFileName: string; - diagnostics: Diagnostic[]; - }; - }; - interface ProjectServiceEventHandler { - (event: ProjectServiceEvent): void; - } - interface HostConfiguration { - formatCodeOptions: ts.FormatCodeOptions; - hostInfo: string; - } - class ProjectService { - host: ServerHost; - psLogger: Logger; - eventHandler: ProjectServiceEventHandler; - filenameToScriptInfo: Map; - openFileRoots: ScriptInfo[]; - inferredProjects: Project[]; - configuredProjects: Project[]; - openFilesReferenced: ScriptInfo[]; - openFileRootsConfigured: ScriptInfo[]; - directoryWatchersForTsconfig: Map; - directoryWatchersRefCount: Map; - hostConfiguration: HostConfiguration; - timerForDetectingProjectFileListChanges: Map; - constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler); - addDefaultHostConfiguration(): void; - getFormatCodeOptions(file?: string): FormatCodeOptions; - watchedFileChanged(fileName: string): void; - directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void; - startTimerForDetectingProjectFileListChanges(project: Project): void; - handleProjectFileListChanges(project: Project): void; - reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string): void; - directoryWatchedForTsconfigChanged(fileName: string): void; - getCanonicalFileName(fileName: string): string; - watchedProjectConfigFileChanged(project: Project): void; - log(msg: string, type?: string): void; - setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments): void; - closeLog(): void; - createInferredProject(root: ScriptInfo): Project; - fileDeletedInFilesystem(info: ScriptInfo): void; - updateConfiguredProjectList(): void; - removeProject(project: Project): void; - setConfiguredProjectRoot(info: ScriptInfo): boolean; - addOpenFile(info: ScriptInfo): void; - closeOpenFile(info: ScriptInfo): void; - findReferencingProjects(info: ScriptInfo, excludedProject?: Project): Project[]; - reloadProjects(): void; - updateProjectStructure(): void; - getScriptInfo(filename: string): ScriptInfo; - openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; - findConfigFile(searchPath: string): string; - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - openOrUpdateConfiguredProjectForFile(fileName: string): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - closeClientFile(filename: string): void; - getProjectForFile(filename: string): Project; - printProjectsForFile(filename: string): void; - printProjects(): void; - configProjectIsActive(fileName: string): boolean; - findConfiguredProjectByConfigFile(configFileName: string): Project; - configFileToProjectOptions(configFilename: string): { - projectOptions?: ProjectOptions; - errors: Diagnostic[]; - }; - private exceedTotalNonTsFileSizeLimit(fileNames); - openConfigFile(configFilename: string, clientFileName?: string): { - project?: Project; - errors: Diagnostic[]; - }; - updateConfiguredProject(project: Project): Diagnostic[]; - createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; - } - class CompilerService { - project: Project; - host: LSHost; - languageService: ts.LanguageService; - classifier: ts.Classifier; - settings: ts.CompilerOptions; - documentRegistry: DocumentRegistry; - constructor(project: Project, opt?: ts.CompilerOptions); - setCompilerOptions(opt: ts.CompilerOptions): void; - isExternalModule(filename: string): boolean; - static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions; - } interface LineCollection { charCount(): number; lineCount(): number; @@ -9566,15 +10910,17 @@ declare namespace ts.server { changes: TextChange[]; versions: LineIndexSnapshot[]; minVersion: number; - private currentVersion; private host; + private currentVersion; static changeNumberThreshold: number; static changeLengthThreshold: number; static maxVersions: number; + private versionToIndex(version); + private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; latest(): LineIndexSnapshot; latestVersion(): number; - reloadFromFile(filename: string, cb?: () => any): void; + reloadFromFile(filename: string): void; reload(script: string): void; getSnapshot(): LineIndexSnapshot; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; @@ -9643,10 +10989,7 @@ declare namespace ts.server { } class LineLeaf implements LineCollection { text: string; - udata: any; constructor(text: string); - setUdata(data: any): void; - getUdata(): any; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; charCount(): number; @@ -9680,6 +11023,7 @@ declare namespace ts { getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; + getTypeRootsVersion?(): number; readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; readFile(path: string, encoding?: string): string; fileExists(path: string): boolean; @@ -9739,6 +11083,7 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; getNavigationBarItems(fileName: string): string; + getNavigationTree(fileName: string): string; getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; @@ -9775,6 +11120,7 @@ declare namespace ts { trace(s: string): void; error(s: string): void; getProjectVersion(): string; + getTypeRootsVersion(): number; useCaseSensitiveFileNames(): boolean; getCompilationSettings(): CompilerOptions; getScriptFileNames(): string[]; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index a8fa909efcc..a360ac081ec 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -150,6 +149,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,6 +157,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -533,16 +540,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -776,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1012,10 +1075,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1389,6 +1487,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1480,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1649,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1886,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1997,19 +2146,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2334,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2495,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2728,6 +2901,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2752,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2781,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3691,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4334,11 +4517,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4761,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -4962,10 +5152,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5099,13 +5290,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -5183,6 +5376,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -5196,7 +5400,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -5395,6 +5601,937 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_7 in packageNameToTypingLocation) { + if (name_7 in inferredTypings && !inferredTypings[name_7]) { + inferredTypings[name_7] = packageNameToTypingLocation[name_7]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(server.LogLevel || (server.LogLevel = {})); + var LogLevel = server.LogLevel; + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typingOptions, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(), + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function throwLanguageServiceIsDisabledError() { + throw new Error("LanguageService is disabled"); + } + server.nullLanguageService = { + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError, + getCompletionEntrySymbol: throwLanguageServiceIsDisabledError, + getImplementationAtPosition: throwLanguageServiceIsDisabledError, + getSourceFile: throwLanguageServiceIsDisabledError, + getCodeFixesAtPosition: throwLanguageServiceIsDisabledError + }; + server.nullLanguageServiceHost = { + setCompilationSettings: function () { return undefined; }, + notifyFileRemoved: function () { return undefined; } + }; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_1 = ts.getDirectoryPath(currentDirectory); + if (parent_1 === currentDirectory) { + break; + } + currentDirectory = parent_1; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5877,10 +7014,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5943,23 +7080,23 @@ var ts; case 139: case 172: case 97: - var parent_1 = node.parent; - if (parent_1.kind === 158) { + var parent_2 = node.parent; + if (parent_2.kind === 158) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (154 <= parent_2.kind && parent_2.kind <= 166) { return true; } - switch (parent_1.kind) { + switch (parent_2.kind) { case 194: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); case 141: - return node === parent_1.constraint; + return node === parent_2.constraint; case 145: case 144: case 142: case 218: - return node === parent_1.type; + return node === parent_2.type; case 220: case 179: case 180: @@ -5968,16 +7105,16 @@ var ts; case 146: case 149: case 150: - return node === parent_1.type; + return node === parent_2.type; case 151: case 152: case 153: - return node === parent_1.type; + return node === parent_2.type; case 177: - return node === parent_1.type; + return node === parent_2.type; case 174: case 175: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + return parent_2.typeArguments && ts.indexOf(parent_2.typeArguments, node) >= 0; case 176: return false; } @@ -6030,9 +7167,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_7 = node.name; - if (name_7 && name_7.kind === 140) { - traverse(name_7.expression); + var name_8 = node.name; + if (name_8 && name_8.kind === 140) { + traverse(name_8.expression); return; } } @@ -6128,6 +7265,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6238,13 +7381,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 179 || func.kind === 180) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 178) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent_3 = func.parent; + while (parent_3.kind === 178) { + prev = parent_3; + parent_3 = parent_3.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { - return parent_2; + if (parent_3.kind === 174 && parent_3.expression === prev) { + return parent_3; } } } @@ -6390,8 +7533,8 @@ var ts; case 8: case 9: case 97: - var parent_3 = node.parent; - switch (parent_3.kind) { + var parent_4 = node.parent; + switch (parent_4.kind) { case 218: case 142: case 145: @@ -6399,7 +7542,7 @@ var ts; case 255: case 253: case 169: - return parent_3.initializer === node; + return parent_4.initializer === node; case 202: case 203: case 204: @@ -6410,32 +7553,32 @@ var ts; case 249: case 215: case 213: - return parent_3.expression === node; + return parent_4.expression === node; case 206: - var forStatement = parent_3; + var forStatement = parent_4; return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || forStatement.condition === node || forStatement.incrementor === node; case 207: case 208: - var forInStatement = parent_3; + var forInStatement = parent_4; return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || forInStatement.expression === node; case 177: case 195: - return node === parent_3.expression; + return node === parent_4.expression; case 197: - return node === parent_3.expression; + return node === parent_4.expression; case 140: - return node === parent_3.expression; + return node === parent_4.expression; case 143: case 248: case 247: return true; case 194: - return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); + return parent_4.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_4); default: - if (isPartOfExpression(parent_3)) { + if (isPartOfExpression(parent_4)) { return true; } } @@ -6443,10 +7586,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6650,17 +7789,17 @@ var ts; node.parent && node.parent.kind === 225) { result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var parent_5 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_5 && parent_5.parent && + parent_5.kind === 187 && + parent_5.operatorToken.kind === 56 && + parent_5.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5.parent, checkParentVariableStatement, getDocs, getTags)); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; + var isPropertyAssignmentExpression = parent_5 && parent_5.kind === 253; if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5, checkParentVariableStatement, getDocs, getTags)); } if (node.kind === 142) { var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); @@ -6693,8 +7832,8 @@ var ts; } } else if (param.name.kind === 69) { - var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + var name_9 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; }); if (paramTags) { return paramTags; } @@ -6765,20 +7904,20 @@ var ts; node = node.parent; } while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; + var parent_6 = node.parent; + if (parent_6.kind === 170 || parent_6.kind === 191) { + node = parent_6; continue; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; + if (parent_6.kind === 253 || parent_6.kind === 254) { + node = parent_6.parent; continue; } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + return parent_6.kind === 187 && + isAssignmentOperator(parent_6.operatorToken.kind) && + parent_6.left === node || + (parent_6.kind === 207 || parent_6.kind === 208) && + parent_6.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; @@ -7044,14 +8183,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -7487,28 +8622,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -7525,7 +8648,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -7552,7 +8675,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -7568,7 +8691,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7595,18 +8718,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +8738,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7651,13 +8775,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7971,14 +9114,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8069,12 +9204,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8163,9 +9292,9 @@ var ts; if (syntaxKindCache[kind]) { return syntaxKindCache[kind]; } - for (var name_9 in syntaxKindEnum) { - if (syntaxKindEnum[name_9] === kind) { - return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + for (var name_10 in syntaxKindEnum) { + if (syntaxKindEnum[name_10] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")"; } } } @@ -8175,7 +9304,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,7 +9373,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -8281,8 +9410,8 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + var name_11 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier); } } break; @@ -8344,15 +9473,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -8491,12 +9621,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -8827,7 +9957,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; @@ -9062,7 +10191,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9094,7 +10223,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9381,7 +10510,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,7 +10518,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -9493,7 +10622,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -9586,7 +10715,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -10486,13 +11615,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -10606,8 +11735,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -10834,7 +11963,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -10846,6 +11975,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -11085,17 +12236,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11122,8 +12368,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_11 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name_12 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } if (node.kind === 230 && node.importClause) { return getGeneratedNameForNode(node); @@ -12205,7 +13451,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -12533,7 +13779,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -12549,7 +13795,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -12560,8 +13806,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14822,8 +16075,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -14909,7 +16162,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15847,8 +17100,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15934,14 +17187,14 @@ var ts; } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(141, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 24) { @@ -16344,7 +17597,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +17627,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16492,11 +17753,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16561,7 +17828,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -17016,7 +18283,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17149,7 +18418,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -17248,9 +18517,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -17782,7 +19054,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -17794,12 +19066,12 @@ var ts; return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_7 = node.parent; + if (!ts.isExternalModule(parent_7)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_7.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17979,6 +19251,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -18117,8 +19392,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -18220,7 +19494,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18265,7 +19539,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -18282,7 +19556,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18618,6 +19892,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -19175,7 +20450,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -19335,28 +20610,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -19593,6 +20868,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -20077,9 +21353,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,7 +21390,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -20131,7 +21407,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -20201,12 +21477,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -20595,12 +21871,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -20787,19 +22063,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { + var name_17 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_17)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_16); + var text = getTextOfPropertyName(name_17); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17)); return unknownType; } } @@ -20858,6 +22134,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -20880,6 +22160,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -20951,7 +22236,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -21420,7 +22705,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21953,13 +23239,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -21998,6 +23295,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22016,20 +23314,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +23338,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,6 +23362,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -22438,7 +23738,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22722,7 +24022,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22821,7 +24122,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -23796,7 +25114,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -25001,17 +26320,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25288,6 +26600,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25302,7 +26631,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -25364,10 +26695,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -25553,12 +26887,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25596,7 +26930,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25723,7 +27058,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -25846,14 +27181,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -25938,7 +27285,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -26003,7 +27350,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -26222,11 +27569,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_18 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_18)) { + var text = getTextOfPropertyName(name_18); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26663,7 +28010,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -26714,7 +28062,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -27109,7 +28460,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -27150,7 +28501,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -27266,15 +28617,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); + var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_19 !== undefined) { + var prop = getPropertyOfType(objectType, name_19); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol)); return unknownType; } } @@ -27375,19 +28726,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -28290,7 +29641,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28440,7 +29793,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28690,14 +30043,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + var name_20 = property.name; + if (name_20.kind === 140) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -28712,7 +30065,7 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } else { @@ -29361,9 +30714,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29383,9 +30736,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -29395,15 +30748,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 69 && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 168 || + name_22.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -29596,7 +30949,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29622,6 +30975,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29635,7 +30989,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -30345,7 +31699,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -30360,9 +31714,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -30500,6 +31851,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -30547,8 +31901,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -30603,6 +31957,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -30616,12 +31973,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24)); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -30639,7 +31996,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -30647,7 +32004,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -31022,7 +32379,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -31741,9 +33103,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31818,9 +33182,9 @@ var ts; break; case 169: case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -31982,9 +33346,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32046,12 +33412,12 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports = getExportsOfModule(moduleSymbol); - for (var id in exports) { + var exports_1 = getExportsOfModule(moduleSymbol); + for (var id in exports_1) { if (id === "__export") { continue; } - var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; if (flags & (1920 | 64 | 384)) { continue; } @@ -32071,7 +33437,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32556,6 +33923,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -32670,9 +34040,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -32979,9 +34349,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33090,9 +34460,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -33211,26 +34581,26 @@ var ts; if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); if (helpersModule) { - var exports = helpersModule.exports; + var exports_2 = helpersModule.exports; if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { - verifyHelperSymbol(exports, "__extends", 107455); + verifyHelperSymbol(exports_2, "__extends", 107455); } if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { - verifyHelperSymbol(exports, "__assign", 107455); + verifyHelperSymbol(exports_2, "__assign", 107455); } if (requestedExternalEmitHelpers & 2048) { - verifyHelperSymbol(exports, "__decorate", 107455); + verifyHelperSymbol(exports_2, "__decorate", 107455); if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455); + verifyHelperSymbol(exports_2, "__metadata", 107455); } } if (requestedExternalEmitHelpers & 4096) { - verifyHelperSymbol(exports, "__param", 107455); + verifyHelperSymbol(exports_2, "__param", 107455); } if (requestedExternalEmitHelpers & 8192) { - verifyHelperSymbol(exports, "__awaiter", 107455); + verifyHelperSymbol(exports_2, "__awaiter", 107455); if (languageVersion < 2) { - verifyHelperSymbol(exports, "__generator", 107455); + verifyHelperSymbol(exports_2, "__generator", 107455); } } } @@ -33652,8 +35022,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33761,10 +35131,9 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + var name_27 = prop.name; + if (name_27.kind === 140) { + checkGrammarComputedPropertyName(name_27); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -33780,8 +35149,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (name_27.kind === 8) { + checkGrammarNumericLiteral(name_27); } currentKind = Property; } @@ -33797,7 +35166,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27); if (effectiveName === undefined) { continue; } @@ -33807,18 +35176,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33831,12 +35200,12 @@ var ts; continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_28 = jsxAttr.name; + if (!seen[name_28.text]) { + seen[name_28.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -33919,17 +35288,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -34763,7 +36123,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -34787,7 +36147,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -34797,7 +36157,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -35072,7 +36432,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -35089,7 +36449,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -35113,7 +36473,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -35153,7 +36513,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -35197,10 +36557,10 @@ var ts; emitArrayLiteralAssignment(target, value, location); } else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); + var name_29 = ts.getMutableClone(target); + ts.setSourceMapRange(name_29, target); + ts.setCommentRange(name_29, target); + emitAssignment(name_29, value, location, undefined); } } function emitObjectLiteralAssignment(target, value, location) { @@ -35314,7 +36674,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,10 +36683,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -35334,12 +36697,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -35493,11 +36863,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -35519,7 +36900,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -35549,7 +36930,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -35591,7 +36972,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -35612,7 +36993,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -35673,7 +37054,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +37073,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35715,8 +37096,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -35726,8 +37107,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -35868,7 +37249,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -35886,12 +37267,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -35905,7 +37286,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -36070,10 +37451,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -36117,14 +37521,14 @@ var ts; function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + var name_30 = ts.getMutableClone(node); + name_30.flags &= ~8; + name_30.original = undefined; + name_30.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30); } - return name_29; + return name_30; case 139: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -36194,8 +37598,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -36207,8 +37611,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36217,8 +37621,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36313,11 +37717,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -36327,14 +37731,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -36383,12 +37787,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -36397,6 +37802,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36408,7 +37814,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -36447,18 +37853,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_31 = node.symbol && node.symbol.name; + if (name_31) { + return currentScopeFirstDeclarationsOfName[name_31] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -36468,13 +37888,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -36485,6 +37905,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36501,15 +37922,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -36536,9 +37959,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -36561,7 +37985,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -36590,9 +38014,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -36613,7 +38037,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -36622,7 +38046,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -36639,8 +38063,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_32 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -36648,9 +38072,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); + ts.setEmitFlags(name_32, emitFlags); } - return name_30; + return name_32; } else { return ts.getGeneratedNameForNode(node); @@ -36712,7 +38136,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -36724,13 +38148,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,14 +38164,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_33 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_33); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_33, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_33, exportedName, node); } } return node; @@ -36756,16 +38180,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -36782,8 +38205,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -36792,7 +38215,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -36820,23 +38243,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -36860,6 +38308,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37018,12 +38469,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_34 = node.tagName; + if (ts.isIdentifier(name_34) && ts.isIntrinsicJsxName(name_34.text)) { + return ts.createLiteral(name_34.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_34); } } } @@ -37305,6 +38756,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37364,7 +38818,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37384,6 +38838,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -37553,7 +39010,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -37690,15 +39147,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37713,14 +39170,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -37731,7 +39188,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -37742,33 +39203,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -37793,34 +39319,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_35 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_35)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_35, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_35, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -37832,11 +39358,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -37844,21 +39370,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -37888,43 +39417,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37943,7 +39472,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -38000,7 +39529,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -38011,10 +39540,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -38055,7 +39584,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -38078,13 +39607,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38179,7 +39708,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -38214,14 +39743,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38239,7 +39768,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38328,7 +39857,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -38338,7 +39867,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -38366,8 +39895,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +39905,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38555,7 +40084,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,13 +40097,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -38694,12 +40242,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -38721,9 +40269,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38773,7 +40321,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -38783,8 +40331,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_36 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -38792,9 +40340,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); + ts.setEmitFlags(name_36, emitFlags); } - return name_35; + return name_36; } return ts.getGeneratedNameForNode(node); } @@ -38842,7 +40390,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,6 +40424,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -38982,7 +40533,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39003,7 +40554,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39034,6 +40585,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +40598,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39064,6 +40617,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39079,7 +40633,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39747,9 +41301,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,11 +41320,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_8 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_8, node); + ts.setCommentRange(clone_8, node); return clone_8; } } @@ -40164,7 +41718,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -40439,7 +41993,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40464,6 +42018,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -40489,7 +42046,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -40500,7 +42057,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -40527,7 +42084,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -40535,12 +42092,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -40603,7 +42160,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -40691,16 +42248,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); + var name_38 = names_1[_i]; + addExportMemberAssignments(statements, name_38); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); + var name_39 = node.name; + if (ts.isIdentifier(name_39)) { + names.push(name_39); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -40718,7 +42275,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -40835,25 +42392,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40894,7 +42451,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40912,11 +42469,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -40931,7 +42488,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -40943,7 +42500,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -40955,12 +42512,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + var name_40 = declaration.propertyName || declaration.name; + if (name_40.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); } } } @@ -40982,7 +42539,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -41010,7 +42567,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -41032,7 +42589,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -41061,6 +42618,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -41093,12 +42653,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -41342,11 +42902,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + var name_41 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); + recordExportName(name_41); } ts.setOriginalNode(newNode, node); node = newNode; @@ -41357,13 +42917,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); + var name_42 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); + hoistVariableDeclaration(name_42); } return [ node, - createExportStatement(name_41, name_41) + createExportStatement(name_42, name_42) ]; } return node; @@ -41517,19 +43077,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -41563,7 +43123,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -41668,7 +43228,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -41701,7 +43261,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -41801,7 +43361,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -41815,6 +43375,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -41951,18 +43514,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -41971,47 +43526,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,75 +43555,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -42144,54 +43638,6 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +43648,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42242,7 +43688,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42427,7 +43873,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,7 +43885,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42612,9 +44058,9 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_43 = baseName + "_" + count; + if (!(name_43 in currentIdentifiers)) { + return name_43; } } } @@ -42632,7 +44078,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -43038,7 +44484,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43606,14 +45052,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43630,8 +45076,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +45103,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +45110,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +45181,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +45191,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +45221,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +45246,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,6 +45323,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -43973,6 +45338,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +45350,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44071,20 +45400,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -44113,10 +45444,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,7 +45471,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -44147,8 +45480,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44256,16 +45591,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,7 +45636,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -44319,7 +45646,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -44332,11 +45659,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44353,14 +45680,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +45699,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44394,8 +45728,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -44431,73 +45765,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -44524,7 +45846,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -44700,17 +46023,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -44726,7 +46044,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -44804,7 +46123,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -45019,7 +46338,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +46351,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45057,15 +46373,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45220,7 +46535,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -45395,11 +46710,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -45431,7 +46746,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -45486,7 +46801,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45548,7 +46863,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45745,8 +47060,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45794,7 +47109,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -45900,31 +47215,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +47314,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +47356,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46225,17 +47500,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +47525,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_44 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_44)) { tempFlags |= flags; - return name_43; + return name_44; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_45 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_45)) { + return name_45; } } } @@ -46445,581 +47715,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +47816,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47181,41 +47876,14 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + var name_46 = names_2[_i]; + var result = name_46 in cache + ? cache[name_46] + : cache[name_46] = loader(name_46, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47241,7 +47909,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,15 +47917,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -47299,7 +47967,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -47346,6 +48015,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -47446,16 +48116,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +48149,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47991,7 +48664,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -48003,7 +48675,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48017,8 +48689,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +48701,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +48745,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +48756,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +48795,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48685,7 +49360,7 @@ var ts; case 97: return true; case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142; default: return false; } @@ -49258,7 +49933,6 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; @@ -49481,7 +50155,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +50166,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -50701,8 +51378,7 @@ var ts; return; case 142: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,13 +51419,13 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -50773,17 +51449,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_47 in nameTable) { + if (nameTable[name_47] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_47]) { + uniqueNames[name_47] = name_47; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50833,7 +51509,9 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 253 && + node.parent.parent.kind === 171 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { @@ -50856,7 +51534,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -50872,7 +51550,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +51560,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +51571,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50934,6 +51612,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +51643,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +51807,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +51820,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51347,7 +52028,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51399,6 +52080,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51429,10 +52111,12 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 || node.kind === 139 || node.kind === 172) { @@ -51483,6 +52167,7 @@ var ts; var attrsType = void 0; if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -51842,8 +52527,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_48 = element.propertyName || element.name; + existingImportsOrExports[name_48.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51927,7 +52612,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +59140,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58605,7 +59169,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +59179,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +59190,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +59228,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58842,7 +59406,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58940,11 +59504,116 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 174) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(69, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -59167,15 +59836,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -59249,7 +59919,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59406,6 +60076,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +60114,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59583,7 +60281,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +60318,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59878,12 +60583,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +60599,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59957,14 +60662,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60020,34 +60737,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60159,6 +60902,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +60912,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60233,43 +60978,2344 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { + if (isOpen === void 0) { isOpen = false; } + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.isOpen = isOpen; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = server.ScriptVersionCache.fromString(host, content); + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); } - return spaceCache[n]; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + ts.Debug.assert(this.containingProjects.length !== 0); + return this.containingProjects[0]; + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.svc.latestVersion().toString(); + }; + ScriptInfo.prototype.reload = function (script) { + this.svc.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.snap(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function () { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.svc.reloadFromFile(this.fileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + var index = this.snap().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (primaryResult.resolvedModule) { + if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { + return primaryResult; + } + } + var secondaryLookupFailedLookupLocations = []; + var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; + if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { + var traceEnabled = ts.isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; + var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); + if (resolvedName) { + return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); + } + } + if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { + primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); + } + return primaryResult; + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_52 = names_3[_i]; + var resolution = newResolutions[name_52]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this); + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) { + return false; + } + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: function () { }, + attach: function (projectService) { }, + onProjectClosed: function (p) { }, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typingOptionsChanged(opt1, opt2) { + return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function toTypingsArray(arr) { + arr.sort(); + return arr; + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + typings: result, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typingOptions); } return result; + }; + TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions.enableAutoDiscovery) { + return; + } + this.installer.enqueueInstallTypingsRequest(project, typingOptions); + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typingOptions: typingOptions, + typings: toTypingsArray(newTypings), + poisoned: false + }; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var crypto = require("crypto"); + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 225 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return crypto.createHash("md5") + .update(text) + .digest("base64"); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + this.fileInfos = ts.createFileMap(); + } + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.fileInfos.get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.fileInfos.getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.fileInfos.set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.fileInfos.remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.fileInfos.forEachValue(function (path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(server.ProjectKind || (server.ProjectKind = {})); + var ProjectKind = server.ProjectKind; + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var Project = (function () { + function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.languageServiceEnabled = languageServiceEnabled; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + if (languageServiceEnabled) { + this.enableLanguageService(); + } + else { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); + this.lsHost = lsHost; + this.languageServiceEnabled = true; + }; + Project.prototype.disableLanguageService = function () { + this.languageService = server.nullLanguageService; + this.lsHost = server.nullLanguageServiceHost; + this.languageServiceEnabled = false; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + result.push(f.fileName); + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function () { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isOpen || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.updateGraph = function () { + if (!this.languageServiceEnabled) { + return true; + } + var hasChanges = this.updateGraphWorker(); + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + this.builder.onProjectUpdateGraph(); + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + this.compilerOptions = compilerOptions; + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions() + }; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.directoriesWatchedForTsconfig = []; + _this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); + InferredProject.NextId++; + return _this; + } + InferredProject.prototype.getProjectName = function () { + return this.inferredProjectName; + }; + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypingOptions = function () { + return { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.NextId = 1; + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.configFileName = configFileName; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + return _this; + } + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.configFileName); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { + this.typingOptions = newTypingOptions; + }; + ConfiguredProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ConfiguredProject.prototype.getProjectName = function () { + return this.configFileName; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.configFileName); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.configFileName); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); + }; + ExternalProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { + if (!newTypingOptions) { + newTypingOptions = { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypingOptions.enableAutoDiscovery === undefined) { + newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); + } + if (!newTypingOptions.include) { + newTypingOptions.include = []; + } + if (!newTypingOptions.exclude) { + newTypingOptions.exclude = []; + } + } + this.typingOptions = newTypingOptions; + }; + ExternalProject.prototype.getProjectName = function () { + return this.externalProjectName; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (_) { return false; } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return x.scriptKind; }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host" + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case "set": + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); + project.updateGraph(); + break; + case "invalidate": + this.typingsCache.invalidateCachedTypingsForProject(project); + break; + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(projectCompilerOptions); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isOpen)) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isOpen) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + this.logger.info("Config file changed: " + project.configFileName); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.reloadFromFile(); + server.removeItemFromSet(this.openFiles, info); + info.isOpen = false; + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + return findProjectByName(configFileName, this.configuredProjects); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typingOptions: parsedCommandLine.typingOptions, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypingOptions(typingOptions); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isOpen && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypingOptions(newTypingOptions); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.configFileName)) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + if (!project.languageServiceEnabled) { + project.enableLanguageService(); + } + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); + } + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (!info.isOpen && !hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + if (info) { + if (fileContent !== undefined) { + info.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(args.formatOptions); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.logger.info("Format host information updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var _a = this.findContainingExternalProject(fileName) + ? {} + : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_3 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_3(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { + var file = changedFiles_1[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProject = function (proj) { + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); + } + this.refreshInferredProjects(); + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +63334,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +63350,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,73 +63361,166 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { + var proj = _a[_i]; + _this.projectService.openExternalProject(proj); + } + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -60397,34 +63539,81 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function (request) { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,72 +63630,94 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function (request) { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; case "configFileDiag": @@ -60515,26 +63726,23 @@ var ts; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60559,7 +63767,7 @@ var ts; }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -60576,17 +63784,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +63799,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +63809,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +63827,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +63838,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,78 +63854,133 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var p = projects_4[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -60732,115 +63989,142 @@ var ts; }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +64145,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; - var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +64200,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options || this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +64353,106 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +64461,34 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +64498,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,26 +64609,64 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -61263,8 +64675,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -61283,10 +64695,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +64705,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +64723,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +64759,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +64776,6 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { - lineIndex = lineIndex || this.getLineIndex(filename); - var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - LSHost.prototype.getLineIndex = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - if (!languageServiceDiabled) { - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); - } - } - Project.prototype.enableLanguageService = function () { - if (this.languageServiceDiabled) { - this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); - } - this.languageServiceDiabled = false; - }; - Project.prototype.disableLanguageService = function () { - this.languageServiceDiabled = true; - }; - Project.prototype.addOpenRef = function () { - this.openRefCount++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - return this.projectService.openFile(filename, false); - }; - Project.prototype.getRootFiles = function () { - if (this.languageServiceDiabled) { - return this.projectOptions ? this.projectOptions.files : undefined; - } - return this.compilerService.host.roots.map(function (info) { return info.fileName; }); - }; - Project.prototype.getFileNames = function () { - if (this.languageServiceDiabled) { - if (!this.projectOptions) { - return undefined; - } - var fileNames = []; - if (this.projectOptions && this.projectOptions.compilerOptions) { - fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); - } - ts.addRange(fileNames, this.projectOptions.files); - return fileNames; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); - }; - Project.prototype.getSourceFile = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.filenameToSourceFile[info.fileName]; - }; - Project.prototype.getSourceFileFromName = function (filename, requireOpen) { - if (this.languageServiceDiabled) { - return undefined; - } - var info = this.projectService.getScriptInfo(filename); - if (info) { - if ((!requireOpen) || info.isOpen) { - return this.getSourceFile(info); - } - } - }; - Project.prototype.isRoot = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.compilerService.host.roots.some(function (root) { return root === info; }); - }; - Project.prototype.removeReferencedFile = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeReferencedFile(info); - this.updateGraph(); - }; - Project.prototype.updateFileMap = function () { - if (this.languageServiceDiabled) { - return; - } - this.filenameToSourceFile = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - Project.prototype.finishGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.updateGraph(); - this.compilerService.languageService.getNavigateToItems(".*"); - }; - Project.prototype.updateGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.program = this.compilerService.languageService.getProgram(); - this.updateFileMap(); - }; - Project.prototype.isConfiguredProject = function () { - return this.projectFilename; - }; - Project.prototype.addRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.addRoot(info); - }; - Project.prototype.removeRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeRoot(info); - }; - Project.prototype.filesToString = function () { - if (this.languageServiceDiabled) { - if (this.projectOptions) { - var strBuilder_1 = ""; - ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); - return strBuilder_1; - } - } - var strBuilder = ""; - ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { - var fileName = fileNames_3[_b]; - var info = this.getScriptInfo(fileName); - if (info.defaultProject == project) { - info.defaultProject = undefined; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { - var totalNonTsFileSize = 0; - if (!this.host.getFileSize) { - return false; - } - for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { - var fileName = fileNames_4[_i]; - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { - var _this = this; - var parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.projectOptions; - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - if (project.languageServiceDiabled) { - project.setProjectOptions(projectOptions); - project.enableLanguageService(); - project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, false); - project.addRoot(info); - } - } - project.finishGraph(); - return errors; - } - var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); - var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); - var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); - var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { - var fileName = fileNamesToRemove_1[_c]; - var info = this.getScriptInfo(fileName); - if (info) { - project.removeRoot(info); - } - } - for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { - var fileName = fileNamesToAdd_1[_d]; - var info = this.getScriptInfo(fileName); - if (!info) { - info = this.openFile(fileName, false); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62605,16 +64797,17 @@ var ts; var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62801,10 +64994,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +65016,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +65024,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +65056,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +65069,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -63011,7 +65207,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +65220,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63404,12 +65600,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63427,7 +65617,7 @@ var ts; server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63505,6 +65695,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63698,11 +65894,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -63881,6 +66078,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -63905,10 +66106,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -63930,10 +66132,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 9116a629d6d..c915bd9efc8 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -388,7 +389,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -425,12 +425,21 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; } @@ -438,6 +447,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -449,15 +459,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +482,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -513,22 +534,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -539,10 +561,12 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } /** @@ -555,95 +579,116 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,13 +696,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -671,42 +720,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +807,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } /** @@ -752,104 +859,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1002,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1092,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1105,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1218,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1149,7 +1361,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1178,8 +1390,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1458,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1372,6 +1585,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1601,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1495,8 +1710,6 @@ declare namespace ts { Intersection = 1048576, Anonymous = 2097152, Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, @@ -1509,7 +1722,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1531,6 +1744,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1614,15 +1828,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1872,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1742,6 +1954,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1846,7 +2059,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1944,10 +2157,6 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1958,18 +2167,6 @@ declare namespace ts { * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,6 +2176,24 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1995,7 +2210,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2007,12 +2222,13 @@ declare namespace ts { * file to. e.g. outDir */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } @@ -2118,6 +2334,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2372,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2397,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2413,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2445,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2500,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2513,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2535,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2642,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +2967,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/lib/typescript.js b/lib/typescript.js index 14fbdce59a8..c534a725901 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -502,6 +502,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -685,8 +686,6 @@ var ts; TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -709,7 +708,7 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589185] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ @@ -993,36 +992,44 @@ var ts; })(ts.TransformFlags || (ts.TransformFlags = {})); var TransformFlags = ts.TransformFlags; /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + EmitFlags[EmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + EmitFlags[EmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + EmitFlags[EmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + EmitFlags[EmitFlags["UMDDefine"] = 16] = "UMDDefine"; + EmitFlags[EmitFlags["SingleLine"] = 32] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 256] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 49152] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + EmitFlags[EmitFlags["ExportName"] = 131072] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 262144] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 524288] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.EmitFlags || (ts.EmitFlags = {})); + var EmitFlags = ts.EmitFlags; + /* @internal */ + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(ts.EmitContext || (ts.EmitContext = {})); + var EmitContext = ts.EmitContext; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,7 +1039,6 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { @@ -1164,6 +1170,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1171,6 +1178,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1501,6 +1515,7 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { @@ -1604,16 +1619,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1929,6 +1950,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -2096,7 +2167,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2202,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2256,49 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2625,6 +2742,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2737,7 +2862,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2757,9 +2881,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,30 +2901,7 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. @@ -2836,6 +2937,84 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); /// var ts; @@ -3040,9 +3219,17 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -3182,6 +3369,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3299,21 +3489,46 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3641,7 +3856,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3802,7 +4017,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -4035,6 +4250,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4059,6 +4276,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4088,7 +4306,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); /// @@ -5145,7 +5370,7 @@ var ts; return token = 69 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -6364,10 +6589,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } @@ -6636,6 +6861,12 @@ var ts; return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 /* MethodDeclaration */ && + (node.parent.kind === 171 /* ObjectLiteralExpression */ || + node.parent.kind === 192 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6723,11 +6954,11 @@ var ts; } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6988,12 +7219,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7655,16 +7880,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -8125,24 +8344,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,7 +8362,7 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified @@ -8184,7 +8391,7 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8217,7 +8424,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host, sourceFiles) { @@ -8242,7 +8449,7 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8275,12 +8482,13 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -8288,7 +8496,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8504,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8331,15 +8539,35 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8700,14 +8928,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8820,12 +9040,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8938,7 +9152,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,7 +9268,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -9179,15 +9393,16 @@ var ts; return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ + function isTemplateHead(node) { + return node.kind === 12 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 /* TemplateMiddle */ || kind === 14 /* TemplateTail */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { return node.kind === 69 /* Identifier */; @@ -9340,12 +9555,12 @@ var ts; return node.kind === 174 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 /* TemplateExpression */ || kind === 11 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191 /* SpreadElementExpression */; } @@ -9688,7 +9903,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; @@ -10029,7 +10243,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10064,7 +10278,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10364,7 +10578,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 1048576 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,7 +10587,7 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -10477,7 +10691,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10570,7 +10784,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -11492,7 +11706,7 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048 /* NoNestedSourceMaps */; return expression; } } @@ -11500,7 +11714,7 @@ var ts; function createRestParameter(name) { return createParameterDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*modifiers*/ undefined, createToken(22 /* DotDotDotToken */), name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -11630,13 +11844,13 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + var generatorFunc = createFunctionExpression(createToken(37 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152 /* AsyncFunctionBody */; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), /*typeArguments*/ undefined, [ createThis(), @@ -11953,7 +12167,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { + if (getEmitFlags(statement) & 8388608 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -11965,6 +12179,34 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + /** + * Ensures "use strict" directive is added + * + * @param node source file + */ + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -12323,17 +12565,180 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 256 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12376,13 +12781,13 @@ var ts; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -13683,8 +14088,8 @@ var ts; // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 24 /* CommaToken */; case 20 /* HeritageClauses */: return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: @@ -14135,7 +14540,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -14151,7 +14556,7 @@ var ts; var literal; if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -14162,8 +14567,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateMiddle */ || fragment.kind === 14 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -17144,7 +17556,7 @@ var ts; parseExpected(56 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a @@ -17702,6 +18114,7 @@ var ts; var parameter = createNode(142 /* Parameter */); parameter.type = parseJSDocType(); if (parseOptional(56 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? parameter.questionToken = createNode(56 /* EqualsToken */); } return finishNode(parameter); @@ -18895,6 +19308,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +19341,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +19356,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +19386,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -19134,11 +19558,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19243,7 +19680,7 @@ var ts; } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19705,7 +20142,11 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + // if try statement has finally block and flow after finally block is unreachable - keep it + // otherwise use whatever flow was accumulated at postFinallyLabel + if (!node.finallyBlock || !(currentFlow.flags & 1 /* Unreachable */)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19840,7 +20281,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } @@ -19942,9 +20383,12 @@ var ts; return 1 /* IsContainer */ | 32 /* HasLocals */; case 256 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 147 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } case 148 /* Constructor */: case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: @@ -20588,10 +21032,13 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { @@ -20829,6 +21276,9 @@ var ts; emitFlags |= 2048 /* HasDecorators */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20994,8 +21444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + if (subtreeFlags & 2048 /* ContainsDecorators */ || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. @@ -21128,7 +21577,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21190,7 +21639,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } } @@ -21216,7 +21665,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21500,6 +21949,677 @@ var ts; return transformFlags & ~excludeFlags; } })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /* @internal */ + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @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(candidate, extensions, failedLookupLocation, 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" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // 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 (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.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 + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + /* @internal */ + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + // Try to load source from the package + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + } + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + // If we didn't find the file normally, look it up in @types. + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /** Climb up parent directories looking for a module. */ + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21607,6 +22727,7 @@ var ts; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); @@ -22350,7 +23471,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -22833,6 +23954,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -23407,9 +24530,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,7 +24576,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -23471,9 +24594,14 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible + // We emit inferred type as type-alias at the current localtion if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } @@ -23549,14 +24677,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -23960,14 +25088,14 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: @@ -24274,6 +25402,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 /* NullKeyword */ || expr.kind === 69 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24306,6 +25438,13 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } + // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer + // or a 'null' or 'undefined' initializer. + if (declaration.kind === 218 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present @@ -24389,7 +25528,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -24935,7 +26074,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -25509,7 +26649,7 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type @@ -25517,7 +26657,19 @@ var ts; break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -25566,6 +26718,7 @@ var ts; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25584,21 +26737,20 @@ var ts; } } else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +26761,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +26790,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -26040,7 +27200,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26365,7 +27525,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26466,7 +27627,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -27553,7 +28731,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 2588672 /* ObjectType */) && + (!(target.flags & 2588672 /* ObjectType */) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -28917,21 +30096,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -29218,6 +30386,26 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29232,7 +30420,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -29304,10 +30494,13 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 /* Union */ ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29531,12 +30724,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 2589185 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29581,7 +30774,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29728,7 +30922,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29877,20 +31071,32 @@ var ts; // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (flowContainer.kind === 179 /* FunctionExpression */ || + flowContainer.kind === 180 /* ArrowFunction */ || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -29988,7 +31194,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30081,7 +31287,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.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]() { .... } @@ -30141,8 +31347,8 @@ var ts; var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting while (container && container.kind === 180 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; @@ -30954,7 +32160,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 /* ObjectType */ && contextualType.isObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -31014,7 +32221,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -31523,7 +32733,7 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } @@ -31567,7 +32777,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } @@ -31848,13 +33058,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } @@ -31862,7 +33072,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -33121,7 +34331,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33305,7 +34517,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -34388,9 +35600,9 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -34628,7 +35840,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34657,6 +35869,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34677,7 +35890,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -35607,7 +36820,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -35622,9 +36835,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -35772,6 +36982,10 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -35926,6 +37140,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35946,12 +37163,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35973,7 +37190,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -35985,7 +37202,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -36480,7 +37697,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -37288,9 +38510,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37568,9 +38792,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 /* SourceFile */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 225 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37668,7 +38894,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 220 /* FunctionDeclaration */ && declaration.kind !== 147 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -38202,6 +39429,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access @@ -38726,9 +39956,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38852,9 +40082,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -39437,8 +40667,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -39550,8 +40780,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { + if (name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_24); } @@ -39731,17 +40960,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -40673,7 +41893,7 @@ var ts; case 175 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179 /* FunctionExpression */: @@ -40697,7 +41917,7 @@ var ts; case 188 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* SpreadElementExpression */: @@ -40708,7 +41928,7 @@ var ts; return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element case 199 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); @@ -41055,7 +42275,7 @@ var ts; var expression = ts.createAssignment(name, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -41081,7 +42301,7 @@ var ts; var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -41114,7 +42334,7 @@ var ts; declaration.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -41164,7 +42384,7 @@ var ts; expression.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); pendingAssignments.push(expression); return expression; } @@ -41210,8 +42430,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, /*original*/ undefined); } } @@ -41380,7 +42600,7 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,11 +42611,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -41424,6 +42648,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } /** @@ -41434,10 +42661,14 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -41702,11 +42933,23 @@ var ts; case 226 /* ModuleBlock */: case 199 /* Block */: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221 /* ClassDeclaration */: + case 220 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + // ensure "use strict" is emitted in all scenarios in alwaysStrict mode + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } // If the source file requires any helpers and is an external module, and // the importHelpers compiler option is enabled, emit a synthesized import // statement for the helpers library. @@ -41733,7 +42976,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + ts.setEmitFlags(node, 1 /* EmitEmitHelpers */ | ts.getEmitFlags(node)); return node; } /** @@ -41792,7 +43035,7 @@ var ts; // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -41951,7 +43194,7 @@ var ts; /*type*/ undefined, classExpression) ]), /*location*/ location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode( /*node*/ transformedClassExpression, /*original*/ node)); @@ -41996,7 +43239,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -42151,7 +43394,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +43428,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 49152 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42239,8 +43482,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -42257,8 +43500,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42524,7 +43767,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); return helper; } /** @@ -42562,12 +43805,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } } @@ -42593,7 +43836,7 @@ var ts; var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); expressions.push(helper); } } @@ -42824,10 +44067,38 @@ var ts; : ts.createIdentifier("Symbol"); case 155 /* TypeReference */: return serializeTypeReferenceNode(node); + case 163 /* IntersectionType */: + case 162 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 69 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough case 158 /* TypeQuery */: case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: case 117 /* AnyKeyword */: case 165 /* ThisType */: break; @@ -43027,8 +44298,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -43060,8 +44331,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43083,8 +44354,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43220,11 +44491,11 @@ var ts; if (languageVersion >= 2 /* ES6 */) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + ts.setEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + ts.setEmitFlags(block, 4 /* EmitSuperHelper */); } } return block; @@ -43244,7 +44515,7 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration( @@ -43256,9 +44527,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); return parameter; } /** @@ -43351,8 +44622,9 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1 /* Export */) + || isES6ExportedDeclaration(node)); } /* * Adds a trailing VariableStatement for an enum or module declaration. @@ -43361,7 +44633,7 @@ var ts; var statement = ts.createVariableStatement( /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } /** @@ -43382,6 +44654,7 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43407,7 +44680,7 @@ var ts; /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -43473,18 +44746,43 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -43499,10 +44797,10 @@ var ts; ts.setOriginalNode(statement, /*original*/ node); // Adjust the source map emit to match the old emitter. if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } // Trailing comments for module declaration should be emitted after the function closure // instead of the variable statement: @@ -43522,8 +44820,8 @@ var ts; // } // })(m1 || (m1 = {})); // trailing comment module // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768 /* NoTrailingComments */); statements.push(statement); } /** @@ -43546,6 +44844,7 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43579,7 +44878,7 @@ var ts; /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } @@ -43591,8 +44890,10 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -43619,6 +44920,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43644,7 +44946,7 @@ var ts; // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152 /* NoComments */); } return block; } @@ -43680,7 +44982,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; @@ -43736,9 +45038,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -43761,7 +45063,7 @@ var ts; emitFlags |= 1536 /* NoSourceMap */; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -43773,7 +45075,7 @@ var ts; */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43822,8 +45124,8 @@ var ts; */ function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -43831,9 +45133,9 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -43910,7 +45212,7 @@ var ts; * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; // If we need to support substitutions for `super` in an async method, @@ -43924,7 +45226,7 @@ var ts; if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } @@ -43935,9 +45237,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,16 +45249,16 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_30, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_30, exportedName, /*location*/ node); } } return node; @@ -43965,16 +45267,15 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 174 /* CallExpression */: + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -43996,8 +45297,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -44007,7 +45308,7 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); @@ -44038,23 +45339,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096 /* AsyncMethodWithSuperBinding */) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), @@ -44083,6 +45409,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -44201,7 +45530,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -44230,6 +45559,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -44283,7 +45615,7 @@ var ts; ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + /*type*/ undefined, ts.setEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); // Write the call to `System.register` // Clear the emit-helpers flag for later passes since we'll have already used it in the module body // So the helper will be emit at the correct position instead of at the top of the source-file @@ -44292,7 +45624,7 @@ var ts; /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & ts.getEmitFlags(node)); var _a; } /** @@ -44676,17 +46008,17 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); var newNode = ts.createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, + /*modifiers*/ undefined, node.asteriskToken, name_31, /*typeParameters*/ undefined, node.parameters, /*type*/ undefined, node.body, /*location*/ node); // Record a declaration export in the outer module body function. recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -44698,16 +46030,16 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); // We only need to hoistVariableDeclaration for EnumDeclaration // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement // which then call transformsVariable for each declaration in declarationList if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -44952,14 +46284,14 @@ var ts; // // Substitutions // - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -44969,9 +46301,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -45013,7 +46345,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var left = node.left; switch (left.kind) { case 69 /* Identifier */: @@ -45118,7 +46450,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); + ts.setEmitFlags(expr, 128 /* NoSubstitution */); var call = createExportExpression(operand, expr); if (node.kind === 185 /* PrefixUnaryExpression */) { return call; @@ -45165,7 +46497,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) ])), ts.createStatement(ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exports])) @@ -45283,7 +46615,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -45301,7 +46633,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -45333,6 +46665,9 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; // Collect information about the external module. @@ -45365,7 +46700,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 /* EmitExportStar */ | ts.getEmitFlags(node)); } return updated; } @@ -45386,7 +46721,7 @@ var ts; */ function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); + ts.setEmitFlags(define, 16 /* UMDDefine */); return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); } /** @@ -45466,7 +46801,7 @@ var ts; if (hasExportStarsToExportValues) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); + ts.setEmitFlags(body, 2 /* EmitExportStar */); } return body; } @@ -45475,13 +46810,13 @@ var ts; if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); statements.push(statement); } } @@ -45574,7 +46909,7 @@ var ts; } // Set emitFlags on the name of the importEqualsDeclaration // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + ts.setEmitFlags(node.name, 128 /* NoSubstitution */); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { @@ -45678,16 +47013,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -45706,7 +47041,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), /*location*/ node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); } } function visitVariableStatement(node) { @@ -45856,20 +47191,20 @@ var ts; /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + ts.setEmitFlags(transformedStatement, 49152 /* NoComments */); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -45879,9 +47214,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -45925,7 +47260,7 @@ var ts; // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -45945,13 +47280,13 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var transformedUnaryExpression = void 0; if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), /*location*/ node); // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + ts.setEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -45966,7 +47301,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144 /* LocalName */) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); if (container) { @@ -45979,7 +47314,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if ((ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -45994,14 +47329,14 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), /*location*/ node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), /*location*/ node); } } @@ -46025,7 +47360,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -46063,7 +47398,7 @@ var ts; if (includeNonAmdDependencies && importAliasName) { // Set emitFlags on the name of the classDeclaration // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + ts.setEmitFlags(importAliasName, 128 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -46098,6 +47433,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -46280,12 +47618,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -46575,6 +47913,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -46820,7 +48161,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,6 +48211,9 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024 /* ContainsGenerator */) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -47011,7 +48355,7 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -47050,7 +48394,7 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, node.parameters, @@ -47099,6 +48443,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +48457,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47132,6 +48478,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47156,7 +48503,7 @@ var ts; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 8388608 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -48202,9 +49549,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,11 +49568,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -48815,7 +50162,7 @@ var ts; return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), /*typeArguments*/ undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( + ts.setEmitFlags(ts.createFunctionExpression( /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(state)], @@ -49218,8 +50565,32 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -49247,6 +50618,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -49418,7 +50792,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180 /* ArrowFunction */) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + if (!(ts.getEmitFlags(currentNode) & 2097152 /* AsyncFunctionBody */)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -49634,17 +51008,17 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); + if (ts.getEmitFlags(node) & 524288 /* Indented */) { + ts.setEmitFlags(classFunction, 524288 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); + ts.setEmitFlags(inner, 49152 /* NoComments */); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); return ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] @@ -49669,14 +51043,14 @@ var ts; // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); return block; } /** @@ -49702,13 +51076,17 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( + var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, getDeclarationName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256 /* CapturesThis */); + } + statements.push(constructorFunction); } /** * Transforms the parameters of the constructor declaration of a class. @@ -49740,51 +51118,146 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 1; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); }); ts.addRange(statements, body); } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), /*location*/ constructor ? constructor.body : node, /*multiLine*/ true); if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 211 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 203 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; } /** - * Adds a synthesized call to `_super` if it is needed. + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. + * @returns The new statement offset into the `statements` array. */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement. + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } /** * Visits a parameter declaration. @@ -49837,17 +51310,17 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } @@ -49865,11 +51338,11 @@ var ts; // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); } } /** @@ -49882,14 +51355,14 @@ var ts; */ function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), ts.setEmitFlags(initializer, 1536 /* NoSourceMap */ | ts.getEmitFlags(initializer)), /*location*/ parameter)) ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), /*elseStatement*/ undefined, /*location*/ parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); statements.push(statement); } /** @@ -49919,13 +51392,13 @@ var ts; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + ts.setEmitFlags(declarationName, 1536 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -49941,7 +51414,7 @@ var ts; ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), /*location*/ parameter)) ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 8388608 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -49953,17 +51426,20 @@ var ts; */ function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } /** * Adds statements to the class body function for a class to define the members of the * class. @@ -50012,20 +51488,20 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152 /* NoComments */); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name), func), /*location*/ member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); + ts.setCommentRange(statement, commentRange); // The location for the statement is used to emit comments only. // No source map should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + ts.setEmitFlags(statement, 1536 /* NoSourceMap */); return statement; } /** @@ -50036,11 +51512,11 @@ var ts; */ function transformAccessorsToStatement(receiver, accessors) { var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); return statement; } /** @@ -50054,24 +51530,24 @@ var ts; // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -50096,7 +51572,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); + ts.setEmitFlags(func, 256 /* CapturesThis */); return func; } /** @@ -50191,7 +51667,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + ts.setEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom // source map location for the close brace. @@ -50205,10 +51681,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); + ts.setEmitFlags(block, 32 /* SingleLine */); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -50274,7 +51750,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -50303,7 +51779,7 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { @@ -50311,7 +51787,7 @@ var ts; // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -50501,7 +51977,7 @@ var ts; // emitter. var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -50549,12 +52025,12 @@ var ts; } } // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 /* NoSourceMap */ | ts.getEmitFlags(expression)); // The old emitter does not emit source maps for the block. // We add the location to preserve comments. var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) @@ -50562,7 +52038,7 @@ var ts; /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, /*location*/ node); // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + ts.setEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); return forStatement; } /** @@ -50591,7 +52067,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), /*location*/ undefined, node.multiLine), 524288 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; @@ -50698,7 +52174,7 @@ var ts; loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152 /* AsyncFunctionBody */) !== 0 && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -50710,7 +52186,7 @@ var ts; var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) @@ -50756,8 +52232,8 @@ var ts; extraVariableDeclarations = []; } // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -50767,8 +52243,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -51003,7 +52479,7 @@ var ts; // Methods with computed property names are handled in visitObjectLiteralExpression. ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, /*location*/ node); } @@ -51040,9 +52516,19 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 128 /* NoSubstitution */); + } + var resultingCall; if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { // [source] // f(...a, b) @@ -51057,7 +52543,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -51069,9 +52555,18 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } + if (node.expression.kind === 95 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } /** * Visits a NewExpression that contains a spread element. @@ -51313,13 +52808,13 @@ var ts; * * @param node The node to be printed. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } /** @@ -51356,9 +52851,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -51434,7 +52929,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + && ts.getEmitFlags(enclosingFunction) & 256 /* CapturesThis */) { return ts.createIdentifier("_this", /*location*/ node); } return node; @@ -51461,7 +52956,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -51469,7 +52964,7 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -51552,13 +53047,6 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,16 +53056,9 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -51588,56 +53069,27 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +53112,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 128 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +53146,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51891,95 +53236,12 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +53250,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,24 +53264,15 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; @@ -52034,12 +53285,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +53346,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +53356,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +53403,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +53432,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 512 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 1024 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +53511,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,6 +53537,9 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -52349,6 +53555,9 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +53568,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52457,21 +53627,23 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -52505,10 +53677,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,7 +53707,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { @@ -52542,8 +53716,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52664,16 +53840,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +53901,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52786,7 +53952,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52987,7 +54153,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,7 +54166,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53202,7 +54368,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53624,7 +54790,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -54265,7 +55431,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +55440,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54294,8 +55460,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,8 +55501,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); // emit output for the __extends helper function @@ -54352,7 +55520,7 @@ var ts; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; // The __generator helper is used by down-level transformations to emulate the runtime // semantics of an ES2015 generator function. When called, this helper returns an // object that implements the Iterator protocol, in that it has `next`, `return`, and @@ -54426,11 +55594,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54447,18 +55615,20 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +55638,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54494,8 +55668,8 @@ var ts; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -54536,135 +55710,124 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals @@ -54696,7 +55859,8 @@ var ts; case 132 /* StringKeyword */: case 133 /* SymbolKeyword */: case 137 /* GlobalKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Parse tree nodes // Names case 139 /* QualifiedName */: @@ -54886,18 +56050,20 @@ var ts; // Enum case 255 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals @@ -54916,7 +56082,8 @@ var ts; case 95 /* SuperKeyword */: case 99 /* TrueKeyword */: case 97 /* ThisKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Expressions case 170 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); @@ -55010,7 +56177,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { + if (ts.getEmitFlags(node) & 16 /* UMDDefine */) { writeLines(umdHelper); } else { @@ -55243,7 +56410,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +56423,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 1048576 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55284,17 +56448,16 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55467,7 +56630,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 32 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55645,11 +56808,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 4194304 /* ReuseTempVariableScope */) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -55687,7 +56850,7 @@ var ts; // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 32 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55743,7 +56906,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55805,7 +56968,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -56023,8 +57186,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56084,7 +57247,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1 /* EmitEmitHelpers */) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -56197,31 +57360,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +57467,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +57513,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56539,17 +57662,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56878,695 +57996,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @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(candidate, extensions, failedLookupLocation, 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" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // 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 (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.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 - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +58101,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57740,45 +58169,6 @@ var ts; } return resolutions; } - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57815,7 +58205,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +58213,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,8 +58223,8 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); @@ -57884,7 +58274,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57938,6 +58329,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -58054,16 +58446,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +58490,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58659,7 +59054,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; // add file to program only if: // - resolution was successful // - noResolve is falsy @@ -58676,7 +59070,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { @@ -58692,8 +59086,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +59098,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +59142,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +59153,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,6 +59193,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58891,12 +59288,15 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -59327,6 +59727,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ @@ -59547,10 +59952,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59712,13 +60118,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) @@ -59799,6 +60207,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -59812,7 +60231,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -60742,7 +61163,7 @@ var ts; return true; case 69 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142 /* Parameter */; default: return false; } @@ -61420,7 +61841,6 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; @@ -61657,7 +62077,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -61671,14 +62091,17 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -62538,8 +62961,7 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62583,14 +63005,14 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -62619,7 +63041,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); @@ -62690,7 +63112,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 253 /* PropertyAssignment */ && + node.parent.parent.kind === 171 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62740,7 +63164,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -62756,7 +63180,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +63190,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +63201,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62819,6 +63243,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +63279,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +63304,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +63479,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +63499,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63285,7 +63732,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63349,6 +63796,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63382,11 +63830,13 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { @@ -63448,6 +63898,7 @@ var ts; if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -64026,9 +64477,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,6 +66901,7 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -66458,10 +66918,13 @@ var ts; return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -66552,13 +67015,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +67033,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -66616,7 +67076,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -66624,6 +67084,9 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); for (var name_49 in nameToDeclarations) { var declarations = nameToDeclarations[name_49]; @@ -66803,6 +67266,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -67077,7 +67547,7 @@ var ts; } } // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { @@ -67242,6 +67712,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +67744,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -71005,25 +71484,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +71512,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +71524,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +71534,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +71542,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +71550,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +71564,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71222,7 +71701,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 225 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); + return body && body.kind === 226 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 256 /* SourceFile */: case 199 /* Block */: case 226 /* ModuleBlock */: @@ -71332,7 +71811,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +71883,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +71891,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71493,13 +71972,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71919,7 +72398,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71980,14 +72459,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +72481,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +72524,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +72540,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72095,7 +72574,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +72585,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +72597,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +72640,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72371,7 +72850,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72473,6 +72952,117 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 174 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -72498,13 +73088,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(69 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72732,15 +73324,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -72816,7 +73409,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72985,6 +73578,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +73617,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73185,7 +73806,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +73846,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73553,12 +74181,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +74197,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73647,14 +74275,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73715,34 +74357,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73926,6 +74594,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +74604,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -74624,7 +75294,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74712,6 +75382,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74914,11 +75590,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +75833,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +75863,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +75890,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index e9c209674b5..5f319ffb74c 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -388,7 +389,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -425,12 +425,21 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; } @@ -438,6 +447,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -449,15 +459,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +482,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -513,22 +534,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -539,10 +561,12 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } /** @@ -555,95 +579,116 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,13 +696,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -671,42 +720,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +807,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } /** @@ -752,104 +859,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1002,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1092,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1105,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1218,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1149,7 +1361,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1178,8 +1390,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1458,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1372,6 +1585,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1601,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1495,8 +1710,6 @@ declare namespace ts { Intersection = 1048576, Anonymous = 2097152, Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, @@ -1509,7 +1722,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1531,6 +1744,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1614,15 +1828,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1872,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1742,6 +1954,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1846,7 +2059,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1944,10 +2157,6 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1958,18 +2167,6 @@ declare namespace ts { * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,6 +2176,24 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1995,7 +2210,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2007,12 +2222,13 @@ declare namespace ts { * file to. e.g. outDir */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } @@ -2118,6 +2334,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2372,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2397,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2413,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2445,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2500,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2513,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2535,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2642,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +2967,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 14fbdce59a8..c534a725901 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -502,6 +502,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -685,8 +686,6 @@ var ts; TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -709,7 +708,7 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589185] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ @@ -993,36 +992,44 @@ var ts; })(ts.TransformFlags || (ts.TransformFlags = {})); var TransformFlags = ts.TransformFlags; /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + EmitFlags[EmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + EmitFlags[EmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + EmitFlags[EmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + EmitFlags[EmitFlags["UMDDefine"] = 16] = "UMDDefine"; + EmitFlags[EmitFlags["SingleLine"] = 32] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 256] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 49152] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + EmitFlags[EmitFlags["ExportName"] = 131072] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 262144] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 524288] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.EmitFlags || (ts.EmitFlags = {})); + var EmitFlags = ts.EmitFlags; + /* @internal */ + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(ts.EmitContext || (ts.EmitContext = {})); + var EmitContext = ts.EmitContext; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,7 +1039,6 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { @@ -1164,6 +1170,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1171,6 +1178,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1501,6 +1515,7 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { @@ -1604,16 +1619,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1929,6 +1950,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -2096,7 +2167,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2202,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2256,49 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2625,6 +2742,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2737,7 +2862,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2757,9 +2881,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,30 +2901,7 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. @@ -2836,6 +2937,84 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); /// var ts; @@ -3040,9 +3219,17 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -3182,6 +3369,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3299,21 +3489,46 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3641,7 +3856,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3802,7 +4017,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -4035,6 +4250,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4059,6 +4276,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4088,7 +4306,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); /// @@ -5145,7 +5370,7 @@ var ts; return token = 69 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -6364,10 +6589,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } @@ -6636,6 +6861,12 @@ var ts; return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 /* MethodDeclaration */ && + (node.parent.kind === 171 /* ObjectLiteralExpression */ || + node.parent.kind === 192 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6723,11 +6954,11 @@ var ts; } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6988,12 +7219,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7655,16 +7880,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -8125,24 +8344,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,7 +8362,7 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified @@ -8184,7 +8391,7 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8217,7 +8424,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host, sourceFiles) { @@ -8242,7 +8449,7 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8275,12 +8482,13 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -8288,7 +8496,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8504,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8331,15 +8539,35 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8700,14 +8928,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8820,12 +9040,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8938,7 +9152,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,7 +9268,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -9179,15 +9393,16 @@ var ts; return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ + function isTemplateHead(node) { + return node.kind === 12 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 /* TemplateMiddle */ || kind === 14 /* TemplateTail */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { return node.kind === 69 /* Identifier */; @@ -9340,12 +9555,12 @@ var ts; return node.kind === 174 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 /* TemplateExpression */ || kind === 11 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191 /* SpreadElementExpression */; } @@ -9688,7 +9903,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; @@ -10029,7 +10243,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10064,7 +10278,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10364,7 +10578,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 1048576 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,7 +10587,7 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -10477,7 +10691,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10570,7 +10784,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -11492,7 +11706,7 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048 /* NoNestedSourceMaps */; return expression; } } @@ -11500,7 +11714,7 @@ var ts; function createRestParameter(name) { return createParameterDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*modifiers*/ undefined, createToken(22 /* DotDotDotToken */), name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -11630,13 +11844,13 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + var generatorFunc = createFunctionExpression(createToken(37 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152 /* AsyncFunctionBody */; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), /*typeArguments*/ undefined, [ createThis(), @@ -11953,7 +12167,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { + if (getEmitFlags(statement) & 8388608 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -11965,6 +12179,34 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + /** + * Ensures "use strict" directive is added + * + * @param node source file + */ + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -12323,17 +12565,180 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 256 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12376,13 +12781,13 @@ var ts; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -13683,8 +14088,8 @@ var ts; // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 24 /* CommaToken */; case 20 /* HeritageClauses */: return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: @@ -14135,7 +14540,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -14151,7 +14556,7 @@ var ts; var literal; if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -14162,8 +14567,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateMiddle */ || fragment.kind === 14 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -17144,7 +17556,7 @@ var ts; parseExpected(56 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a @@ -17702,6 +18114,7 @@ var ts; var parameter = createNode(142 /* Parameter */); parameter.type = parseJSDocType(); if (parseOptional(56 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? parameter.questionToken = createNode(56 /* EqualsToken */); } return finishNode(parameter); @@ -18895,6 +19308,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +19341,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +19356,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +19386,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -19134,11 +19558,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19243,7 +19680,7 @@ var ts; } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19705,7 +20142,11 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + // if try statement has finally block and flow after finally block is unreachable - keep it + // otherwise use whatever flow was accumulated at postFinallyLabel + if (!node.finallyBlock || !(currentFlow.flags & 1 /* Unreachable */)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19840,7 +20281,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } @@ -19942,9 +20383,12 @@ var ts; return 1 /* IsContainer */ | 32 /* HasLocals */; case 256 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 147 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } case 148 /* Constructor */: case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: @@ -20588,10 +21032,13 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { @@ -20829,6 +21276,9 @@ var ts; emitFlags |= 2048 /* HasDecorators */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20994,8 +21444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + if (subtreeFlags & 2048 /* ContainsDecorators */ || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. @@ -21128,7 +21577,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21190,7 +21639,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } } @@ -21216,7 +21665,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21500,6 +21949,677 @@ var ts; return transformFlags & ~excludeFlags; } })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /* @internal */ + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @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(candidate, extensions, failedLookupLocation, 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" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // 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 (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.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 + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + /* @internal */ + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + // Try to load source from the package + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + } + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + // If we didn't find the file normally, look it up in @types. + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /** Climb up parent directories looking for a module. */ + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21607,6 +22727,7 @@ var ts; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); @@ -22350,7 +23471,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -22833,6 +23954,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -23407,9 +24530,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,7 +24576,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -23471,9 +24594,14 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible + // We emit inferred type as type-alias at the current localtion if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } @@ -23549,14 +24677,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -23960,14 +25088,14 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: @@ -24274,6 +25402,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 /* NullKeyword */ || expr.kind === 69 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24306,6 +25438,13 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } + // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer + // or a 'null' or 'undefined' initializer. + if (declaration.kind === 218 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present @@ -24389,7 +25528,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -24935,7 +26074,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -25509,7 +26649,7 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type @@ -25517,7 +26657,19 @@ var ts; break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -25566,6 +26718,7 @@ var ts; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25584,21 +26737,20 @@ var ts; } } else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +26761,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +26790,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -26040,7 +27200,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26365,7 +27525,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26466,7 +27627,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -27553,7 +28731,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 2588672 /* ObjectType */) && + (!(target.flags & 2588672 /* ObjectType */) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -28917,21 +30096,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -29218,6 +30386,26 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29232,7 +30420,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -29304,10 +30494,13 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 /* Union */ ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29531,12 +30724,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 2589185 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29581,7 +30774,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29728,7 +30922,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29877,20 +31071,32 @@ var ts; // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (flowContainer.kind === 179 /* FunctionExpression */ || + flowContainer.kind === 180 /* ArrowFunction */ || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -29988,7 +31194,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30081,7 +31287,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.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]() { .... } @@ -30141,8 +31347,8 @@ var ts; var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting while (container && container.kind === 180 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; @@ -30954,7 +32160,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 /* ObjectType */ && contextualType.isObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -31014,7 +32221,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -31523,7 +32733,7 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } @@ -31567,7 +32777,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } @@ -31848,13 +33058,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } @@ -31862,7 +33072,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -33121,7 +34331,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33305,7 +34517,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -34388,9 +35600,9 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -34628,7 +35840,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34657,6 +35869,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34677,7 +35890,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -35607,7 +36820,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -35622,9 +36835,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -35772,6 +36982,10 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -35926,6 +37140,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35946,12 +37163,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35973,7 +37190,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -35985,7 +37202,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -36480,7 +37697,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -37288,9 +38510,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37568,9 +38792,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 /* SourceFile */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 225 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37668,7 +38894,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 220 /* FunctionDeclaration */ && declaration.kind !== 147 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -38202,6 +39429,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access @@ -38726,9 +39956,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38852,9 +40082,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -39437,8 +40667,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -39550,8 +40780,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { + if (name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_24); } @@ -39731,17 +40960,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -40673,7 +41893,7 @@ var ts; case 175 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179 /* FunctionExpression */: @@ -40697,7 +41917,7 @@ var ts; case 188 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* SpreadElementExpression */: @@ -40708,7 +41928,7 @@ var ts; return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element case 199 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); @@ -41055,7 +42275,7 @@ var ts; var expression = ts.createAssignment(name, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -41081,7 +42301,7 @@ var ts; var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -41114,7 +42334,7 @@ var ts; declaration.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -41164,7 +42384,7 @@ var ts; expression.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); pendingAssignments.push(expression); return expression; } @@ -41210,8 +42430,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, /*original*/ undefined); } } @@ -41380,7 +42600,7 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,11 +42611,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -41424,6 +42648,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } /** @@ -41434,10 +42661,14 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -41702,11 +42933,23 @@ var ts; case 226 /* ModuleBlock */: case 199 /* Block */: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221 /* ClassDeclaration */: + case 220 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + // ensure "use strict" is emitted in all scenarios in alwaysStrict mode + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } // If the source file requires any helpers and is an external module, and // the importHelpers compiler option is enabled, emit a synthesized import // statement for the helpers library. @@ -41733,7 +42976,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + ts.setEmitFlags(node, 1 /* EmitEmitHelpers */ | ts.getEmitFlags(node)); return node; } /** @@ -41792,7 +43035,7 @@ var ts; // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -41951,7 +43194,7 @@ var ts; /*type*/ undefined, classExpression) ]), /*location*/ location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode( /*node*/ transformedClassExpression, /*original*/ node)); @@ -41996,7 +43239,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -42151,7 +43394,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +43428,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 49152 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42239,8 +43482,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -42257,8 +43500,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42524,7 +43767,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); return helper; } /** @@ -42562,12 +43805,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } } @@ -42593,7 +43836,7 @@ var ts; var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); expressions.push(helper); } } @@ -42824,10 +44067,38 @@ var ts; : ts.createIdentifier("Symbol"); case 155 /* TypeReference */: return serializeTypeReferenceNode(node); + case 163 /* IntersectionType */: + case 162 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 69 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough case 158 /* TypeQuery */: case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: case 117 /* AnyKeyword */: case 165 /* ThisType */: break; @@ -43027,8 +44298,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -43060,8 +44331,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43083,8 +44354,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43220,11 +44491,11 @@ var ts; if (languageVersion >= 2 /* ES6 */) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + ts.setEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + ts.setEmitFlags(block, 4 /* EmitSuperHelper */); } } return block; @@ -43244,7 +44515,7 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration( @@ -43256,9 +44527,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); return parameter; } /** @@ -43351,8 +44622,9 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1 /* Export */) + || isES6ExportedDeclaration(node)); } /* * Adds a trailing VariableStatement for an enum or module declaration. @@ -43361,7 +44633,7 @@ var ts; var statement = ts.createVariableStatement( /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } /** @@ -43382,6 +44654,7 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43407,7 +44680,7 @@ var ts; /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -43473,18 +44746,43 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -43499,10 +44797,10 @@ var ts; ts.setOriginalNode(statement, /*original*/ node); // Adjust the source map emit to match the old emitter. if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } // Trailing comments for module declaration should be emitted after the function closure // instead of the variable statement: @@ -43522,8 +44820,8 @@ var ts; // } // })(m1 || (m1 = {})); // trailing comment module // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768 /* NoTrailingComments */); statements.push(statement); } /** @@ -43546,6 +44844,7 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43579,7 +44878,7 @@ var ts; /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } @@ -43591,8 +44890,10 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -43619,6 +44920,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43644,7 +44946,7 @@ var ts; // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152 /* NoComments */); } return block; } @@ -43680,7 +44982,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; @@ -43736,9 +45038,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -43761,7 +45063,7 @@ var ts; emitFlags |= 1536 /* NoSourceMap */; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -43773,7 +45075,7 @@ var ts; */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43822,8 +45124,8 @@ var ts; */ function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -43831,9 +45133,9 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -43910,7 +45212,7 @@ var ts; * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; // If we need to support substitutions for `super` in an async method, @@ -43924,7 +45226,7 @@ var ts; if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } @@ -43935,9 +45237,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,16 +45249,16 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_30, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_30, exportedName, /*location*/ node); } } return node; @@ -43965,16 +45267,15 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 174 /* CallExpression */: + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -43996,8 +45297,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -44007,7 +45308,7 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); @@ -44038,23 +45339,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096 /* AsyncMethodWithSuperBinding */) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), @@ -44083,6 +45409,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -44201,7 +45530,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -44230,6 +45559,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -44283,7 +45615,7 @@ var ts; ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + /*type*/ undefined, ts.setEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); // Write the call to `System.register` // Clear the emit-helpers flag for later passes since we'll have already used it in the module body // So the helper will be emit at the correct position instead of at the top of the source-file @@ -44292,7 +45624,7 @@ var ts; /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & ts.getEmitFlags(node)); var _a; } /** @@ -44676,17 +46008,17 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); var newNode = ts.createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, + /*modifiers*/ undefined, node.asteriskToken, name_31, /*typeParameters*/ undefined, node.parameters, /*type*/ undefined, node.body, /*location*/ node); // Record a declaration export in the outer module body function. recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -44698,16 +46030,16 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); // We only need to hoistVariableDeclaration for EnumDeclaration // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement // which then call transformsVariable for each declaration in declarationList if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -44952,14 +46284,14 @@ var ts; // // Substitutions // - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -44969,9 +46301,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -45013,7 +46345,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var left = node.left; switch (left.kind) { case 69 /* Identifier */: @@ -45118,7 +46450,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); + ts.setEmitFlags(expr, 128 /* NoSubstitution */); var call = createExportExpression(operand, expr); if (node.kind === 185 /* PrefixUnaryExpression */) { return call; @@ -45165,7 +46497,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) ])), ts.createStatement(ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exports])) @@ -45283,7 +46615,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -45301,7 +46633,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -45333,6 +46665,9 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; // Collect information about the external module. @@ -45365,7 +46700,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 /* EmitExportStar */ | ts.getEmitFlags(node)); } return updated; } @@ -45386,7 +46721,7 @@ var ts; */ function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); + ts.setEmitFlags(define, 16 /* UMDDefine */); return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); } /** @@ -45466,7 +46801,7 @@ var ts; if (hasExportStarsToExportValues) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); + ts.setEmitFlags(body, 2 /* EmitExportStar */); } return body; } @@ -45475,13 +46810,13 @@ var ts; if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); statements.push(statement); } } @@ -45574,7 +46909,7 @@ var ts; } // Set emitFlags on the name of the importEqualsDeclaration // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + ts.setEmitFlags(node.name, 128 /* NoSubstitution */); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { @@ -45678,16 +47013,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -45706,7 +47041,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), /*location*/ node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); } } function visitVariableStatement(node) { @@ -45856,20 +47191,20 @@ var ts; /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + ts.setEmitFlags(transformedStatement, 49152 /* NoComments */); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -45879,9 +47214,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -45925,7 +47260,7 @@ var ts; // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -45945,13 +47280,13 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var transformedUnaryExpression = void 0; if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), /*location*/ node); // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + ts.setEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -45966,7 +47301,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144 /* LocalName */) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); if (container) { @@ -45979,7 +47314,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if ((ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -45994,14 +47329,14 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), /*location*/ node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), /*location*/ node); } } @@ -46025,7 +47360,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -46063,7 +47398,7 @@ var ts; if (includeNonAmdDependencies && importAliasName) { // Set emitFlags on the name of the classDeclaration // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + ts.setEmitFlags(importAliasName, 128 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -46098,6 +47433,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -46280,12 +47618,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -46575,6 +47913,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -46820,7 +48161,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,6 +48211,9 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024 /* ContainsGenerator */) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -47011,7 +48355,7 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -47050,7 +48394,7 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, node.parameters, @@ -47099,6 +48443,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +48457,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47132,6 +48478,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47156,7 +48503,7 @@ var ts; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 8388608 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -48202,9 +49549,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,11 +49568,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -48815,7 +50162,7 @@ var ts; return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), /*typeArguments*/ undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( + ts.setEmitFlags(ts.createFunctionExpression( /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(state)], @@ -49218,8 +50565,32 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -49247,6 +50618,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -49418,7 +50792,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180 /* ArrowFunction */) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + if (!(ts.getEmitFlags(currentNode) & 2097152 /* AsyncFunctionBody */)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -49634,17 +51008,17 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); + if (ts.getEmitFlags(node) & 524288 /* Indented */) { + ts.setEmitFlags(classFunction, 524288 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); + ts.setEmitFlags(inner, 49152 /* NoComments */); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); return ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] @@ -49669,14 +51043,14 @@ var ts; // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); return block; } /** @@ -49702,13 +51076,17 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( + var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, getDeclarationName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256 /* CapturesThis */); + } + statements.push(constructorFunction); } /** * Transforms the parameters of the constructor declaration of a class. @@ -49740,51 +51118,146 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 1; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); }); ts.addRange(statements, body); } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), /*location*/ constructor ? constructor.body : node, /*multiLine*/ true); if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 211 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 203 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; } /** - * Adds a synthesized call to `_super` if it is needed. + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. + * @returns The new statement offset into the `statements` array. */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement. + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } /** * Visits a parameter declaration. @@ -49837,17 +51310,17 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } @@ -49865,11 +51338,11 @@ var ts; // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); } } /** @@ -49882,14 +51355,14 @@ var ts; */ function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), ts.setEmitFlags(initializer, 1536 /* NoSourceMap */ | ts.getEmitFlags(initializer)), /*location*/ parameter)) ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), /*elseStatement*/ undefined, /*location*/ parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); statements.push(statement); } /** @@ -49919,13 +51392,13 @@ var ts; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + ts.setEmitFlags(declarationName, 1536 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -49941,7 +51414,7 @@ var ts; ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), /*location*/ parameter)) ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 8388608 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -49953,17 +51426,20 @@ var ts; */ function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } /** * Adds statements to the class body function for a class to define the members of the * class. @@ -50012,20 +51488,20 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152 /* NoComments */); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name), func), /*location*/ member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); + ts.setCommentRange(statement, commentRange); // The location for the statement is used to emit comments only. // No source map should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + ts.setEmitFlags(statement, 1536 /* NoSourceMap */); return statement; } /** @@ -50036,11 +51512,11 @@ var ts; */ function transformAccessorsToStatement(receiver, accessors) { var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); return statement; } /** @@ -50054,24 +51530,24 @@ var ts; // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -50096,7 +51572,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); + ts.setEmitFlags(func, 256 /* CapturesThis */); return func; } /** @@ -50191,7 +51667,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + ts.setEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom // source map location for the close brace. @@ -50205,10 +51681,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); + ts.setEmitFlags(block, 32 /* SingleLine */); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -50274,7 +51750,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -50303,7 +51779,7 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { @@ -50311,7 +51787,7 @@ var ts; // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -50501,7 +51977,7 @@ var ts; // emitter. var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -50549,12 +52025,12 @@ var ts; } } // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 /* NoSourceMap */ | ts.getEmitFlags(expression)); // The old emitter does not emit source maps for the block. // We add the location to preserve comments. var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) @@ -50562,7 +52038,7 @@ var ts; /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, /*location*/ node); // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + ts.setEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); return forStatement; } /** @@ -50591,7 +52067,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), /*location*/ undefined, node.multiLine), 524288 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; @@ -50698,7 +52174,7 @@ var ts; loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152 /* AsyncFunctionBody */) !== 0 && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -50710,7 +52186,7 @@ var ts; var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) @@ -50756,8 +52232,8 @@ var ts; extraVariableDeclarations = []; } // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -50767,8 +52243,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -51003,7 +52479,7 @@ var ts; // Methods with computed property names are handled in visitObjectLiteralExpression. ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, /*location*/ node); } @@ -51040,9 +52516,19 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 128 /* NoSubstitution */); + } + var resultingCall; if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { // [source] // f(...a, b) @@ -51057,7 +52543,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -51069,9 +52555,18 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } + if (node.expression.kind === 95 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } /** * Visits a NewExpression that contains a spread element. @@ -51313,13 +52808,13 @@ var ts; * * @param node The node to be printed. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } /** @@ -51356,9 +52851,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -51434,7 +52929,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + && ts.getEmitFlags(enclosingFunction) & 256 /* CapturesThis */) { return ts.createIdentifier("_this", /*location*/ node); } return node; @@ -51461,7 +52956,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -51469,7 +52964,7 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -51552,13 +53047,6 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,16 +53056,9 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -51588,56 +53069,27 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +53112,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 128 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +53146,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51891,95 +53236,12 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +53250,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,24 +53264,15 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; @@ -52034,12 +53285,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +53346,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +53356,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +53403,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +53432,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 512 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 1024 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +53511,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,6 +53537,9 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -52349,6 +53555,9 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +53568,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52457,21 +53627,23 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -52505,10 +53677,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,7 +53707,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { @@ -52542,8 +53716,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52664,16 +53840,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +53901,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52786,7 +53952,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52987,7 +54153,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,7 +54166,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53202,7 +54368,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53624,7 +54790,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -54265,7 +55431,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +55440,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54294,8 +55460,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,8 +55501,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); // emit output for the __extends helper function @@ -54352,7 +55520,7 @@ var ts; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; // The __generator helper is used by down-level transformations to emulate the runtime // semantics of an ES2015 generator function. When called, this helper returns an // object that implements the Iterator protocol, in that it has `next`, `return`, and @@ -54426,11 +55594,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54447,18 +55615,20 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +55638,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54494,8 +55668,8 @@ var ts; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -54536,135 +55710,124 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals @@ -54696,7 +55859,8 @@ var ts; case 132 /* StringKeyword */: case 133 /* SymbolKeyword */: case 137 /* GlobalKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Parse tree nodes // Names case 139 /* QualifiedName */: @@ -54886,18 +56050,20 @@ var ts; // Enum case 255 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals @@ -54916,7 +56082,8 @@ var ts; case 95 /* SuperKeyword */: case 99 /* TrueKeyword */: case 97 /* ThisKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Expressions case 170 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); @@ -55010,7 +56177,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { + if (ts.getEmitFlags(node) & 16 /* UMDDefine */) { writeLines(umdHelper); } else { @@ -55243,7 +56410,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +56423,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 1048576 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55284,17 +56448,16 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55467,7 +56630,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 32 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55645,11 +56808,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 4194304 /* ReuseTempVariableScope */) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -55687,7 +56850,7 @@ var ts; // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 32 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55743,7 +56906,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55805,7 +56968,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -56023,8 +57186,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56084,7 +57247,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1 /* EmitEmitHelpers */) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -56197,31 +57360,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +57467,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +57513,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56539,17 +57662,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56878,695 +57996,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @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(candidate, extensions, failedLookupLocation, 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" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // 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 (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.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 - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +58101,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57740,45 +58169,6 @@ var ts; } return resolutions; } - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57815,7 +58205,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +58213,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,8 +58223,8 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); @@ -57884,7 +58274,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57938,6 +58329,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -58054,16 +58446,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +58490,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58659,7 +59054,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; // add file to program only if: // - resolution was successful // - noResolve is falsy @@ -58676,7 +59070,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { @@ -58692,8 +59086,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +59098,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +59142,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +59153,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,6 +59193,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58891,12 +59288,15 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -59327,6 +59727,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ @@ -59547,10 +59952,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59712,13 +60118,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) @@ -59799,6 +60207,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -59812,7 +60231,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -60742,7 +61163,7 @@ var ts; return true; case 69 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142 /* Parameter */; default: return false; } @@ -61420,7 +61841,6 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; @@ -61657,7 +62077,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -61671,14 +62091,17 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -62538,8 +62961,7 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62583,14 +63005,14 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -62619,7 +63041,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); @@ -62690,7 +63112,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 253 /* PropertyAssignment */ && + node.parent.parent.kind === 171 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62740,7 +63164,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -62756,7 +63180,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +63190,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +63201,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62819,6 +63243,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +63279,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +63304,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +63479,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +63499,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63285,7 +63732,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63349,6 +63796,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63382,11 +63830,13 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { @@ -63448,6 +63898,7 @@ var ts; if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -64026,9 +64477,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,6 +66901,7 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -66458,10 +66918,13 @@ var ts; return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -66552,13 +67015,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +67033,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -66616,7 +67076,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -66624,6 +67084,9 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); for (var name_49 in nameToDeclarations) { var declarations = nameToDeclarations[name_49]; @@ -66803,6 +67266,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -67077,7 +67547,7 @@ var ts; } } // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { @@ -67242,6 +67712,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +67744,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -71005,25 +71484,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +71512,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +71524,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +71534,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +71542,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +71550,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +71564,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71222,7 +71701,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 225 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); + return body && body.kind === 226 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 256 /* SourceFile */: case 199 /* Block */: case 226 /* ModuleBlock */: @@ -71332,7 +71811,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +71883,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +71891,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71493,13 +71972,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71919,7 +72398,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71980,14 +72459,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +72481,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +72524,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +72540,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72095,7 +72574,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +72585,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +72597,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +72640,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72371,7 +72850,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72473,6 +72952,117 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 174 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -72498,13 +73088,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(69 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72732,15 +73324,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -72816,7 +73409,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72985,6 +73578,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +73617,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73185,7 +73806,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +73846,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73553,12 +74181,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +74197,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73647,14 +74275,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73715,34 +74357,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73926,6 +74594,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +74604,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -74624,7 +75294,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74712,6 +75382,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74914,11 +75590,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +75833,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +75863,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +75890,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index b1248c700fa..577a8ee4fc9 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -790,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1537,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1550,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1570,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1624,6 +1649,60 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; function positionIsSynthesized(pos) { return !(pos >= 0); } @@ -1821,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1947,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -2090,6 +2178,11 @@ var ts; } return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2414,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2575,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2809,6 +2902,7 @@ var ts; Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2833,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2862,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3772,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4844,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -5294,7 +5401,7 @@ var ts; ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true } + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; @@ -5704,7 +5811,7 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); } ts.getEffectiveTypeRoots = getEffectiveTypeRoots; function getDefaultTypeRoots(currentDirectory, host) { @@ -5958,11 +6065,11 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -5988,57 +6095,6 @@ var ts; return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); var supportedExtensions = ts.getSupportedExtensions(compilerOptions); @@ -6169,20 +6225,28 @@ var ts; } } function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; } } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } } var parentPath = ts.getDirectoryPath(directory); if (parentPath === directory || checkOneLevel) { @@ -6192,7 +6256,6 @@ var ts; } return undefined; } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; function classicNameResolver(moduleName, containingFile, compilerOptions, host) { var traceEnabled = isTraceEnabled(compilerOptions, host); var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; @@ -6205,18 +6268,8 @@ var ts; } var referencedSourceFile; if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); @@ -6227,6 +6280,20 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -6242,6 +6309,36 @@ var ts; var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost); return result.resolvedModule && result.resolvedModule.resolvedFileName; } + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 2] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters"; + })(typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {})); + var PackageNameValidationResult = typingsInstaller.PackageNameValidationResult; + typingsInstaller.MaxPackageNameLength = 214; + function validatePackageName(packageName) { + ts.Debug.assert(!!packageName, "Package name is not specified"); + if (packageName.length > typingsInstaller.MaxPackageNameLength) { + return PackageNameValidationResult.NameTooLong; + } + if (packageName.charCodeAt(0) === 46) { + return PackageNameValidationResult.NameStartsWithDot; + } + if (packageName.charCodeAt(0) === 95) { + return PackageNameValidationResult.NameStartsWithUnderscore; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return PackageNameValidationResult.ScopedPackagesNotSupported; + } + if (encodeURIComponent(packageName) !== packageName) { + return PackageNameValidationResult.NameContainsNonURISafeCharacters; + } + return PackageNameValidationResult.Ok; + } + typingsInstaller.validatePackageName = validatePackageName; typingsInstaller.NpmViewRequest = "npm view"; typingsInstaller.NpmInstallRequest = "npm install"; var TypingsInstaller = (function () { @@ -6364,15 +6461,54 @@ var ts; } this.knownCachesSet[cacheLocation] = true; }; + TypingsInstaller.prototype.filterTypings = function (typingsToInstall) { + if (typingsToInstall.length === 0) { + return typingsToInstall; + } + var result = []; + for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) { + var typing = typingsToInstall_1[_i]; + if (this.missingTypingsSet[typing]) { + continue; + } + var validationResult = validatePackageName(typing); + if (validationResult === PackageNameValidationResult.Ok) { + result.push(typing); + } + else { + this.missingTypingsSet[typing] = true; + if (this.log.isEnabled()) { + switch (validationResult) { + case PackageNameValidationResult.NameTooLong: + this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters"); + break; + case PackageNameValidationResult.NameStartsWithDot: + this.log.writeLine("Package name '" + typing + "' cannot start with '.'"); + break; + case PackageNameValidationResult.NameStartsWithUnderscore: + this.log.writeLine("Package name '" + typing + "' cannot start with '_'"); + break; + case PackageNameValidationResult.ScopedPackagesNotSupported: + this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported"); + break; + case PackageNameValidationResult.NameContainsNonURISafeCharacters: + this.log.writeLine("Package name '" + typing + "' contains non URI safe characters"); + break; + } + } + } + } + return result; + }; TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { var _this = this; if (this.log.isEnabled()) { this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall)); } - typingsToInstall = ts.filter(typingsToInstall, function (x) { return !_this.missingTypingsSet[x]; }); + typingsToInstall = this.filterTypings(typingsToInstall); if (typingsToInstall.length === 0) { if (this.log.isEnabled()) { - this.log.writeLine("All typings are known to be missing - no need to go any further"); + this.log.writeLine("All typings are known to be missing or invalid - no need to go any further"); } return; } @@ -6412,8 +6548,8 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles)); } - for (var _a = 0, typingsToInstall_1 = typingsToInstall; _a < typingsToInstall_1.length; _a++) { - var toInstall = typingsToInstall_1[_a]; + for (var _a = 0, typingsToInstall_2 = typingsToInstall; _a < typingsToInstall_2.length; _a++) { + var toInstall = typingsToInstall_2[_a]; if (!installedPackages[toInstall]) { if (_this.log.isEnabled()) { _this.log.writeLine("New missing typing package '" + toInstall + "'"); @@ -6429,8 +6565,8 @@ var ts; this.installRunCount++; var execInstallCmdCount = 0; var filteredTypings = []; - for (var _i = 0, typingsToInstall_2 = typingsToInstall; _i < typingsToInstall_2.length; _i++) { - var typing = typingsToInstall_2[_i]; + for (var _i = 0, typingsToInstall_3 = typingsToInstall; _i < typingsToInstall_3.length; _i++) { + var typing = typingsToInstall_3[_i]; execNpmViewTyping(this, typing); } function execNpmViewTyping(self, typing) { @@ -6553,13 +6689,14 @@ var ts; var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) { - _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log); - this.installTypingHost = ts.sys; - if (this.log.isEnabled()) { - this.log.writeLine("Process id: " + process.pid); + var _this = _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + _this.installTypingHost = ts.sys; + if (_this.log.isEnabled()) { + _this.log.writeLine("Process id: " + process.pid); } var exec = require("child_process").exec; - this.exec = exec; + _this.exec = exec; + return _this; } NodeTypingsInstaller.prototype.init = function () { var _this = this; From 2cd404038eb0ca962350674fbdbbbe1bcf07810d Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 17:11:03 -0700 Subject: [PATCH 65/74] Port fix in https://github.com/Microsoft/TypeScript/pull/11293 to correct file --- src/lib/es5.d.ts | 3 +++ tests/cases/fourslash/functionTypes.ts | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index ccff01a8722..2c457a432c6 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -244,6 +244,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of a function. */ + toString(): string; + prototype: any; readonly length: number; diff --git a/tests/cases/fourslash/functionTypes.ts b/tests/cases/fourslash/functionTypes.ts index 8973f73431b..0baccba286e 100644 --- a/tests/cases/fourslash/functionTypes.ts +++ b/tests/cases/fourslash/functionTypes.ts @@ -23,7 +23,7 @@ verify.numberOfErrorsInCurrentFile(0); for (var i = 1; i <= 7; i++) { goTo.marker('' + i); - verify.memberListCount(7); + verify.memberListCount(8); verify.completionListContains('apply'); verify.completionListContains('arguments'); verify.completionListContains('bind'); @@ -31,4 +31,5 @@ for (var i = 1; i <= 7; i++) { verify.completionListContains('length'); verify.completionListContains('caller'); verify.completionListContains('prototype'); + verify.completionListContains('toString'); } From cdafc9dca1df725e6684a84433d147710870e2bd Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 17:29:03 -0700 Subject: [PATCH 66/74] Update LKG --- lib/lib.d.ts | 3 +++ lib/lib.es5.d.ts | 3 +++ lib/lib.es6.d.ts | 3 +++ lib/tsc.js | 2 -- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 87280fedba4..922820b5d90 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -260,6 +260,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of a function. */ + toString(): string; + prototype: any; readonly length: number; diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index d20c7d1e3a7..a13ffc92d04 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -260,6 +260,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of a function. */ + toString(): string; + prototype: any; readonly length: number; diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 6067d810b44..4c8806dd7dd 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -260,6 +260,9 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; + /** Returns a string representation of a function. */ + toString(): string; + prototype: any; readonly length: number; diff --git a/lib/tsc.js b/lib/tsc.js index 7f46b1dddb4..b1fac7955d0 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -67,7 +67,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -7937,7 +7936,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; From 86784a5eef6c9d4e5fbb68e5c7a1eedfc23ed8a8 Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Fri, 14 Oct 2016 10:54:54 +0200 Subject: [PATCH 67/74] Get rid of ES6 completely --- src/compiler/commandLineParser.ts | 4 ++-- src/compiler/types.ts | 6 ++---- tests/baselines/reference/APISample_linter.js | 4 ++-- tests/cases/compiler/APISample_linter.ts | 2 +- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 553efa9e3af..545c7f3e708 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -101,7 +101,7 @@ namespace ts { "amd": ModuleKind.AMD, "system": ModuleKind.System, "umd": ModuleKind.UMD, - "es6": ModuleKind.ES6, + "es6": ModuleKind.ES2015, "es2015": ModuleKind.ES2015, }), description: Diagnostics.Specify_module_code_generation_Colon_commonjs_amd_system_umd_or_es2015, @@ -261,7 +261,7 @@ namespace ts { type: createMap({ "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, - "es6": ScriptTarget.ES6, + "es6": ScriptTarget.ES2015, "es2015": ScriptTarget.ES2015, "es2016": ScriptTarget.ES2016, "es2017": ScriptTarget.ES2017, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index ae9502c21d2..68bda608238 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3019,8 +3019,7 @@ namespace ts { AMD = 2, UMD = 3, System = 4, - ES6 = 5, - ES2015 = ES6, + ES2015 = 5, } export const enum JsxEmit { @@ -3053,8 +3052,7 @@ namespace ts { export const enum ScriptTarget { ES3 = 0, ES5 = 1, - ES6 = 2, - ES2015 = ES6, + ES2015 = 2, ES2016 = 3, ES2017 = 4, Latest = ES2017, diff --git a/tests/baselines/reference/APISample_linter.js b/tests/baselines/reference/APISample_linter.js index 4e563c7cac3..1421b53a00c 100644 --- a/tests/baselines/reference/APISample_linter.js +++ b/tests/baselines/reference/APISample_linter.js @@ -58,7 +58,7 @@ export function delint(sourceFile: ts.SourceFile) { const fileNames: string[] = process.argv.slice(2); fileNames.forEach(fileName => { // Parse a file - let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); @@ -113,7 +113,7 @@ exports.delint = delint; var fileNames = process.argv.slice(2); fileNames.forEach(function (fileName) { // Parse a file - var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + var sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); }); diff --git a/tests/cases/compiler/APISample_linter.ts b/tests/cases/compiler/APISample_linter.ts index 89f0be7a0f5..dc5e2644b4f 100644 --- a/tests/cases/compiler/APISample_linter.ts +++ b/tests/cases/compiler/APISample_linter.ts @@ -61,7 +61,7 @@ export function delint(sourceFile: ts.SourceFile) { const fileNames: string[] = process.argv.slice(2); fileNames.forEach(fileName => { // Parse a file - let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, /*setParentNodes */ true); + let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES2015, /*setParentNodes */ true); // delint it delint(sourceFile); From 6417dab60bfb5f3775d82487979d940376b5d24a Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Fri, 14 Oct 2016 08:11:23 -0700 Subject: [PATCH 68/74] Merge pull request #11605 from Microsoft/vladima/convert-enums-to-const convert all enums to const enums when building protocol.d.ts --- .gitignore | 1 + scripts/buildProtocol.ts | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 5e4bc0af5ea..f1ea04e3efb 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ tests/cases/**/*.js.map scripts/debug.bat scripts/run.bat scripts/word2md.js +scripts/buildProtocol.js scripts/ior.js scripts/buildProtocol.js scripts/*.js.map diff --git a/scripts/buildProtocol.ts b/scripts/buildProtocol.ts index 8d49262a470..55ad086815c 100644 --- a/scripts/buildProtocol.ts +++ b/scripts/buildProtocol.ts @@ -42,7 +42,14 @@ class DeclarationsWalker { return; } // splice declaration in final d.ts file - const text = decl.getFullText(); + let text = decl.getFullText(); + if (decl.kind === ts.SyntaxKind.EnumDeclaration && !(decl.flags & ts.NodeFlags.Const)) { + // patch enum declaration to make them constan + const declStart = decl.getStart() - decl.getFullStart(); + const prefix = text.substring(0, declStart); + const suffix = text.substring(declStart + "enum".length, decl.getEnd() - decl.getFullStart()); + text = prefix + "const enum" + suffix; + } this.text += `${text}\n`; // recursively pull all dependencies into result dts file From 7352e971215a07026c8f7ab7786ed2c9a900e70b Mon Sep 17 00:00:00 2001 From: Andrej Baran Date: Sat, 15 Oct 2016 01:16:11 +0200 Subject: [PATCH 69/74] Cleanup ES2017 async tests --- .../reference/asyncAliasReturnType_es2017.js | 9 --- .../asyncAliasReturnType_es2017.symbols | 11 ---- .../asyncAliasReturnType_es2017.types | 11 ---- .../reference/asyncClass_es2017.errors.txt | 8 --- .../baselines/reference/asyncClass_es2017.js | 7 -- .../asyncConstructor_es2017.errors.txt | 10 --- .../reference/asyncConstructor_es2017.js | 11 ---- .../reference/asyncDeclare_es2017.errors.txt | 7 -- .../reference/asyncDeclare_es2017.js | 4 -- .../reference/asyncEnum_es2017.errors.txt | 9 --- tests/baselines/reference/asyncEnum_es2017.js | 10 --- ...yncFunctionDeclaration15_es2017.errors.txt | 48 -------------- .../asyncFunctionDeclaration15_es2017.js | 64 ------------------- .../reference/asyncGetter_es2017.errors.txt | 13 ---- .../baselines/reference/asyncGetter_es2017.js | 11 ---- .../asyncImportedPromise_es2017.errors.txt | 13 ---- .../reference/asyncImportedPromise_es2017.js | 21 ------ .../asyncInterface_es2017.errors.txt | 8 --- .../reference/asyncInterface_es2017.js | 5 -- .../reference/asyncModule_es2017.errors.txt | 8 --- .../baselines/reference/asyncModule_es2017.js | 5 -- .../reference/asyncMultiFile_es2017.js | 11 ---- .../reference/asyncMultiFile_es2017.symbols | 8 --- .../reference/asyncMultiFile_es2017.types | 8 --- ...asyncQualifiedReturnType_es2017.errors.txt | 13 ---- .../asyncQualifiedReturnType_es2017.js | 18 ------ .../reference/asyncSetter_es2017.errors.txt | 10 --- .../baselines/reference/asyncSetter_es2017.js | 11 ---- .../baselines/reference/awaitUnion_es2017.js | 22 ------- .../reference/awaitUnion_es2017.symbols | 44 ------------- .../reference/awaitUnion_es2017.types | 49 -------------- tests/baselines/reference/es2017basicAsync.js | 4 +- .../reference/es2017basicAsync.symbols | 4 +- .../reference/es2017basicAsync.types | 4 +- tests/cases/compiler/es2017basicAsync.ts | 2 +- .../es2017/asyncAliasReturnType_es2017.ts | 6 -- .../async/es2017/asyncClass_es2017.ts | 4 -- .../async/es2017/asyncConstructor_es2017.ts | 6 -- .../async/es2017/asyncDeclare_es2017.ts | 3 - .../async/es2017/asyncEnum_es2017.ts | 5 -- .../async/es2017/asyncGetter_es2017.ts | 6 -- .../es2017/asyncImportedPromise_es2017.ts | 10 --- .../async/es2017/asyncInterface_es2017.ts | 4 -- .../async/es2017/asyncModule_es2017.ts | 4 -- .../async/es2017/asyncMultiFile_es2017.ts | 5 -- .../es2017/asyncQualifiedReturnType_es2017.ts | 9 --- .../async/es2017/asyncSetter_es2017.ts | 6 -- .../async/es2017/awaitUnion_es2017.ts | 14 ---- .../asyncFunctionDeclaration15_es2017.ts | 25 -------- 49 files changed, 7 insertions(+), 601 deletions(-) delete mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.js delete mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.symbols delete mode 100644 tests/baselines/reference/asyncAliasReturnType_es2017.types delete mode 100644 tests/baselines/reference/asyncClass_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncClass_es2017.js delete mode 100644 tests/baselines/reference/asyncConstructor_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncConstructor_es2017.js delete mode 100644 tests/baselines/reference/asyncDeclare_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncDeclare_es2017.js delete mode 100644 tests/baselines/reference/asyncEnum_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncEnum_es2017.js delete mode 100644 tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncFunctionDeclaration15_es2017.js delete mode 100644 tests/baselines/reference/asyncGetter_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncGetter_es2017.js delete mode 100644 tests/baselines/reference/asyncImportedPromise_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncImportedPromise_es2017.js delete mode 100644 tests/baselines/reference/asyncInterface_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncInterface_es2017.js delete mode 100644 tests/baselines/reference/asyncModule_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncModule_es2017.js delete mode 100644 tests/baselines/reference/asyncMultiFile_es2017.js delete mode 100644 tests/baselines/reference/asyncMultiFile_es2017.symbols delete mode 100644 tests/baselines/reference/asyncMultiFile_es2017.types delete mode 100644 tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncQualifiedReturnType_es2017.js delete mode 100644 tests/baselines/reference/asyncSetter_es2017.errors.txt delete mode 100644 tests/baselines/reference/asyncSetter_es2017.js delete mode 100644 tests/baselines/reference/awaitUnion_es2017.js delete mode 100644 tests/baselines/reference/awaitUnion_es2017.symbols delete mode 100644 tests/baselines/reference/awaitUnion_es2017.types delete mode 100644 tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncClass_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncEnum_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncGetter_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncInterface_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncModule_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/asyncSetter_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/awaitUnion_es2017.ts delete mode 100644 tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.js b/tests/baselines/reference/asyncAliasReturnType_es2017.js deleted file mode 100644 index f76f2b13b45..00000000000 --- a/tests/baselines/reference/asyncAliasReturnType_es2017.js +++ /dev/null @@ -1,9 +0,0 @@ -//// [asyncAliasReturnType_es2017.ts] -type PromiseAlias = Promise; - -async function f(): PromiseAlias { -} - -//// [asyncAliasReturnType_es2017.js] -async function f() { -} diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.symbols b/tests/baselines/reference/asyncAliasReturnType_es2017.symbols deleted file mode 100644 index cc4fc5b8096..00000000000 --- a/tests/baselines/reference/asyncAliasReturnType_es2017.symbols +++ /dev/null @@ -1,11 +0,0 @@ -=== tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts === -type PromiseAlias = Promise; ->PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es2017.ts, 0, 0)) ->T : Symbol(T, Decl(asyncAliasReturnType_es2017.ts, 0, 18)) ->Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) ->T : Symbol(T, Decl(asyncAliasReturnType_es2017.ts, 0, 18)) - -async function f(): PromiseAlias { ->f : Symbol(f, Decl(asyncAliasReturnType_es2017.ts, 0, 34)) ->PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es2017.ts, 0, 0)) -} diff --git a/tests/baselines/reference/asyncAliasReturnType_es2017.types b/tests/baselines/reference/asyncAliasReturnType_es2017.types deleted file mode 100644 index 67c521b77fa..00000000000 --- a/tests/baselines/reference/asyncAliasReturnType_es2017.types +++ /dev/null @@ -1,11 +0,0 @@ -=== tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts === -type PromiseAlias = Promise; ->PromiseAlias : Promise ->T : T ->Promise : Promise ->T : T - -async function f(): PromiseAlias { ->f : () => Promise ->PromiseAlias : Promise -} diff --git a/tests/baselines/reference/asyncClass_es2017.errors.txt b/tests/baselines/reference/asyncClass_es2017.errors.txt deleted file mode 100644 index 37612b0b0f2..00000000000 --- a/tests/baselines/reference/asyncClass_es2017.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/conformance/async/es2017/asyncClass_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. - - -==== tests/cases/conformance/async/es2017/asyncClass_es2017.ts (1 errors) ==== - async class C { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncClass_es2017.js b/tests/baselines/reference/asyncClass_es2017.js deleted file mode 100644 index e619bd50b97..00000000000 --- a/tests/baselines/reference/asyncClass_es2017.js +++ /dev/null @@ -1,7 +0,0 @@ -//// [asyncClass_es2017.ts] -async class C { -} - -//// [asyncClass_es2017.js] -async class C { -} diff --git a/tests/baselines/reference/asyncConstructor_es2017.errors.txt b/tests/baselines/reference/asyncConstructor_es2017.errors.txt deleted file mode 100644 index 3b0c1b42fa9..00000000000 --- a/tests/baselines/reference/asyncConstructor_es2017.errors.txt +++ /dev/null @@ -1,10 +0,0 @@ -tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts(2,3): error TS1089: 'async' modifier cannot appear on a constructor declaration. - - -==== tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts (1 errors) ==== - class C { - async constructor() { - ~~~~~ -!!! error TS1089: 'async' modifier cannot appear on a constructor declaration. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncConstructor_es2017.js b/tests/baselines/reference/asyncConstructor_es2017.js deleted file mode 100644 index 7dcd6ec6943..00000000000 --- a/tests/baselines/reference/asyncConstructor_es2017.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [asyncConstructor_es2017.ts] -class C { - async constructor() { - } -} - -//// [asyncConstructor_es2017.js] -class C { - async constructor() { - } -} diff --git a/tests/baselines/reference/asyncDeclare_es2017.errors.txt b/tests/baselines/reference/asyncDeclare_es2017.errors.txt deleted file mode 100644 index bb74a3865d5..00000000000 --- a/tests/baselines/reference/asyncDeclare_es2017.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts(1,9): error TS1040: 'async' modifier cannot be used in an ambient context. - - -==== tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts (1 errors) ==== - declare async function foo(): Promise; - ~~~~~ -!!! error TS1040: 'async' modifier cannot be used in an ambient context. \ No newline at end of file diff --git a/tests/baselines/reference/asyncDeclare_es2017.js b/tests/baselines/reference/asyncDeclare_es2017.js deleted file mode 100644 index 2ff588b2851..00000000000 --- a/tests/baselines/reference/asyncDeclare_es2017.js +++ /dev/null @@ -1,4 +0,0 @@ -//// [asyncDeclare_es2017.ts] -declare async function foo(): Promise; - -//// [asyncDeclare_es2017.js] diff --git a/tests/baselines/reference/asyncEnum_es2017.errors.txt b/tests/baselines/reference/asyncEnum_es2017.errors.txt deleted file mode 100644 index 8e0015d0b24..00000000000 --- a/tests/baselines/reference/asyncEnum_es2017.errors.txt +++ /dev/null @@ -1,9 +0,0 @@ -tests/cases/conformance/async/es2017/asyncEnum_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. - - -==== tests/cases/conformance/async/es2017/asyncEnum_es2017.ts (1 errors) ==== - async enum E { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - Value - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncEnum_es2017.js b/tests/baselines/reference/asyncEnum_es2017.js deleted file mode 100644 index df1f846c2f9..00000000000 --- a/tests/baselines/reference/asyncEnum_es2017.js +++ /dev/null @@ -1,10 +0,0 @@ -//// [asyncEnum_es2017.ts] -async enum E { - Value -} - -//// [asyncEnum_es2017.js] -var E; -(function (E) { - E[E["Value"] = 0] = "Value"; -})(E || (E = {})); diff --git a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt deleted file mode 100644 index efc1e2440bf..00000000000 --- a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.errors.txt +++ /dev/null @@ -1,48 +0,0 @@ -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(6,23): error TS1064: The return type of an async function or method must be the global Promise type. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(7,23): error TS1064: The return type of an async function or method must be the global Promise type. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(8,23): error TS1064: The return type of an async function or method must be the global Promise type. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(9,23): error TS1064: The return type of an async function or method must be the global Promise type. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(10,23): error TS1064: The return type of an async function or method must be the global Promise type. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(17,16): error TS1059: Return expression in async function does not have a valid callable 'then' member. -tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts(23,25): error TS1058: Operand for 'await' does not have a valid callable 'then' member. - - -==== tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts (7 errors) ==== - declare class Thenable { then(): void; } - declare let a: any; - declare let obj: { then: string; }; - declare let thenable: Thenable; - async function fn1() { } // valid: Promise - async function fn2(): { } { } // error - ~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - async function fn3(): any { } // error - ~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - async function fn4(): number { } // error - ~~~~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - async function fn5(): PromiseLike { } // error - ~~~~~~~~~~~~~~~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - async function fn6(): Thenable { } // error - ~~~~~~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - async function fn7() { return; } // valid: Promise - async function fn8() { return 1; } // valid: Promise - async function fn9() { return null; } // valid: Promise - async function fn10() { return undefined; } // valid: Promise - async function fn11() { return a; } // valid: Promise - async function fn12() { return obj; } // valid: Promise<{ then: string; }> - async function fn13() { return thenable; } // error - ~~~~ -!!! error TS1059: Return expression in async function does not have a valid callable 'then' member. - async function fn14() { await 1; } // valid: Promise - async function fn15() { await null; } // valid: Promise - async function fn16() { await undefined; } // valid: Promise - async function fn17() { await a; } // valid: Promise - async function fn18() { await obj; } // valid: Promise - async function fn19() { await thenable; } // error - ~~~~~~~~~~~~~~ -!!! error TS1058: Operand for 'await' does not have a valid callable 'then' member. - \ No newline at end of file diff --git a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js b/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js deleted file mode 100644 index 5704366025e..00000000000 --- a/tests/baselines/reference/asyncFunctionDeclaration15_es2017.js +++ /dev/null @@ -1,64 +0,0 @@ -//// [asyncFunctionDeclaration15_es2017.ts] -declare class Thenable { then(): void; } -declare let a: any; -declare let obj: { then: string; }; -declare let thenable: Thenable; -async function fn1() { } // valid: Promise -async function fn2(): { } { } // error -async function fn3(): any { } // error -async function fn4(): number { } // error -async function fn5(): PromiseLike { } // error -async function fn6(): Thenable { } // error -async function fn7() { return; } // valid: Promise -async function fn8() { return 1; } // valid: Promise -async function fn9() { return null; } // valid: Promise -async function fn10() { return undefined; } // valid: Promise -async function fn11() { return a; } // valid: Promise -async function fn12() { return obj; } // valid: Promise<{ then: string; }> -async function fn13() { return thenable; } // error -async function fn14() { await 1; } // valid: Promise -async function fn15() { await null; } // valid: Promise -async function fn16() { await undefined; } // valid: Promise -async function fn17() { await a; } // valid: Promise -async function fn18() { await obj; } // valid: Promise -async function fn19() { await thenable; } // error - - -//// [asyncFunctionDeclaration15_es2017.js] -async function fn1() { } // valid: Promise -// valid: Promise -async function fn2() { } // error -// error -async function fn3() { } // error -// error -async function fn4() { } // error -// error -async function fn5() { } // error -// error -async function fn6() { } // error -// error -async function fn7() { return; } // valid: Promise -// valid: Promise -async function fn8() { return 1; } // valid: Promise -// valid: Promise -async function fn9() { return null; } // valid: Promise -// valid: Promise -async function fn10() { return undefined; } // valid: Promise -// valid: Promise -async function fn11() { return a; } // valid: Promise -// valid: Promise -async function fn12() { return obj; } // valid: Promise<{ then: string; }> -// valid: Promise<{ then: string; }> -async function fn13() { return thenable; } // error -// error -async function fn14() { await 1; } // valid: Promise -// valid: Promise -async function fn15() { await null; } // valid: Promise -// valid: Promise -async function fn16() { await undefined; } // valid: Promise -// valid: Promise -async function fn17() { await a; } // valid: Promise -// valid: Promise -async function fn18() { await obj; } // valid: Promise -// valid: Promise -async function fn19() { await thenable; } // error diff --git a/tests/baselines/reference/asyncGetter_es2017.errors.txt b/tests/baselines/reference/asyncGetter_es2017.errors.txt deleted file mode 100644 index 386e95d5977..00000000000 --- a/tests/baselines/reference/asyncGetter_es2017.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/async/es2017/asyncGetter_es2017.ts(2,3): error TS1042: 'async' modifier cannot be used here. -tests/cases/conformance/async/es2017/asyncGetter_es2017.ts(2,13): error TS2378: A 'get' accessor must return a value. - - -==== tests/cases/conformance/async/es2017/asyncGetter_es2017.ts (2 errors) ==== - class C { - async get foo() { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - ~~~ -!!! error TS2378: A 'get' accessor must return a value. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncGetter_es2017.js b/tests/baselines/reference/asyncGetter_es2017.js deleted file mode 100644 index ad8fa347cb5..00000000000 --- a/tests/baselines/reference/asyncGetter_es2017.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [asyncGetter_es2017.ts] -class C { - async get foo() { - } -} - -//// [asyncGetter_es2017.js] -class C { - async get foo() { - } -} diff --git a/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt b/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt deleted file mode 100644 index a0348b2e691..00000000000 --- a/tests/baselines/reference/asyncImportedPromise_es2017.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/async/es2017/test.ts(3,25): error TS1064: The return type of an async function or method must be the global Promise type. - - -==== tests/cases/conformance/async/es2017/task.ts (0 errors) ==== - export class Task extends Promise { } - -==== tests/cases/conformance/async/es2017/test.ts (1 errors) ==== - import { Task } from "./task"; - class Test { - async example(): Task { return; } - ~~~~~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncImportedPromise_es2017.js b/tests/baselines/reference/asyncImportedPromise_es2017.js deleted file mode 100644 index a48c58c1707..00000000000 --- a/tests/baselines/reference/asyncImportedPromise_es2017.js +++ /dev/null @@ -1,21 +0,0 @@ -//// [tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts] //// - -//// [task.ts] -export class Task extends Promise { } - -//// [test.ts] -import { Task } from "./task"; -class Test { - async example(): Task { return; } -} - -//// [task.js] -"use strict"; -class Task extends Promise { -} -exports.Task = Task; -//// [test.js] -"use strict"; -class Test { - async example() { return; } -} diff --git a/tests/baselines/reference/asyncInterface_es2017.errors.txt b/tests/baselines/reference/asyncInterface_es2017.errors.txt deleted file mode 100644 index dfbc8789797..00000000000 --- a/tests/baselines/reference/asyncInterface_es2017.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/conformance/async/es2017/asyncInterface_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. - - -==== tests/cases/conformance/async/es2017/asyncInterface_es2017.ts (1 errors) ==== - async interface I { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncInterface_es2017.js b/tests/baselines/reference/asyncInterface_es2017.js deleted file mode 100644 index 4d897389538..00000000000 --- a/tests/baselines/reference/asyncInterface_es2017.js +++ /dev/null @@ -1,5 +0,0 @@ -//// [asyncInterface_es2017.ts] -async interface I { -} - -//// [asyncInterface_es2017.js] diff --git a/tests/baselines/reference/asyncModule_es2017.errors.txt b/tests/baselines/reference/asyncModule_es2017.errors.txt deleted file mode 100644 index 8b6a4c3dc66..00000000000 --- a/tests/baselines/reference/asyncModule_es2017.errors.txt +++ /dev/null @@ -1,8 +0,0 @@ -tests/cases/conformance/async/es2017/asyncModule_es2017.ts(1,1): error TS1042: 'async' modifier cannot be used here. - - -==== tests/cases/conformance/async/es2017/asyncModule_es2017.ts (1 errors) ==== - async module M { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncModule_es2017.js b/tests/baselines/reference/asyncModule_es2017.js deleted file mode 100644 index fe3e17d5e74..00000000000 --- a/tests/baselines/reference/asyncModule_es2017.js +++ /dev/null @@ -1,5 +0,0 @@ -//// [asyncModule_es2017.ts] -async module M { -} - -//// [asyncModule_es2017.js] diff --git a/tests/baselines/reference/asyncMultiFile_es2017.js b/tests/baselines/reference/asyncMultiFile_es2017.js deleted file mode 100644 index 804a58e4b4c..00000000000 --- a/tests/baselines/reference/asyncMultiFile_es2017.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts] //// - -//// [a.ts] -async function f() {} -//// [b.ts] -function g() { } - -//// [a.js] -async function f() { } -//// [b.js] -function g() { } diff --git a/tests/baselines/reference/asyncMultiFile_es2017.symbols b/tests/baselines/reference/asyncMultiFile_es2017.symbols deleted file mode 100644 index 9d8ff6dbe85..00000000000 --- a/tests/baselines/reference/asyncMultiFile_es2017.symbols +++ /dev/null @@ -1,8 +0,0 @@ -=== tests/cases/conformance/async/es2017/a.ts === -async function f() {} ->f : Symbol(f, Decl(a.ts, 0, 0)) - -=== tests/cases/conformance/async/es2017/b.ts === -function g() { } ->g : Symbol(g, Decl(b.ts, 0, 0)) - diff --git a/tests/baselines/reference/asyncMultiFile_es2017.types b/tests/baselines/reference/asyncMultiFile_es2017.types deleted file mode 100644 index e1f8da34c94..00000000000 --- a/tests/baselines/reference/asyncMultiFile_es2017.types +++ /dev/null @@ -1,8 +0,0 @@ -=== tests/cases/conformance/async/es2017/a.ts === -async function f() {} ->f : () => Promise - -=== tests/cases/conformance/async/es2017/b.ts === -function g() { } ->g : () => void - diff --git a/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt b/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt deleted file mode 100644 index b9027c36539..00000000000 --- a/tests/baselines/reference/asyncQualifiedReturnType_es2017.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts(6,21): error TS1064: The return type of an async function or method must be the global Promise type. - - -==== tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts (1 errors) ==== - namespace X { - export class MyPromise extends Promise { - } - } - - async function f(): X.MyPromise { - ~~~~~~~~~~~~~~~~~ -!!! error TS1064: The return type of an async function or method must be the global Promise type. - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncQualifiedReturnType_es2017.js b/tests/baselines/reference/asyncQualifiedReturnType_es2017.js deleted file mode 100644 index 164a4fef610..00000000000 --- a/tests/baselines/reference/asyncQualifiedReturnType_es2017.js +++ /dev/null @@ -1,18 +0,0 @@ -//// [asyncQualifiedReturnType_es2017.ts] -namespace X { - export class MyPromise extends Promise { - } -} - -async function f(): X.MyPromise { -} - -//// [asyncQualifiedReturnType_es2017.js] -var X; -(function (X) { - class MyPromise extends Promise { - } - X.MyPromise = MyPromise; -})(X || (X = {})); -async function f() { -} diff --git a/tests/baselines/reference/asyncSetter_es2017.errors.txt b/tests/baselines/reference/asyncSetter_es2017.errors.txt deleted file mode 100644 index 0acd8538f20..00000000000 --- a/tests/baselines/reference/asyncSetter_es2017.errors.txt +++ /dev/null @@ -1,10 +0,0 @@ -tests/cases/conformance/async/es2017/asyncSetter_es2017.ts(2,3): error TS1042: 'async' modifier cannot be used here. - - -==== tests/cases/conformance/async/es2017/asyncSetter_es2017.ts (1 errors) ==== - class C { - async set foo(value) { - ~~~~~ -!!! error TS1042: 'async' modifier cannot be used here. - } - } \ No newline at end of file diff --git a/tests/baselines/reference/asyncSetter_es2017.js b/tests/baselines/reference/asyncSetter_es2017.js deleted file mode 100644 index 8260c5232a2..00000000000 --- a/tests/baselines/reference/asyncSetter_es2017.js +++ /dev/null @@ -1,11 +0,0 @@ -//// [asyncSetter_es2017.ts] -class C { - async set foo(value) { - } -} - -//// [asyncSetter_es2017.js] -class C { - async set foo(value) { - } -} diff --git a/tests/baselines/reference/awaitUnion_es2017.js b/tests/baselines/reference/awaitUnion_es2017.js deleted file mode 100644 index 12f8b95a652..00000000000 --- a/tests/baselines/reference/awaitUnion_es2017.js +++ /dev/null @@ -1,22 +0,0 @@ -//// [awaitUnion_es2017.ts] -declare let a: number | string; -declare let b: PromiseLike | PromiseLike; -declare let c: PromiseLike; -declare let d: number | PromiseLike; -declare let e: number | PromiseLike; -async function f() { - let await_a = await a; - let await_b = await b; - let await_c = await c; - let await_d = await d; - let await_e = await e; -} - -//// [awaitUnion_es2017.js] -async function f() { - let await_a = await a; - let await_b = await b; - let await_c = await c; - let await_d = await d; - let await_e = await e; -} diff --git a/tests/baselines/reference/awaitUnion_es2017.symbols b/tests/baselines/reference/awaitUnion_es2017.symbols deleted file mode 100644 index e70abce4f0b..00000000000 --- a/tests/baselines/reference/awaitUnion_es2017.symbols +++ /dev/null @@ -1,44 +0,0 @@ -=== tests/cases/conformance/async/es2017/awaitUnion_es2017.ts === -declare let a: number | string; ->a : Symbol(a, Decl(awaitUnion_es2017.ts, 0, 11)) - -declare let b: PromiseLike | PromiseLike; ->b : Symbol(b, Decl(awaitUnion_es2017.ts, 1, 11)) ->PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) ->PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) - -declare let c: PromiseLike; ->c : Symbol(c, Decl(awaitUnion_es2017.ts, 2, 11)) ->PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) - -declare let d: number | PromiseLike; ->d : Symbol(d, Decl(awaitUnion_es2017.ts, 3, 11)) ->PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) - -declare let e: number | PromiseLike; ->e : Symbol(e, Decl(awaitUnion_es2017.ts, 4, 11)) ->PromiseLike : Symbol(PromiseLike, Decl(lib.es5.d.ts, --, --)) - -async function f() { ->f : Symbol(f, Decl(awaitUnion_es2017.ts, 4, 53)) - - let await_a = await a; ->await_a : Symbol(await_a, Decl(awaitUnion_es2017.ts, 6, 4)) ->a : Symbol(a, Decl(awaitUnion_es2017.ts, 0, 11)) - - let await_b = await b; ->await_b : Symbol(await_b, Decl(awaitUnion_es2017.ts, 7, 4)) ->b : Symbol(b, Decl(awaitUnion_es2017.ts, 1, 11)) - - let await_c = await c; ->await_c : Symbol(await_c, Decl(awaitUnion_es2017.ts, 8, 4)) ->c : Symbol(c, Decl(awaitUnion_es2017.ts, 2, 11)) - - let await_d = await d; ->await_d : Symbol(await_d, Decl(awaitUnion_es2017.ts, 9, 4)) ->d : Symbol(d, Decl(awaitUnion_es2017.ts, 3, 11)) - - let await_e = await e; ->await_e : Symbol(await_e, Decl(awaitUnion_es2017.ts, 10, 4)) ->e : Symbol(e, Decl(awaitUnion_es2017.ts, 4, 11)) -} diff --git a/tests/baselines/reference/awaitUnion_es2017.types b/tests/baselines/reference/awaitUnion_es2017.types deleted file mode 100644 index 58f8a4ec4b4..00000000000 --- a/tests/baselines/reference/awaitUnion_es2017.types +++ /dev/null @@ -1,49 +0,0 @@ -=== tests/cases/conformance/async/es2017/awaitUnion_es2017.ts === -declare let a: number | string; ->a : string | number - -declare let b: PromiseLike | PromiseLike; ->b : PromiseLike | PromiseLike ->PromiseLike : PromiseLike ->PromiseLike : PromiseLike - -declare let c: PromiseLike; ->c : PromiseLike ->PromiseLike : PromiseLike - -declare let d: number | PromiseLike; ->d : number | PromiseLike ->PromiseLike : PromiseLike - -declare let e: number | PromiseLike; ->e : number | PromiseLike ->PromiseLike : PromiseLike - -async function f() { ->f : () => Promise - - let await_a = await a; ->await_a : string | number ->await a : string | number ->a : string | number - - let await_b = await b; ->await_b : string | number ->await b : string | number ->b : PromiseLike | PromiseLike - - let await_c = await c; ->await_c : string | number ->await c : string | number ->c : PromiseLike - - let await_d = await d; ->await_d : string | number ->await d : string | number ->d : number | PromiseLike - - let await_e = await e; ->await_e : string | number ->await e : string | number ->e : number | PromiseLike -} diff --git a/tests/baselines/reference/es2017basicAsync.js b/tests/baselines/reference/es2017basicAsync.js index b19eaa4b0ba..d0443c1899c 100644 --- a/tests/baselines/reference/es2017basicAsync.js +++ b/tests/baselines/reference/es2017basicAsync.js @@ -8,7 +8,7 @@ async function asyncFunc() { await 0; } -const asycnArrowFunc = async (): Promise => { +const asyncArrowFunc = async (): Promise => { await 0; } @@ -54,7 +54,7 @@ async () => { async function asyncFunc() { await 0; } -const asycnArrowFunc = async () => { +const asyncArrowFunc = async () => { await 0; }; async function asyncIIFE() { diff --git a/tests/baselines/reference/es2017basicAsync.symbols b/tests/baselines/reference/es2017basicAsync.symbols index 75f4d2cfa76..d79faf1502a 100644 --- a/tests/baselines/reference/es2017basicAsync.symbols +++ b/tests/baselines/reference/es2017basicAsync.symbols @@ -12,8 +12,8 @@ async function asyncFunc() { await 0; } -const asycnArrowFunc = async (): Promise => { ->asycnArrowFunc : Symbol(asycnArrowFunc, Decl(es2017basicAsync.ts, 9, 5)) +const asyncArrowFunc = async (): Promise => { +>asyncArrowFunc : Symbol(asyncArrowFunc, Decl(es2017basicAsync.ts, 9, 5)) >Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --)) await 0; diff --git a/tests/baselines/reference/es2017basicAsync.types b/tests/baselines/reference/es2017basicAsync.types index 71c2dbe50f3..30d19cb4dfe 100644 --- a/tests/baselines/reference/es2017basicAsync.types +++ b/tests/baselines/reference/es2017basicAsync.types @@ -17,8 +17,8 @@ async function asyncFunc() { >0 : 0 } -const asycnArrowFunc = async (): Promise => { ->asycnArrowFunc : () => Promise +const asyncArrowFunc = async (): Promise => { +>asyncArrowFunc : () => Promise >async (): Promise => { await 0;} : () => Promise >Promise : Promise diff --git a/tests/cases/compiler/es2017basicAsync.ts b/tests/cases/compiler/es2017basicAsync.ts index b13a5d29bc0..b08ee6a18ae 100644 --- a/tests/cases/compiler/es2017basicAsync.ts +++ b/tests/cases/compiler/es2017basicAsync.ts @@ -10,7 +10,7 @@ async function asyncFunc() { await 0; } -const asycnArrowFunc = async (): Promise => { +const asyncArrowFunc = async (): Promise => { await 0; } diff --git a/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts b/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts deleted file mode 100644 index 87bbc42e166..00000000000 --- a/tests/cases/conformance/async/es2017/asyncAliasReturnType_es2017.ts +++ /dev/null @@ -1,6 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -type PromiseAlias = Promise; - -async function f(): PromiseAlias { -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncClass_es2017.ts b/tests/cases/conformance/async/es2017/asyncClass_es2017.ts deleted file mode 100644 index 78746c972d0..00000000000 --- a/tests/cases/conformance/async/es2017/asyncClass_es2017.ts +++ /dev/null @@ -1,4 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -async class C { -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts b/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts deleted file mode 100644 index 874c0b99239..00000000000 --- a/tests/cases/conformance/async/es2017/asyncConstructor_es2017.ts +++ /dev/null @@ -1,6 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -class C { - async constructor() { - } -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts b/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts deleted file mode 100644 index d7fd4888fed..00000000000 --- a/tests/cases/conformance/async/es2017/asyncDeclare_es2017.ts +++ /dev/null @@ -1,3 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -declare async function foo(): Promise; \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts b/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts deleted file mode 100644 index dc995206e84..00000000000 --- a/tests/cases/conformance/async/es2017/asyncEnum_es2017.ts +++ /dev/null @@ -1,5 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -async enum E { - Value -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts b/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts deleted file mode 100644 index 340c33138cf..00000000000 --- a/tests/cases/conformance/async/es2017/asyncGetter_es2017.ts +++ /dev/null @@ -1,6 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -class C { - async get foo() { - } -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts b/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts deleted file mode 100644 index 81f5b690edd..00000000000 --- a/tests/cases/conformance/async/es2017/asyncImportedPromise_es2017.ts +++ /dev/null @@ -1,10 +0,0 @@ -// @target: es2017 -// @module: commonjs -// @filename: task.ts -export class Task extends Promise { } - -// @filename: test.ts -import { Task } from "./task"; -class Test { - async example(): Task { return; } -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts b/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts deleted file mode 100644 index 252730f9ff6..00000000000 --- a/tests/cases/conformance/async/es2017/asyncInterface_es2017.ts +++ /dev/null @@ -1,4 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -async interface I { -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncModule_es2017.ts b/tests/cases/conformance/async/es2017/asyncModule_es2017.ts deleted file mode 100644 index 7c577e27fb9..00000000000 --- a/tests/cases/conformance/async/es2017/asyncModule_es2017.ts +++ /dev/null @@ -1,4 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -async module M { -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts b/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts deleted file mode 100644 index 920bdfb8bda..00000000000 --- a/tests/cases/conformance/async/es2017/asyncMultiFile_es2017.ts +++ /dev/null @@ -1,5 +0,0 @@ -// @target: es2017 -// @filename: a.ts -async function f() {} -// @filename: b.ts -function g() { } \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts b/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts deleted file mode 100644 index 95695168cea..00000000000 --- a/tests/cases/conformance/async/es2017/asyncQualifiedReturnType_es2017.ts +++ /dev/null @@ -1,9 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -namespace X { - export class MyPromise extends Promise { - } -} - -async function f(): X.MyPromise { -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts b/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts deleted file mode 100644 index 658c07d42e8..00000000000 --- a/tests/cases/conformance/async/es2017/asyncSetter_es2017.ts +++ /dev/null @@ -1,6 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -class C { - async set foo(value) { - } -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts b/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts deleted file mode 100644 index 493aa838ffe..00000000000 --- a/tests/cases/conformance/async/es2017/awaitUnion_es2017.ts +++ /dev/null @@ -1,14 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -declare let a: number | string; -declare let b: PromiseLike | PromiseLike; -declare let c: PromiseLike; -declare let d: number | PromiseLike; -declare let e: number | PromiseLike; -async function f() { - let await_a = await a; - let await_b = await b; - let await_c = await c; - let await_d = await d; - let await_e = await e; -} \ No newline at end of file diff --git a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts b/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts deleted file mode 100644 index 2585dc666f4..00000000000 --- a/tests/cases/conformance/async/es2017/functionDeclarations/asyncFunctionDeclaration15_es2017.ts +++ /dev/null @@ -1,25 +0,0 @@ -// @target: es2017 -// @noEmitHelpers: true -declare class Thenable { then(): void; } -declare let a: any; -declare let obj: { then: string; }; -declare let thenable: Thenable; -async function fn1() { } // valid: Promise -async function fn2(): { } { } // error -async function fn3(): any { } // error -async function fn4(): number { } // error -async function fn5(): PromiseLike { } // error -async function fn6(): Thenable { } // error -async function fn7() { return; } // valid: Promise -async function fn8() { return 1; } // valid: Promise -async function fn9() { return null; } // valid: Promise -async function fn10() { return undefined; } // valid: Promise -async function fn11() { return a; } // valid: Promise -async function fn12() { return obj; } // valid: Promise<{ then: string; }> -async function fn13() { return thenable; } // error -async function fn14() { await 1; } // valid: Promise -async function fn15() { await null; } // valid: Promise -async function fn16() { await undefined; } // valid: Promise -async function fn17() { await a; } // valid: Promise -async function fn18() { await obj; } // valid: Promise -async function fn19() { await thenable; } // error From 980a8947875fdf78231ea546767dee47393fabfa Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 14 Oct 2016 18:10:34 -0700 Subject: [PATCH 70/74] Fix emit issue regarding null/undefined in type annotations --- src/compiler/binder.ts | 113 +++++++++++------- src/compiler/emitter.ts | 19 ++- src/compiler/transformers/es6.ts | 2 + src/compiler/transformers/ts.ts | 46 ++++++- src/compiler/types.ts | 2 + .../reference/constructorArgsErrors1.js | 2 +- .../reference/constructorArgsErrors5.js | 2 +- .../parserErrorRecovery_ParameterList6.js | 1 - .../transformsElideNullUndefinedType.js | 54 +++++++++ .../transformsElideNullUndefinedType.symbols | 72 +++++++++++ .../transformsElideNullUndefinedType.types | 94 +++++++++++++++ .../reference/typeGuardFunctionErrors.js | 2 - .../transformsElideNullUndefinedType.ts | 32 +++++ 13 files changed, 392 insertions(+), 49 deletions(-) create mode 100644 tests/baselines/reference/transformsElideNullUndefinedType.js create mode 100644 tests/baselines/reference/transformsElideNullUndefinedType.symbols create mode 100644 tests/baselines/reference/transformsElideNullUndefinedType.types create mode 100644 tests/cases/compiler/transformsElideNullUndefinedType.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index b9e26e4f38d..4f01607289d 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2330,6 +2330,9 @@ namespace ts { case SyntaxKind.CallExpression: return computeCallExpression(node, subtreeFlags); + case SyntaxKind.NewExpression: + return computeNewExpression(node, subtreeFlags); + case SyntaxKind.ModuleDeclaration: return computeModuleDeclaration(node, subtreeFlags); @@ -2407,6 +2410,10 @@ namespace ts { const expression = node.expression; const expressionKind = expression.kind; + if (node.typeArguments) { + transformFlags |= TransformFlags.AssertTypeScript; + } + if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression || isSuperOrSuperProperty(expression, expressionKind)) { // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 @@ -2433,6 +2440,21 @@ namespace ts { return false; } + function computeNewExpression(node: NewExpression, subtreeFlags: TransformFlags) { + let transformFlags = subtreeFlags; + if (node.typeArguments) { + transformFlags |= TransformFlags.AssertTypeScript; + } + if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { + // If the this node contains a SpreadElementExpression then it is an ES6 + // node. + transformFlags |= TransformFlags.AssertES6; + } + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; + return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; + } + + function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; const operatorTokenKind = node.operatorToken.kind; @@ -2461,13 +2483,12 @@ namespace ts { const initializer = node.initializer; const dotDotDotToken = node.dotDotDotToken; - // If the parameter has a question token, then it is TypeScript syntax. - if (node.questionToken) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & TransformFlags.ContainsDecorators || isThisIdentifier(name)) { + // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript + // syntax. + if (node.questionToken + || node.type + || subtreeFlags & TransformFlags.ContainsDecorators + || isThisIdentifier(name)) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2526,7 +2547,8 @@ namespace ts { // TypeScript syntax. // An exported declaration may be TypeScript syntax. if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) - || (modifierFlags & ModifierFlags.Export)) { + || (modifierFlags & ModifierFlags.Export) + || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2547,7 +2569,8 @@ namespace ts { // A class with a parameter property assignment, property initializer, or decorator is // TypeScript syntax. - if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) { + if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask + || node.typeParameters) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2601,10 +2624,10 @@ namespace ts { function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const body = node.body; - if (body === undefined) { - // An overload constructor is TypeScript syntax. + // TypeScript-specific modifiers and overloads are TypeScript syntax + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2615,22 +2638,19 @@ namespace ts { function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) { // A MethodDeclaration is ES6 syntax. let transformFlags = subtreeFlags | TransformFlags.AssertES6; - const modifierFlags = getModifierFlags(node); - const body = node.body; - const typeParameters = node.typeParameters; - const asteriskToken = node.asteriskToken; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || typeParameters - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { + // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and + // overloads are TypeScript syntax. + if (node.decorators + || hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } @@ -2640,14 +2660,13 @@ namespace ts { function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const modifierFlags = getModifierFlags(node); - const body = node.body; - // A MethodDeclaration is TypeScript syntax if it is either async, abstract, overloaded, - // generic, or has a decorator. - if (!body - || (modifierFlags & (ModifierFlags.Async | ModifierFlags.Abstract)) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { + // Decorators, TypeScript-specific modifiers, type annotations, and overloads are + // TypeScript syntax. + if (node.decorators + || hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.type + || !node.body) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2673,7 +2692,6 @@ namespace ts { let transformFlags: TransformFlags; const modifierFlags = getModifierFlags(node); const body = node.body; - const asteriskToken = node.asteriskToken; if (!body || (modifierFlags & ModifierFlags.Ambient)) { // An ambient declaration is TypeScript syntax. @@ -2688,8 +2706,11 @@ namespace ts { transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES6; } - // If a FunctionDeclaration is async, then it is TypeScript syntax. - if (modifierFlags & ModifierFlags.Async) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (modifierFlags & ModifierFlags.TypeScriptModifier + || node.typeParameters + || node.type) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2705,7 +2726,7 @@ namespace ts { // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } } @@ -2716,11 +2737,12 @@ namespace ts { function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) { let transformFlags = subtreeFlags; - const modifierFlags = getModifierFlags(node); - const asteriskToken = node.asteriskToken; - // An async function expression is TypeScript syntax. - if (modifierFlags & ModifierFlags.Async) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2736,7 +2758,7 @@ namespace ts { // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { + if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { transformFlags |= TransformFlags.AssertGenerator; } @@ -2747,10 +2769,12 @@ namespace ts { function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. let transformFlags = subtreeFlags | TransformFlags.AssertES6; - const modifierFlags = getModifierFlags(node); - // An async arrow function is TypeScript syntax. - if (modifierFlags & ModifierFlags.Async) { + // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript + // syntax. + if (hasModifier(node, ModifierFlags.TypeScriptModifier) + || node.typeParameters + || node.type) { transformFlags |= TransformFlags.AssertTypeScript; } @@ -2787,6 +2811,11 @@ namespace ts { transformFlags |= TransformFlags.AssertES6 | TransformFlags.ContainsBindingPattern; } + // Type annotations are TypeScript syntax. + if (node.type) { + transformFlags |= TransformFlags.AssertTypeScript; + } + node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; return transformFlags & ~TransformFlags.NodeExcludes; } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 270fb0ca624..a77096618d6 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -504,15 +504,29 @@ const _super = (function (geti, seti) { // Contextual keywords case SyntaxKind.AbstractKeyword: + case SyntaxKind.AsKeyword: case SyntaxKind.AnyKeyword: case SyntaxKind.AsyncKeyword: + case SyntaxKind.AwaitKeyword: case SyntaxKind.BooleanKeyword: + case SyntaxKind.ConstructorKeyword: case SyntaxKind.DeclareKeyword: - case SyntaxKind.NumberKeyword: + case SyntaxKind.GetKeyword: + case SyntaxKind.IsKeyword: + case SyntaxKind.ModuleKeyword: + case SyntaxKind.NamespaceKeyword: + case SyntaxKind.NeverKeyword: case SyntaxKind.ReadonlyKeyword: + case SyntaxKind.RequireKeyword: + case SyntaxKind.NumberKeyword: + case SyntaxKind.SetKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.SymbolKeyword: + case SyntaxKind.TypeKeyword: + case SyntaxKind.UndefinedKeyword: + case SyntaxKind.FromKeyword: case SyntaxKind.GlobalKeyword: + case SyntaxKind.OfKeyword: writeTokenText(kind); return; @@ -1198,12 +1212,14 @@ const _super = (function (geti, seti) { function emitCallExpression(node: CallExpression) { emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, ListFormat.CallExpressionArguments); } function emitNewExpression(node: NewExpression) { write("new "); emitExpression(node.expression); + emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, ListFormat.NewExpressionArguments); } @@ -1575,6 +1591,7 @@ const _super = (function (geti, seti) { function emitVariableDeclaration(node: VariableDeclaration) { emit(node.name); + emitWithPrefix(": ", node.type); emitExpressionWithPrefix(" = ", node.initializer); } diff --git a/src/compiler/transformers/es6.ts b/src/compiler/transformers/es6.ts index 8d8a817c183..fd9f7d2406c 100644 --- a/src/compiler/transformers/es6.ts +++ b/src/compiler/transformers/es6.ts @@ -1416,6 +1416,7 @@ namespace ts { if (getAccessor) { const getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + setEmitFlags(getterFunction, EmitFlags.NoLeadingComments); const getter = createPropertyAssignment("get", getterFunction); setCommentRange(getter, getCommentRange(getAccessor)); properties.push(getter); @@ -1424,6 +1425,7 @@ namespace ts { if (setAccessor) { const setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + setEmitFlags(setterFunction, EmitFlags.NoLeadingComments); const setter = createPropertyAssignment("set", setterFunction); setCommentRange(setter, getCommentRange(setAccessor)); properties.push(setter); diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index 2c146c91bc3..f1ff9856bad 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -287,7 +287,7 @@ namespace ts { case SyntaxKind.Constructor: // TypeScript constructors are transformed in `visitClassDeclaration`. - return undefined; + return visitConstructor(node); case SyntaxKind.InterfaceDeclaration: // TypeScript interfaces are elided, but some comments may be preserved. @@ -377,6 +377,12 @@ namespace ts { // TypeScript type assertions are removed, but their subtrees are preserved. return visitAssertionExpression(node); + case SyntaxKind.CallExpression: + return visitCallExpression(node); + + case SyntaxKind.NewExpression: + return visitNewExpression(node); + case SyntaxKind.NonNullExpression: // TypeScript non-null expressions are removed, but their subtrees are preserved. return visitNonNullExpression(node); @@ -393,6 +399,9 @@ namespace ts { // TypeScript namespace exports for variable statements must be transformed. return visitVariableStatement(node); + case SyntaxKind.VariableDeclaration: + return visitVariableDeclaration(node); + case SyntaxKind.ModuleDeclaration: // TypeScript namespace declarations must be transformed. return visitModuleDeclaration(node); @@ -2088,6 +2097,14 @@ namespace ts { return !nodeIsMissing(node.body); } + function visitConstructor(node: ConstructorDeclaration) { + if (!shouldEmitFunctionLikeDeclaration(node)) { + return undefined; + } + + return visitEachChild(node, visitor, context); + } + /** * Visits a method declaration of a class. * @@ -2295,13 +2312,16 @@ namespace ts { function transformFunctionBodyWorker(body: Block, start = 0) { const savedCurrentScope = currentScope; + const savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentScope = body; + currentScopeFirstDeclarationsOfName = createMap(); startLexicalEnvironment(); const statements = visitNodes(body.statements, visitor, isStatement, start); const visited = updateBlock(body, statements); const declarations = endLexicalEnvironment(); currentScope = savedCurrentScope; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; return mergeFunctionBodyLexicalEnvironment(visited, declarations); } @@ -2481,6 +2501,14 @@ namespace ts { } } + function visitVariableDeclaration(node: VariableDeclaration) { + return updateVariableDeclaration( + node, + visitNode(node.name, visitor, isBindingName), + /*type*/ undefined, + visitNode(node.initializer, visitor, isExpression)); + } + /** * Visits an await expression. * @@ -2541,6 +2569,22 @@ namespace ts { return createPartiallyEmittedExpression(expression, node); } + function visitCallExpression(node: CallExpression) { + return updateCall( + node, + visitNode(node.expression, visitor, isExpression), + /*typeArguments*/ undefined, + visitNodes(node.arguments, visitor, isExpression)); + } + + function visitNewExpression(node: NewExpression) { + return updateNew( + node, + visitNode(node.expression, visitor, isExpression), + /*typeArguments*/ undefined, + visitNodes(node.arguments, visitor, isExpression)); + } + /** * Determines whether to emit an enum declaration. * diff --git a/src/compiler/types.ts b/src/compiler/types.ts index e87fa3e786f..d66677910f8 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -456,6 +456,8 @@ namespace ts { // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property. ParameterPropertyModifier = AccessibilityModifier | Readonly, NonPublicAccessibilityModifier = Private | Protected, + + TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Async | Const } export const enum JsxFlags { diff --git a/tests/baselines/reference/constructorArgsErrors1.js b/tests/baselines/reference/constructorArgsErrors1.js index 15c5e64952b..bb0725ab8b9 100644 --- a/tests/baselines/reference/constructorArgsErrors1.js +++ b/tests/baselines/reference/constructorArgsErrors1.js @@ -6,7 +6,7 @@ class foo { //// [constructorArgsErrors1.js] var foo = (function () { - function foo(static a) { + function foo(a) { } return foo; }()); diff --git a/tests/baselines/reference/constructorArgsErrors5.js b/tests/baselines/reference/constructorArgsErrors5.js index 6ba68cb88b4..c481d6f323c 100644 --- a/tests/baselines/reference/constructorArgsErrors5.js +++ b/tests/baselines/reference/constructorArgsErrors5.js @@ -7,7 +7,7 @@ class foo { //// [constructorArgsErrors5.js] var foo = (function () { - function foo(export a) { + function foo(a) { } return foo; }()); diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList6.js b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js index c3d5a838f88..7c221aaa20a 100644 --- a/tests/baselines/reference/parserErrorRecovery_ParameterList6.js +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js @@ -7,7 +7,6 @@ class Foo { var Foo = (function () { function Foo() { } - Foo.prototype.banana = function (x) { }; return Foo; }()); break ; diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.js b/tests/baselines/reference/transformsElideNullUndefinedType.js new file mode 100644 index 00000000000..a5e27eee08b --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.js @@ -0,0 +1,54 @@ +//// [transformsElideNullUndefinedType.ts] + +var v0: null; +var v1: undefined; + +function f0(): null { return null; } +function f1(): undefined { return undefined; } + +var f2 = function (): null { return null; } +var f3 = function (): undefined { return undefined; } + +var f4 = (): null => null; +var f5 = (): undefined => undefined; + +function f6(p0: null) { } +function f7(p1: undefined) { } + +class C { + m0(): null { return null; } + m1(): undefined { return undefined; } + + get a0(): null { return null; } + get a1(): undefined { return undefined; } +} + +declare function fn(); + +fn(); +fn(); + +new C(); +new C(); + +//// [transformsElideNullUndefinedType.js] +var v0; +var v1; +function f0() { return null; } +function f1() { return undefined; } +var f2 = function () { return null; }; +var f3 = function () { return undefined; }; +var f4 = () => null; +var f5 = () => undefined; +function f6(p0) { } +function f7(p1) { } +class C { + m0() { return null; } + m1() { return undefined; } + get a0() { return null; } + get a1() { return undefined; } +} +fn(); +fn(); +new C(); +new C(); diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.symbols b/tests/baselines/reference/transformsElideNullUndefinedType.symbols new file mode 100644 index 00000000000..0c9333d9820 --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.symbols @@ -0,0 +1,72 @@ +=== tests/cases/compiler/transformsElideNullUndefinedType.ts === + +var v0: null; +>v0 : Symbol(v0, Decl(transformsElideNullUndefinedType.ts, 1, 3)) + +var v1: undefined; +>v1 : Symbol(v1, Decl(transformsElideNullUndefinedType.ts, 2, 3)) + +function f0(): null { return null; } +>f0 : Symbol(f0, Decl(transformsElideNullUndefinedType.ts, 2, 18)) + +function f1(): undefined { return undefined; } +>f1 : Symbol(f1, Decl(transformsElideNullUndefinedType.ts, 4, 36)) +>undefined : Symbol(undefined) + +var f2 = function (): null { return null; } +>f2 : Symbol(f2, Decl(transformsElideNullUndefinedType.ts, 7, 3)) + +var f3 = function (): undefined { return undefined; } +>f3 : Symbol(f3, Decl(transformsElideNullUndefinedType.ts, 8, 3)) +>undefined : Symbol(undefined) + +var f4 = (): null => null; +>f4 : Symbol(f4, Decl(transformsElideNullUndefinedType.ts, 10, 3)) + +var f5 = (): undefined => undefined; +>f5 : Symbol(f5, Decl(transformsElideNullUndefinedType.ts, 11, 3)) +>undefined : Symbol(undefined) + +function f6(p0: null) { } +>f6 : Symbol(f6, Decl(transformsElideNullUndefinedType.ts, 11, 36)) +>p0 : Symbol(p0, Decl(transformsElideNullUndefinedType.ts, 13, 12)) + +function f7(p1: undefined) { } +>f7 : Symbol(f7, Decl(transformsElideNullUndefinedType.ts, 13, 25)) +>p1 : Symbol(p1, Decl(transformsElideNullUndefinedType.ts, 14, 12)) + +class C { +>C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 16, 8)) + + m0(): null { return null; } +>m0 : Symbol(C.m0, Decl(transformsElideNullUndefinedType.ts, 16, 12)) + + m1(): undefined { return undefined; } +>m1 : Symbol(C.m1, Decl(transformsElideNullUndefinedType.ts, 17, 31)) +>undefined : Symbol(undefined) + + get a0(): null { return null; } +>a0 : Symbol(C.a0, Decl(transformsElideNullUndefinedType.ts, 18, 41)) + + get a1(): undefined { return undefined; } +>a1 : Symbol(C.a1, Decl(transformsElideNullUndefinedType.ts, 20, 35)) +>undefined : Symbol(undefined) +} + +declare function fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 24, 20)) + +fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) + +fn(); +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) + +new C(); +>C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) + +new C(); +>C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) + diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.types b/tests/baselines/reference/transformsElideNullUndefinedType.types new file mode 100644 index 00000000000..66a73c83141 --- /dev/null +++ b/tests/baselines/reference/transformsElideNullUndefinedType.types @@ -0,0 +1,94 @@ +=== tests/cases/compiler/transformsElideNullUndefinedType.ts === + +var v0: null; +>v0 : null +>null : null + +var v1: undefined; +>v1 : undefined + +function f0(): null { return null; } +>f0 : () => null +>null : null +>null : null + +function f1(): undefined { return undefined; } +>f1 : () => undefined +>undefined : undefined + +var f2 = function (): null { return null; } +>f2 : () => null +>function (): null { return null; } : () => null +>null : null +>null : null + +var f3 = function (): undefined { return undefined; } +>f3 : () => undefined +>function (): undefined { return undefined; } : () => undefined +>undefined : undefined + +var f4 = (): null => null; +>f4 : () => null +>(): null => null : () => null +>null : null +>null : null + +var f5 = (): undefined => undefined; +>f5 : () => undefined +>(): undefined => undefined : () => undefined +>undefined : undefined + +function f6(p0: null) { } +>f6 : (p0: null) => void +>p0 : null +>null : null + +function f7(p1: undefined) { } +>f7 : (p1: undefined) => void +>p1 : undefined + +class C { +>C : C +>T : T + + m0(): null { return null; } +>m0 : () => null +>null : null +>null : null + + m1(): undefined { return undefined; } +>m1 : () => undefined +>undefined : undefined + + get a0(): null { return null; } +>a0 : null +>null : null +>null : null + + get a1(): undefined { return undefined; } +>a1 : undefined +>undefined : undefined +} + +declare function fn(); +>fn : () => any +>T : T + +fn(); +>fn() : any +>fn : () => any +>null : null + +fn(); +>fn() : any +>fn : () => any + +new C(); +>new C() : C +>C : typeof C +>null : null + +new C(); +>new C() : C +>C : typeof C + diff --git a/tests/baselines/reference/typeGuardFunctionErrors.js b/tests/baselines/reference/typeGuardFunctionErrors.js index 6f0880ad7f5..244b0df3333 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.js +++ b/tests/baselines/reference/typeGuardFunctionErrors.js @@ -171,7 +171,6 @@ var C = (function (_super) { function hasANonBooleanReturnStatement(x) { return ''; } -function hasTypeGuardTypeInsideTypeGuardType(x) { } is; A; { @@ -232,7 +231,6 @@ function b2(a, A) { if (a === void 0) { a = is; } } ; -function b3() { } is; A; { diff --git a/tests/cases/compiler/transformsElideNullUndefinedType.ts b/tests/cases/compiler/transformsElideNullUndefinedType.ts new file mode 100644 index 00000000000..244f2ea9c75 --- /dev/null +++ b/tests/cases/compiler/transformsElideNullUndefinedType.ts @@ -0,0 +1,32 @@ +// @target: es6 + +var v0: null; +var v1: undefined; + +function f0(): null { return null; } +function f1(): undefined { return undefined; } + +var f2 = function (): null { return null; } +var f3 = function (): undefined { return undefined; } + +var f4 = (): null => null; +var f5 = (): undefined => undefined; + +function f6(p0: null) { } +function f7(p1: undefined) { } + +class C { + m0(): null { return null; } + m1(): undefined { return undefined; } + + get a0(): null { return null; } + get a1(): undefined { return undefined; } +} + +declare function fn(); + +fn(); +fn(); + +new C(); +new C(); \ No newline at end of file From a1cbfcae4b2560f2709a88e4d41185ac548c5e5c Mon Sep 17 00:00:00 2001 From: Zhengbo Li Date: Fri, 14 Oct 2016 20:50:12 -0700 Subject: [PATCH 71/74] Add missing trigger file (#11641) * Add missing trigger file property for config file diags * Add test --- src/harness/unittests/tsserverProjectSystem.ts | 10 +++++++++- src/server/editorServices.ts | 12 ++++++------ src/server/session.ts | 2 +- 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/harness/unittests/tsserverProjectSystem.ts b/src/harness/unittests/tsserverProjectSystem.ts index 468d6aac14b..9d086e4549e 100644 --- a/src/harness/unittests/tsserverProjectSystem.ts +++ b/src/harness/unittests/tsserverProjectSystem.ts @@ -135,7 +135,7 @@ namespace ts.projectSystem { } export class TestServerEventManager { - private events: server.ProjectServiceEvent[] = []; + public events: server.ProjectServiceEvent[] = []; handler: server.ProjectServiceEventHandler = (event: server.ProjectServiceEvent) => { this.events.push(event); @@ -2286,6 +2286,14 @@ namespace ts.projectSystem { const session = createSession(host, /*typingsInstaller*/ undefined, serverEventManager.handler); openFilesForSession([file], session); serverEventManager.checkEventCountOfType("configFileDiag", 1); + + for (const event of serverEventManager.events) { + if (event.eventName === "configFileDiag") { + assert.equal(event.data.configFileName, configFile.path); + assert.equal(event.data.triggerFile, file.path); + return; + } + } }); it("are generated when the config file doesn't have errors", () => { diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 91b9f90c88b..54b257242fd 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -11,7 +11,7 @@ namespace ts.server { export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; export type ProjectServiceEvent = - { eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile?: string, configFileName: string, diagnostics: Diagnostic[] } }; + { eventName: "context", data: { project: Project, fileName: NormalizedPath } } | { eventName: "configFileDiag", data: { triggerFile: string, configFileName: string, diagnostics: Diagnostic[] } }; export interface ProjectServiceEventHandler { (event: ProjectServiceEvent): void; @@ -392,12 +392,12 @@ namespace ts.server { this.throttledOperations.schedule( project.configFileName, /*delay*/250, - () => this.handleChangeInSourceFileForConfiguredProject(project)); + () => this.handleChangeInSourceFileForConfiguredProject(project, fileName)); } - private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject) { + private handleChangeInSourceFileForConfiguredProject(project: ConfiguredProject, triggerFile: string) { const { projectOptions, configFileErrors } = this.convertConfigFileContentToProjectOptions(project.configFileName); - this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors, triggerFile); const newRootFiles = projectOptions.files.map((f => this.getCanonicalFileName(f))); const currentRootFiles = project.getRootFiles().map((f => this.getCanonicalFileName(f))); @@ -434,7 +434,7 @@ namespace ts.server { } const { configFileErrors } = this.convertConfigFileContentToProjectOptions(fileName); - this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.reportConfigFileDiagnostics(fileName, configFileErrors, fileName); this.logger.info(`Detected newly added tsconfig file: ${fileName}`); this.reloadProjects(); @@ -757,7 +757,7 @@ namespace ts.server { return project; } - private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string) { + private reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile: string) { if (!this.eventHandler) { return; } diff --git a/src/server/session.ts b/src/server/session.ts index 539142eff18..3df6a1acb51 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -761,7 +761,7 @@ namespace ts.server { if (this.eventHander) { this.eventHander({ eventName: "configFileDiag", - data: { fileName, configFileName, diagnostics: configFileErrors || [] } + data: { triggerFile: fileName, configFileName, diagnostics: configFileErrors || [] } }); } } From 40e99e7f6691b356c3a4d1da873cd799812d29d4 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Fri, 14 Oct 2016 21:34:59 -0700 Subject: [PATCH 72/74] Updated comment --- src/compiler/transformers/ts.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.ts index f1ff9856bad..1189c1380ab 100644 --- a/src/compiler/transformers/ts.ts +++ b/src/compiler/transformers/ts.ts @@ -286,7 +286,6 @@ namespace ts { // TypeScript property declarations are elided. case SyntaxKind.Constructor: - // TypeScript constructors are transformed in `visitClassDeclaration`. return visitConstructor(node); case SyntaxKind.InterfaceDeclaration: From a4a7c237b3b55ad250fa2c55a66fd1cce4c3f071 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Sat, 15 Oct 2016 15:18:32 -0700 Subject: [PATCH 73/74] Fix issues from merge --- src/compiler/binder.ts | 8 +- src/compiler/binder.ts.orig | 3181 ----------------------------------- 2 files changed, 4 insertions(+), 3185 deletions(-) delete mode 100644 src/compiler/binder.ts.orig diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index d71e6ea2c85..4711d54e0b2 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2469,7 +2469,7 @@ namespace ts { if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { // If the this node contains a SpreadElementExpression then it is an ES6 // node. - transformFlags |= TransformFlags.AssertES6; + transformFlags |= TransformFlags.AssertES2015; } node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; @@ -2671,7 +2671,7 @@ namespace ts { } // An async method declaration is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { + if (hasModifier(node, ModifierFlags.Async)) { transformFlags |= TransformFlags.AssertES2017; } @@ -2778,7 +2778,7 @@ namespace ts { } // An async function expression is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { + if (hasModifier(node, ModifierFlags.Async)) { transformFlags |= TransformFlags.AssertES2017; } @@ -2815,7 +2815,7 @@ namespace ts { } // An async arrow function is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { + if (hasModifier(node, ModifierFlags.Async)) { transformFlags |= TransformFlags.AssertES2017; } diff --git a/src/compiler/binder.ts.orig b/src/compiler/binder.ts.orig deleted file mode 100644 index 6cbd7d746d1..00000000000 --- a/src/compiler/binder.ts.orig +++ /dev/null @@ -1,3181 +0,0 @@ -/// -/// - -/* @internal */ -namespace ts { - export const enum ModuleInstanceState { - NonInstantiated = 0, - Instantiated = 1, - ConstEnumOnly = 2 - } - - interface ActiveLabel { - name: string; - breakTarget: FlowLabel; - continueTarget: FlowLabel; - referenced: boolean; - } - - export function getModuleInstanceState(node: Node): ModuleInstanceState { - // A module is uninstantiated if it contains only - // 1. interface declarations, type alias declarations - if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.TypeAliasDeclaration) { - return ModuleInstanceState.NonInstantiated; - } - // 2. const enum declarations - else if (isConstEnumDeclaration(node)) { - return ModuleInstanceState.ConstEnumOnly; - } - // 3. non-exported import declarations - else if ((node.kind === SyntaxKind.ImportDeclaration || node.kind === SyntaxKind.ImportEqualsDeclaration) && !(hasModifier(node, ModifierFlags.Export))) { - return ModuleInstanceState.NonInstantiated; - } - // 4. other uninstantiated module declarations. - else if (node.kind === SyntaxKind.ModuleBlock) { - let state = ModuleInstanceState.NonInstantiated; - forEachChild(node, n => { - switch (getModuleInstanceState(n)) { - case ModuleInstanceState.NonInstantiated: - // child is non-instantiated - continue searching - return false; - case ModuleInstanceState.ConstEnumOnly: - // child is const enum only - record state and continue searching - state = ModuleInstanceState.ConstEnumOnly; - return false; - case ModuleInstanceState.Instantiated: - // child is instantiated - record state and stop - state = ModuleInstanceState.Instantiated; - return true; - } - }); - return state; - } - else if (node.kind === SyntaxKind.ModuleDeclaration) { - const body = (node).body; - return body ? getModuleInstanceState(body) : ModuleInstanceState.Instantiated; - } - else { - return ModuleInstanceState.Instantiated; - } - } - - const enum ContainerFlags { - // The current node is not a container, and no container manipulation should happen before - // recursing into it. - None = 0, - - // The current node is a container. It should be set as the current container (and block- - // container) before recursing into it. The current node does not have locals. Examples: - // - // Classes, ObjectLiterals, TypeLiterals, Interfaces... - IsContainer = 1 << 0, - - // The current node is a block-scoped-container. It should be set as the current block- - // container before recursing into it. Examples: - // - // Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements... - IsBlockScopedContainer = 1 << 1, - - // The current node is the container of a control flow path. The current control flow should - // be saved and restored, and a new control flow initialized within the container. - IsControlFlowContainer = 1 << 2, - - IsFunctionLike = 1 << 3, - IsFunctionExpression = 1 << 4, - HasLocals = 1 << 5, - IsInterface = 1 << 6, - IsObjectLiteralOrClassExpressionMethod = 1 << 7, - } - - const binder = createBinder(); - - export function bindSourceFile(file: SourceFile, options: CompilerOptions) { - performance.mark("beforeBind"); - binder(file, options); - performance.mark("afterBind"); - performance.measure("Bind", "beforeBind", "afterBind"); - } - - function createBinder(): (file: SourceFile, options: CompilerOptions) => void { - let file: SourceFile; - let options: CompilerOptions; - let languageVersion: ScriptTarget; - let parent: Node; - let container: Node; - let blockScopeContainer: Node; - let lastContainer: Node; - let seenThisKeyword: boolean; - - // state used by control flow analysis - let currentFlow: FlowNode; - let currentBreakTarget: FlowLabel; - let currentContinueTarget: FlowLabel; - let currentReturnTarget: FlowLabel; - let currentTrueTarget: FlowLabel; - let currentFalseTarget: FlowLabel; - let preSwitchCaseFlow: FlowNode; - let activeLabels: ActiveLabel[]; - let hasExplicitReturn: boolean; - - // state used for emit helpers - let emitFlags: NodeFlags; - - // If this file is an external module, then it is automatically in strict-mode according to - // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places or if we hit a class/namespace - // or if compiler options contain alwaysStrict. - let inStrictMode: boolean; - - let symbolCount = 0; - let Symbol: { new (flags: SymbolFlags, name: string): Symbol }; - let classifiableNames: Map; - - const unreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; - const reportedUnreachableFlow: FlowNode = { flags: FlowFlags.Unreachable }; - - // state used to aggregate transform flags during bind. - let subtreeTransformFlags: TransformFlags = TransformFlags.None; - let skipTransformFlagAggregation: boolean; - - function bindSourceFile(f: SourceFile, opts: CompilerOptions) { - file = f; - options = opts; - languageVersion = getEmitScriptTarget(options); - inStrictMode = bindInStrictMode(file, opts); - classifiableNames = createMap(); - symbolCount = 0; - skipTransformFlagAggregation = isDeclarationFile(file); - - Symbol = objectAllocator.getSymbolConstructor(); - - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; - } - - file = undefined; - options = undefined; - languageVersion = undefined; - parent = undefined; - container = undefined; - blockScopeContainer = undefined; - lastContainer = undefined; - seenThisKeyword = false; - currentFlow = undefined; - currentBreakTarget = undefined; - currentContinueTarget = undefined; - currentReturnTarget = undefined; - currentTrueTarget = undefined; - currentFalseTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - emitFlags = NodeFlags.None; - subtreeTransformFlags = TransformFlags.None; - } - - return bindSourceFile; - - function bindInStrictMode(file: SourceFile, opts: CompilerOptions): boolean { - if (opts.alwaysStrict && !isDeclarationFile(file)) { - // bind in strict mode source files with alwaysStrict option - return true; - } - else { - return !!file.externalModuleIndicator; - } - } - - function createSymbol(flags: SymbolFlags, name: string): Symbol { - symbolCount++; - return new Symbol(flags, name); - } - - function addDeclarationToSymbol(symbol: Symbol, node: Declaration, symbolFlags: SymbolFlags) { - symbol.flags |= symbolFlags; - - node.symbol = symbol; - - if (!symbol.declarations) { - symbol.declarations = []; - } - symbol.declarations.push(node); - - if (symbolFlags & SymbolFlags.HasExports && !symbol.exports) { - symbol.exports = createMap(); - } - - if (symbolFlags & SymbolFlags.HasMembers && !symbol.members) { - symbol.members = createMap(); - } - - if (symbolFlags & SymbolFlags.Value) { - const valueDeclaration = symbol.valueDeclaration; - if (!valueDeclaration || - (valueDeclaration.kind !== node.kind && valueDeclaration.kind === SyntaxKind.ModuleDeclaration)) { - // other kinds of value declarations take precedence over modules - symbol.valueDeclaration = node; - } - } - } - - // Should not be called on a declaration with a computed property name, - // unless it is a well known Symbol. - function getDeclarationName(node: Declaration): string { - if (node.name) { - if (isAmbientModule(node)) { - return isGlobalScopeAugmentation(node) ? "__global" : `"${(node.name).text}"`; - } - if (node.name.kind === SyntaxKind.ComputedPropertyName) { - const nameExpression = (node.name).expression; - // treat computed property names where expression is string/numeric literal as just string/numeric literal - if (isStringOrNumericLiteral(nameExpression.kind)) { - return (nameExpression).text; - } - - Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); - return getPropertyNameForKnownSymbolName((nameExpression).name.text); - } - return (node.name).text; - } - switch (node.kind) { - case SyntaxKind.Constructor: - return "__constructor"; - case SyntaxKind.FunctionType: - case SyntaxKind.CallSignature: - return "__call"; - case SyntaxKind.ConstructorType: - case SyntaxKind.ConstructSignature: - return "__new"; - case SyntaxKind.IndexSignature: - return "__index"; - case SyntaxKind.ExportDeclaration: - return "__export"; - case SyntaxKind.ExportAssignment: - return (node).isExportEquals ? "export=" : "default"; - case SyntaxKind.BinaryExpression: - switch (getSpecialPropertyAssignmentKind(node)) { - case SpecialPropertyAssignmentKind.ModuleExports: - // module.exports = ... - return "export="; - case SpecialPropertyAssignmentKind.ExportsProperty: - case SpecialPropertyAssignmentKind.ThisProperty: - // exports.x = ... or this.y = ... - return ((node as BinaryExpression).left as PropertyAccessExpression).name.text; - case SpecialPropertyAssignmentKind.PrototypeProperty: - // className.prototype.methodName = ... - return (((node as BinaryExpression).left as PropertyAccessExpression).expression as PropertyAccessExpression).name.text; - } - Debug.fail("Unknown binary declaration kind"); - break; - - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.ClassDeclaration: - return hasModifier(node, ModifierFlags.Default) ? "default" : undefined; - case SyntaxKind.JSDocFunctionType: - return isJSDocConstructSignature(node) ? "__new" : "__call"; - case SyntaxKind.Parameter: - // Parameters with names are handled at the top of this function. Parameters - // without names can only come from JSDocFunctionTypes. - Debug.assert(node.parent.kind === SyntaxKind.JSDocFunctionType); - let functionType = node.parent; - let index = indexOf(functionType.parameters, node); - return "arg" + index; - case SyntaxKind.JSDocTypedefTag: - const parentNode = node.parent && node.parent.parent; - let nameFromParentNode: string; - if (parentNode && parentNode.kind === SyntaxKind.VariableStatement) { - if ((parentNode).declarationList.declarations.length > 0) { - const nameIdentifier = (parentNode).declarationList.declarations[0].name; - if (nameIdentifier.kind === SyntaxKind.Identifier) { - nameFromParentNode = (nameIdentifier).text; - } - } - } - return nameFromParentNode; - } - } - - function getDisplayName(node: Declaration): string { - return node.name ? declarationNameToString(node.name) : getDeclarationName(node); - } - - /** - * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names. - * @param symbolTable - The symbol table which node will be added to. - * @param parent - node's parent declaration. - * @param node - The declaration to be added to the symbol table - * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.) - * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations. - */ - function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { - Debug.assert(!hasDynamicName(node)); - - const isDefaultExport = hasModifier(node, ModifierFlags.Default); - - // The exported symbol for an export default function/class node is always named "default" - const name = isDefaultExport && parent ? "default" : getDeclarationName(node); - - let symbol: Symbol; - if (name === undefined) { - symbol = createSymbol(SymbolFlags.None, "__missing"); - } - else { - // Check and see if the symbol table already has a symbol with this name. If not, - // create a new symbol with this name and add it to the table. Note that we don't - // give the new symbol any flags *yet*. This ensures that it will not conflict - // with the 'excludes' flags we pass in. - // - // If we do get an existing symbol, see if it conflicts with the new symbol we're - // creating. For example, a 'var' symbol and a 'class' symbol will conflict within - // the same symbol table. If we have a conflict, report the issue on each - // declaration we have for this symbol, and then create a new symbol for this - // declaration. - // - // Note that when properties declared in Javascript constructors - // (marked by isReplaceableByMethod) conflict with another symbol, the property loses. - // Always. This allows the common Javascript pattern of overwriting a prototype method - // with an bound instance method of the same type: `this.method = this.method.bind(this)` - // - // If we created a new symbol, either because we didn't have a symbol with this name - // in the symbol table, or we conflicted with an existing symbol, then just add this - // node as the sole declaration of the new symbol. - // - // Otherwise, we'll be merging into a compatible existing symbol (for example when - // you have multiple 'vars' with the same name in the same container). In this case - // just add this node into the declarations list of the symbol. - symbol = symbolTable[name] || (symbolTable[name] = createSymbol(SymbolFlags.None, name)); - - if (name && (includes & SymbolFlags.Classifiable)) { - classifiableNames[name] = name; - } - - if (symbol.flags & excludes) { - if (symbol.isReplaceableByMethod) { - // Javascript constructor-declared symbols can be discarded in favor of - // prototype symbols like methods. - symbol = symbolTable[name] = createSymbol(SymbolFlags.None, name); - } - else { - if (node.name) { - node.name.parent = node; - } - - // Report errors every position with duplicate declaration - // Report errors on previous encountered declarations - let message = symbol.flags & SymbolFlags.BlockScopedVariable - ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 - : Diagnostics.Duplicate_identifier_0; - - if (symbol.declarations && symbol.declarations.length) { - // If the current node is a default export of some sort, then check if - // there are any other default exports that we need to error on. - // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. - if (isDefaultExport) { - message = Diagnostics.A_module_cannot_have_multiple_default_exports; - } - else { - // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. - // Error on multiple export default in the following case: - // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default - // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) - if (symbol.declarations && symbol.declarations.length && - (isDefaultExport || (node.kind === SyntaxKind.ExportAssignment && !(node).isExportEquals))) { - message = Diagnostics.A_module_cannot_have_multiple_default_exports; - } - } - } - - forEach(symbol.declarations, declaration => { - file.bindDiagnostics.push(createDiagnosticForNode(declaration.name || declaration, message, getDisplayName(declaration))); - }); - file.bindDiagnostics.push(createDiagnosticForNode(node.name || node, message, getDisplayName(node))); - - symbol = createSymbol(SymbolFlags.None, name); - } - } - } - - addDeclarationToSymbol(symbol, node, includes); - symbol.parent = parent; - - return symbol; - } - - function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - const hasExportModifier = getCombinedModifierFlags(node) & ModifierFlags.Export; - if (symbolFlags & SymbolFlags.Alias) { - if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - else { - // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue, - // ExportType, or ExportContainer flag, and an associated export symbol with all the correct flags set - // on it. There are 2 main reasons: - // - // 1. We treat locals and exports of the same name as mutually exclusive within a container. - // That means the binder will issue a Duplicate Identifier error if you mix locals and exports - // with the same name in the same container. - // TODO: Make this a more specific error and decouple it from the exclusion logic. - // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, - // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way - // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - - // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge - // 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 (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) { - const exportKind = - (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | - (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | - (symbolFlags & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); - const local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); - local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - node.localSymbol = local; - return local; - } - else { - return declareSymbol(container.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - } - - // All container nodes are kept on a linked list in declaration order. This list is used by - // the getLocalNameOfContainer function in the type checker to validate that the local name - // used for a container is unique. - function bindContainer(node: Node, containerFlags: ContainerFlags) { - // Before we recurse into a node's children, we first save the existing parent, container - // and block-container. Then after we pop out of processing the children, we restore - // these saved values. - const saveContainer = container; - const savedBlockScopeContainer = blockScopeContainer; - - // Depending on what kind of node this is, we may have to adjust the current container - // and block-container. If the current node is a container, then it is automatically - // considered the current block-container as well. Also, for containers that we know - // may contain locals, we proactively initialize the .locals field. We do this because - // it's highly likely that the .locals will be needed to place some child in (for example, - // a parameter, or variable declaration). - // - // However, we do not proactively create the .locals for block-containers because it's - // totally normal and common for block-containers to never actually have a block-scoped - // variable in them. We don't want to end up allocating an object for every 'block' we - // run into when most of them won't be necessary. - // - // Finally, if this is a block-container, then we clear out any existing .locals object - // it may contain within it. This happens in incremental scenarios. Because we can be - // reusing a node from a previous compilation, that node may have had 'locals' created - // for it. We must clear this so we don't accidentally move any stale data forward from - // a previous compilation. - if (containerFlags & ContainerFlags.IsContainer) { - container = blockScopeContainer = node; - if (containerFlags & ContainerFlags.HasLocals) { - container.locals = createMap(); - } - addToContainerChain(container); - } - else if (containerFlags & ContainerFlags.IsBlockScopedContainer) { - blockScopeContainer = node; - blockScopeContainer.locals = undefined; - } - if (containerFlags & ContainerFlags.IsControlFlowContainer) { - const saveCurrentFlow = currentFlow; - const saveBreakTarget = currentBreakTarget; - const saveContinueTarget = currentContinueTarget; - const saveReturnTarget = currentReturnTarget; - const saveActiveLabels = activeLabels; - const saveHasExplicitReturn = hasExplicitReturn; - const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !!getImmediatelyInvokedFunctionExpression(node); - // An IIFE is considered part of the containing control flow. Return statements behave - // similarly to break statements that exit to a label just past the statement body. - if (isIIFE) { - currentReturnTarget = createBranchLabel(); - } - else { - currentFlow = { flags: FlowFlags.Start }; - if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { - (currentFlow).container = node; - } - currentReturnTarget = undefined; - } - currentBreakTarget = undefined; - currentContinueTarget = undefined; - activeLabels = undefined; - hasExplicitReturn = false; - bindChildren(node); - // Reset all reachability check related flags on node (for incremental scenarios) - // Reset all emit helper flags on node (for incremental scenarios) - node.flags &= ~NodeFlags.ReachabilityAndEmitFlags; - if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((node).body)) { - node.flags |= NodeFlags.HasImplicitReturn; - if (hasExplicitReturn) node.flags |= NodeFlags.HasExplicitReturn; - } - if (node.kind === SyntaxKind.SourceFile) { - node.flags |= emitFlags; - } - if (isIIFE) { - addAntecedent(currentReturnTarget, currentFlow); - currentFlow = finishFlowLabel(currentReturnTarget); - } - else { - currentFlow = saveCurrentFlow; - } - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - currentReturnTarget = saveReturnTarget; - activeLabels = saveActiveLabels; - hasExplicitReturn = saveHasExplicitReturn; - } - else if (containerFlags & ContainerFlags.IsInterface) { - seenThisKeyword = false; - bindChildren(node); - node.flags = seenThisKeyword ? node.flags | NodeFlags.ContainsThis : node.flags & ~NodeFlags.ContainsThis; - } - else { - bindChildren(node); - } - container = saveContainer; - blockScopeContainer = savedBlockScopeContainer; - } - - function bindChildren(node: Node): void { - if (skipTransformFlagAggregation) { - bindChildrenWorker(node); - } - else if (node.transformFlags & TransformFlags.HasComputedFlags) { - skipTransformFlagAggregation = true; - bindChildrenWorker(node); - skipTransformFlagAggregation = false; - } - else { - const savedSubtreeTransformFlags = subtreeTransformFlags; - subtreeTransformFlags = 0; - bindChildrenWorker(node); - subtreeTransformFlags = savedSubtreeTransformFlags | computeTransformFlagsForNode(node, subtreeTransformFlags); - } - } - - function bindChildrenWorker(node: Node): void { - // Binding of JsDocComment should be done before the current block scope container changes. - // because the scope of JsDocComment should not be affected by whether the current node is a - // container or not. - if (isInJavaScriptFile(node) && node.jsDocComments) { - forEach(node.jsDocComments, bind); - } - if (checkUnreachable(node)) { - forEachChild(node, bind); - return; - } - switch (node.kind) { - case SyntaxKind.WhileStatement: - bindWhileStatement(node); - break; - case SyntaxKind.DoStatement: - bindDoStatement(node); - break; - case SyntaxKind.ForStatement: - bindForStatement(node); - break; - case SyntaxKind.ForInStatement: - case SyntaxKind.ForOfStatement: - bindForInOrForOfStatement(node); - break; - case SyntaxKind.IfStatement: - bindIfStatement(node); - break; - case SyntaxKind.ReturnStatement: - case SyntaxKind.ThrowStatement: - bindReturnOrThrow(node); - break; - case SyntaxKind.BreakStatement: - case SyntaxKind.ContinueStatement: - bindBreakOrContinueStatement(node); - break; - case SyntaxKind.TryStatement: - bindTryStatement(node); - break; - case SyntaxKind.SwitchStatement: - bindSwitchStatement(node); - break; - case SyntaxKind.CaseBlock: - bindCaseBlock(node); - break; - case SyntaxKind.CaseClause: - bindCaseClause(node); - break; - case SyntaxKind.LabeledStatement: - bindLabeledStatement(node); - break; - case SyntaxKind.PrefixUnaryExpression: - bindPrefixUnaryExpressionFlow(node); - break; - case SyntaxKind.PostfixUnaryExpression: - bindPostfixUnaryExpressionFlow(node); - break; - case SyntaxKind.BinaryExpression: - bindBinaryExpressionFlow(node); - break; - case SyntaxKind.DeleteExpression: - bindDeleteExpressionFlow(node); - break; - case SyntaxKind.ConditionalExpression: - bindConditionalExpressionFlow(node); - break; - case SyntaxKind.VariableDeclaration: - bindVariableDeclarationFlow(node); - break; - case SyntaxKind.CallExpression: - bindCallExpressionFlow(node); - break; - default: - forEachChild(node, bind); - break; - } - } - - function isNarrowingExpression(expr: Expression): boolean { - switch (expr.kind) { - case SyntaxKind.Identifier: - case SyntaxKind.ThisKeyword: - case SyntaxKind.PropertyAccessExpression: - return isNarrowableReference(expr); - case SyntaxKind.CallExpression: - return hasNarrowableArgument(expr); - case SyntaxKind.ParenthesizedExpression: - return isNarrowingExpression((expr).expression); - case SyntaxKind.BinaryExpression: - return isNarrowingBinaryExpression(expr); - case SyntaxKind.PrefixUnaryExpression: - return (expr).operator === SyntaxKind.ExclamationToken && isNarrowingExpression((expr).operand); - } - return false; - } - - function isNarrowableReference(expr: Expression): boolean { - return expr.kind === SyntaxKind.Identifier || - expr.kind === SyntaxKind.ThisKeyword || - expr.kind === SyntaxKind.PropertyAccessExpression && isNarrowableReference((expr).expression); - } - - function hasNarrowableArgument(expr: CallExpression) { - if (expr.arguments) { - for (const argument of expr.arguments) { - if (isNarrowableReference(argument)) { - return true; - } - } - } - if (expr.expression.kind === SyntaxKind.PropertyAccessExpression && - isNarrowableReference((expr.expression).expression)) { - return true; - } - return false; - } - - function isNarrowingTypeofOperands(expr1: Expression, expr2: Expression) { - return expr1.kind === SyntaxKind.TypeOfExpression && isNarrowableOperand((expr1).expression) && expr2.kind === SyntaxKind.StringLiteral; - } - - function isNarrowingBinaryExpression(expr: BinaryExpression) { - switch (expr.operatorToken.kind) { - case SyntaxKind.EqualsToken: - return isNarrowableReference(expr.left); - case SyntaxKind.EqualsEqualsToken: - case SyntaxKind.ExclamationEqualsToken: - case SyntaxKind.EqualsEqualsEqualsToken: - case SyntaxKind.ExclamationEqualsEqualsToken: - return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) || - isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right); - case SyntaxKind.InstanceOfKeyword: - return isNarrowableOperand(expr.left); - case SyntaxKind.CommaToken: - return isNarrowingExpression(expr.right); - } - return false; - } - - function isNarrowableOperand(expr: Expression): boolean { - switch (expr.kind) { - case SyntaxKind.ParenthesizedExpression: - return isNarrowableOperand((expr).expression); - case SyntaxKind.BinaryExpression: - switch ((expr).operatorToken.kind) { - case SyntaxKind.EqualsToken: - return isNarrowableOperand((expr).left); - case SyntaxKind.CommaToken: - return isNarrowableOperand((expr).right); - } - } - return isNarrowableReference(expr); - } - - function createBranchLabel(): FlowLabel { - return { - flags: FlowFlags.BranchLabel, - antecedents: undefined - }; - } - - function createLoopLabel(): FlowLabel { - return { - flags: FlowFlags.LoopLabel, - antecedents: undefined - }; - } - - function setFlowNodeReferenced(flow: FlowNode) { - // On first reference we set the Referenced flag, thereafter we set the Shared flag - flow.flags |= flow.flags & FlowFlags.Referenced ? FlowFlags.Shared : FlowFlags.Referenced; - } - - function addAntecedent(label: FlowLabel, antecedent: FlowNode): void { - if (!(antecedent.flags & FlowFlags.Unreachable) && !contains(label.antecedents, antecedent)) { - (label.antecedents || (label.antecedents = [])).push(antecedent); - setFlowNodeReferenced(antecedent); - } - } - - function createFlowCondition(flags: FlowFlags, antecedent: FlowNode, expression: Expression): FlowNode { - if (antecedent.flags & FlowFlags.Unreachable) { - return antecedent; - } - if (!expression) { - return flags & FlowFlags.TrueCondition ? antecedent : unreachableFlow; - } - if (expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition || - expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) { - return unreachableFlow; - } - if (!isNarrowingExpression(expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags, - expression, - antecedent - }; - } - - function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode { - if (!isNarrowingExpression(switchStatement.expression)) { - return antecedent; - } - setFlowNodeReferenced(antecedent); - return { - flags: FlowFlags.SwitchClause, - switchStatement, - clauseStart, - clauseEnd, - antecedent - }; - } - - function createFlowAssignment(antecedent: FlowNode, node: Expression | VariableDeclaration | BindingElement): FlowNode { - setFlowNodeReferenced(antecedent); - return { - flags: FlowFlags.Assignment, - antecedent, - node - }; - } - - function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode { - setFlowNodeReferenced(antecedent); - return { - flags: FlowFlags.ArrayMutation, - antecedent, - node - }; - } - - function finishFlowLabel(flow: FlowLabel): FlowNode { - const antecedents = flow.antecedents; - if (!antecedents) { - return unreachableFlow; - } - if (antecedents.length === 1) { - return antecedents[0]; - } - return flow; - } - - function isStatementCondition(node: Node) { - const parent = node.parent; - switch (parent.kind) { - case SyntaxKind.IfStatement: - case SyntaxKind.WhileStatement: - case SyntaxKind.DoStatement: - return (parent).expression === node; - case SyntaxKind.ForStatement: - case SyntaxKind.ConditionalExpression: - return (parent).condition === node; - } - return false; - } - - function isLogicalExpression(node: Node) { - while (true) { - if (node.kind === SyntaxKind.ParenthesizedExpression) { - node = (node).expression; - } - else if (node.kind === SyntaxKind.PrefixUnaryExpression && (node).operator === SyntaxKind.ExclamationToken) { - node = (node).operand; - } - else { - return node.kind === SyntaxKind.BinaryExpression && ( - (node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken || - (node).operatorToken.kind === SyntaxKind.BarBarToken); - } - } - } - - function isTopLevelLogicalExpression(node: Node): boolean { - while (node.parent.kind === SyntaxKind.ParenthesizedExpression || - node.parent.kind === SyntaxKind.PrefixUnaryExpression && - (node.parent).operator === SyntaxKind.ExclamationToken) { - node = node.parent; - } - return !isStatementCondition(node) && !isLogicalExpression(node.parent); - } - - function bindCondition(node: Expression, trueTarget: FlowLabel, falseTarget: FlowLabel) { - const saveTrueTarget = currentTrueTarget; - const saveFalseTarget = currentFalseTarget; - currentTrueTarget = trueTarget; - currentFalseTarget = falseTarget; - bind(node); - currentTrueTarget = saveTrueTarget; - currentFalseTarget = saveFalseTarget; - if (!node || !isLogicalExpression(node)) { - addAntecedent(trueTarget, createFlowCondition(FlowFlags.TrueCondition, currentFlow, node)); - addAntecedent(falseTarget, createFlowCondition(FlowFlags.FalseCondition, currentFlow, node)); - } - } - - function bindIterativeStatement(node: Statement, breakTarget: FlowLabel, continueTarget: FlowLabel): void { - const saveBreakTarget = currentBreakTarget; - const saveContinueTarget = currentContinueTarget; - currentBreakTarget = breakTarget; - currentContinueTarget = continueTarget; - bind(node); - currentBreakTarget = saveBreakTarget; - currentContinueTarget = saveContinueTarget; - } - - function bindWhileStatement(node: WhileStatement): void { - const preWhileLabel = createLoopLabel(); - const preBodyLabel = createBranchLabel(); - const postWhileLabel = createBranchLabel(); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = preWhileLabel; - bindCondition(node.expression, preBodyLabel, postWhileLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel); - addAntecedent(preWhileLabel, currentFlow); - currentFlow = finishFlowLabel(postWhileLabel); - } - - function bindDoStatement(node: DoStatement): void { - const preDoLabel = createLoopLabel(); - const preConditionLabel = createBranchLabel(); - const postDoLabel = createBranchLabel(); - addAntecedent(preDoLabel, currentFlow); - currentFlow = preDoLabel; - bindIterativeStatement(node.statement, postDoLabel, preConditionLabel); - addAntecedent(preConditionLabel, currentFlow); - currentFlow = finishFlowLabel(preConditionLabel); - bindCondition(node.expression, preDoLabel, postDoLabel); - currentFlow = finishFlowLabel(postDoLabel); - } - - function bindForStatement(node: ForStatement): void { - const preLoopLabel = createLoopLabel(); - const preBodyLabel = createBranchLabel(); - const postLoopLabel = createBranchLabel(); - bind(node.initializer); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bindCondition(node.condition, preBodyLabel, postLoopLabel); - currentFlow = finishFlowLabel(preBodyLabel); - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - bind(node.incrementor); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - - function bindForInOrForOfStatement(node: ForInStatement | ForOfStatement): void { - const preLoopLabel = createLoopLabel(); - const postLoopLabel = createBranchLabel(); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = preLoopLabel; - bind(node.expression); - addAntecedent(postLoopLabel, currentFlow); - bind(node.initializer); - if (node.initializer.kind !== SyntaxKind.VariableDeclarationList) { - bindAssignmentTargetFlow(node.initializer); - } - bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel); - addAntecedent(preLoopLabel, currentFlow); - currentFlow = finishFlowLabel(postLoopLabel); - } - - function bindIfStatement(node: IfStatement): void { - const thenLabel = createBranchLabel(); - const elseLabel = createBranchLabel(); - const postIfLabel = createBranchLabel(); - bindCondition(node.expression, thenLabel, elseLabel); - currentFlow = finishFlowLabel(thenLabel); - bind(node.thenStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(elseLabel); - bind(node.elseStatement); - addAntecedent(postIfLabel, currentFlow); - currentFlow = finishFlowLabel(postIfLabel); - } - - function bindReturnOrThrow(node: ReturnStatement | ThrowStatement): void { - bind(node.expression); - if (node.kind === SyntaxKind.ReturnStatement) { - hasExplicitReturn = true; - if (currentReturnTarget) { - addAntecedent(currentReturnTarget, currentFlow); - } - } - currentFlow = unreachableFlow; - } - - function findActiveLabel(name: string) { - if (activeLabels) { - for (const label of activeLabels) { - if (label.name === name) { - return label; - } - } - } - return undefined; - } - - function bindbreakOrContinueFlow(node: BreakOrContinueStatement, breakTarget: FlowLabel, continueTarget: FlowLabel) { - const flowLabel = node.kind === SyntaxKind.BreakStatement ? breakTarget : continueTarget; - if (flowLabel) { - addAntecedent(flowLabel, currentFlow); - currentFlow = unreachableFlow; - } - } - - function bindBreakOrContinueStatement(node: BreakOrContinueStatement): void { - bind(node.label); - if (node.label) { - const activeLabel = findActiveLabel(node.label.text); - if (activeLabel) { - activeLabel.referenced = true; - bindbreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget); - } - } - else { - bindbreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget); - } - } - - function bindTryStatement(node: TryStatement): void { - const postFinallyLabel = createBranchLabel(); - const preTryFlow = currentFlow; - // TODO: Every statement in try block is potentially an exit point! - bind(node.tryBlock); - addAntecedent(postFinallyLabel, currentFlow); - if (node.catchClause) { - currentFlow = preTryFlow; - bind(node.catchClause); - addAntecedent(postFinallyLabel, currentFlow); - } - if (node.finallyBlock) { - currentFlow = preTryFlow; - bind(node.finallyBlock); - } - // if try statement has finally block and flow after finally block is unreachable - keep it - // otherwise use whatever flow was accumulated at postFinallyLabel - if (!node.finallyBlock || !(currentFlow.flags & FlowFlags.Unreachable)) { - currentFlow = finishFlowLabel(postFinallyLabel); - } - } - - function bindSwitchStatement(node: SwitchStatement): void { - const postSwitchLabel = createBranchLabel(); - bind(node.expression); - const saveBreakTarget = currentBreakTarget; - const savePreSwitchCaseFlow = preSwitchCaseFlow; - currentBreakTarget = postSwitchLabel; - preSwitchCaseFlow = currentFlow; - bind(node.caseBlock); - addAntecedent(postSwitchLabel, currentFlow); - const hasDefault = forEach(node.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause); - // We mark a switch statement as possibly exhaustive if it has no default clause and if all - // case clauses have unreachable end points (e.g. they all return). - node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents; - if (!hasDefault) { - addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0)); - } - currentBreakTarget = saveBreakTarget; - preSwitchCaseFlow = savePreSwitchCaseFlow; - currentFlow = finishFlowLabel(postSwitchLabel); - } - - function bindCaseBlock(node: CaseBlock): void { - const clauses = node.clauses; - let fallthroughFlow = unreachableFlow; - for (let i = 0; i < clauses.length; i++) { - const clauseStart = i; - while (!clauses[i].statements.length && i + 1 < clauses.length) { - bind(clauses[i]); - i++; - } - const preCaseLabel = createBranchLabel(); - addAntecedent(preCaseLabel, createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1)); - addAntecedent(preCaseLabel, fallthroughFlow); - currentFlow = finishFlowLabel(preCaseLabel); - const clause = clauses[i]; - bind(clause); - fallthroughFlow = currentFlow; - if (!(currentFlow.flags & FlowFlags.Unreachable) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch); - } - } - } - - function bindCaseClause(node: CaseClause): void { - const saveCurrentFlow = currentFlow; - currentFlow = preSwitchCaseFlow; - bind(node.expression); - currentFlow = saveCurrentFlow; - forEach(node.statements, bind); - } - - function pushActiveLabel(name: string, breakTarget: FlowLabel, continueTarget: FlowLabel): ActiveLabel { - const activeLabel = { - name, - breakTarget, - continueTarget, - referenced: false - }; - (activeLabels || (activeLabels = [])).push(activeLabel); - return activeLabel; - } - - function popActiveLabel() { - activeLabels.pop(); - } - - function bindLabeledStatement(node: LabeledStatement): void { - const preStatementLabel = createLoopLabel(); - const postStatementLabel = createBranchLabel(); - bind(node.label); - addAntecedent(preStatementLabel, currentFlow); - const activeLabel = pushActiveLabel(node.label.text, postStatementLabel, preStatementLabel); - bind(node.statement); - popActiveLabel(); - if (!activeLabel.referenced && !options.allowUnusedLabels) { - file.bindDiagnostics.push(createDiagnosticForNode(node.label, Diagnostics.Unused_label)); - } - addAntecedent(postStatementLabel, currentFlow); - currentFlow = finishFlowLabel(postStatementLabel); - } - - function bindDestructuringTargetFlow(node: Expression) { - if (node.kind === SyntaxKind.BinaryExpression && (node).operatorToken.kind === SyntaxKind.EqualsToken) { - bindAssignmentTargetFlow((node).left); - } - else { - bindAssignmentTargetFlow(node); - } - } - - function bindAssignmentTargetFlow(node: Expression) { - if (isNarrowableReference(node)) { - currentFlow = createFlowAssignment(currentFlow, node); - } - else if (node.kind === SyntaxKind.ArrayLiteralExpression) { - for (const e of (node).elements) { - if (e.kind === SyntaxKind.SpreadElementExpression) { - bindAssignmentTargetFlow((e).expression); - } - else { - bindDestructuringTargetFlow(e); - } - } - } - else if (node.kind === SyntaxKind.ObjectLiteralExpression) { - for (const p of (node).properties) { - if (p.kind === SyntaxKind.PropertyAssignment) { - bindDestructuringTargetFlow((p).initializer); - } - else if (p.kind === SyntaxKind.ShorthandPropertyAssignment) { - bindAssignmentTargetFlow((p).name); - } - } - } - } - - function bindLogicalExpression(node: BinaryExpression, trueTarget: FlowLabel, falseTarget: FlowLabel) { - const preRightLabel = createBranchLabel(); - if (node.operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { - bindCondition(node.left, preRightLabel, falseTarget); - } - else { - bindCondition(node.left, trueTarget, preRightLabel); - } - currentFlow = finishFlowLabel(preRightLabel); - bind(node.operatorToken); - bindCondition(node.right, trueTarget, falseTarget); - } - - function bindPrefixUnaryExpressionFlow(node: PrefixUnaryExpression) { - if (node.operator === SyntaxKind.ExclamationToken) { - const saveTrueTarget = currentTrueTarget; - currentTrueTarget = currentFalseTarget; - currentFalseTarget = saveTrueTarget; - forEachChild(node, bind); - currentFalseTarget = currentTrueTarget; - currentTrueTarget = saveTrueTarget; - } - else { - forEachChild(node, bind); - if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { - bindAssignmentTargetFlow(node.operand); - } - } - } - - function bindPostfixUnaryExpressionFlow(node: PostfixUnaryExpression) { - forEachChild(node, bind); - if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { - bindAssignmentTargetFlow(node.operand); - } - } - - function bindBinaryExpressionFlow(node: BinaryExpression) { - const operator = node.operatorToken.kind; - if (operator === SyntaxKind.AmpersandAmpersandToken || operator === SyntaxKind.BarBarToken) { - if (isTopLevelLogicalExpression(node)) { - const postExpressionLabel = createBranchLabel(); - bindLogicalExpression(node, postExpressionLabel, postExpressionLabel); - currentFlow = finishFlowLabel(postExpressionLabel); - } - else { - bindLogicalExpression(node, currentTrueTarget, currentFalseTarget); - } - } - else { - forEachChild(node, bind); - if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) { - bindAssignmentTargetFlow(node.left); - if (node.left.kind === SyntaxKind.ElementAccessExpression) { - const elementAccess = node.left; - if (isNarrowableOperand(elementAccess.expression)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - } - } - - function bindDeleteExpressionFlow(node: DeleteExpression) { - forEachChild(node, bind); - if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { - bindAssignmentTargetFlow(node.expression); - } - } - - function bindConditionalExpressionFlow(node: ConditionalExpression) { - const trueLabel = createBranchLabel(); - const falseLabel = createBranchLabel(); - const postExpressionLabel = createBranchLabel(); - bindCondition(node.condition, trueLabel, falseLabel); - currentFlow = finishFlowLabel(trueLabel); - bind(node.whenTrue); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(falseLabel); - bind(node.whenFalse); - addAntecedent(postExpressionLabel, currentFlow); - currentFlow = finishFlowLabel(postExpressionLabel); - } - - function bindInitializedVariableFlow(node: VariableDeclaration | ArrayBindingElement) { - const name = !isOmittedExpression(node) ? node.name : undefined; - if (isBindingPattern(name)) { - for (const child of name.elements) { - bindInitializedVariableFlow(child); - } - } - else { - currentFlow = createFlowAssignment(currentFlow, node); - } - } - - function bindVariableDeclarationFlow(node: VariableDeclaration) { - forEachChild(node, bind); - if (node.initializer || node.parent.parent.kind === SyntaxKind.ForInStatement || node.parent.parent.kind === SyntaxKind.ForOfStatement) { - bindInitializedVariableFlow(node); - } - } - - function bindCallExpressionFlow(node: CallExpression) { - // If the target of the call expression is a function expression or arrow function we have - // an immediately invoked function expression (IIFE). Initialize the flowNode property to - // the current control flow (which includes evaluation of the IIFE arguments). - let expr: Expression = node.expression; - while (expr.kind === SyntaxKind.ParenthesizedExpression) { - expr = (expr).expression; - } - if (expr.kind === SyntaxKind.FunctionExpression || expr.kind === SyntaxKind.ArrowFunction) { - forEach(node.typeArguments, bind); - forEach(node.arguments, bind); - bind(node.expression); - } - else { - forEachChild(node, bind); - } - if (node.expression.kind === SyntaxKind.PropertyAccessExpression) { - const propertyAccess = node.expression; - if (isNarrowableOperand(propertyAccess.expression) && isPushOrUnshiftIdentifier(propertyAccess.name)) { - currentFlow = createFlowArrayMutation(currentFlow, node); - } - } - } - - function getContainerFlags(node: Node): ContainerFlags { - switch (node.kind) { - case SyntaxKind.ClassExpression: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.TypeLiteral: - case SyntaxKind.JSDocTypeLiteral: - case SyntaxKind.JSDocRecordType: - return ContainerFlags.IsContainer; - - case SyntaxKind.InterfaceDeclaration: - return ContainerFlags.IsContainer | ContainerFlags.IsInterface; - - case SyntaxKind.JSDocFunctionType: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.TypeAliasDeclaration: - return ContainerFlags.IsContainer | ContainerFlags.HasLocals; - - case SyntaxKind.SourceFile: - return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals; - - case SyntaxKind.MethodDeclaration: - if (isObjectLiteralOrClassExpressionMethod(node)) { - return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsObjectLiteralOrClassExpressionMethod; - } - case SyntaxKind.Constructor: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike; - - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals | ContainerFlags.IsFunctionLike | ContainerFlags.IsFunctionExpression; - - case SyntaxKind.ModuleBlock: - return ContainerFlags.IsControlFlowContainer; - case SyntaxKind.PropertyDeclaration: - return (node).initializer ? ContainerFlags.IsControlFlowContainer : 0; - - case SyntaxKind.CatchClause: - case SyntaxKind.ForStatement: - case SyntaxKind.ForInStatement: - case SyntaxKind.ForOfStatement: - case SyntaxKind.CaseBlock: - return ContainerFlags.IsBlockScopedContainer; - - case SyntaxKind.Block: - // do not treat blocks directly inside a function as a block-scoped-container. - // Locals that reside in this block should go to the function locals. Otherwise 'x' - // would not appear to be a redeclaration of a block scoped local in the following - // example: - // - // function foo() { - // var x; - // let x; - // } - // - // If we placed 'var x' into the function locals and 'let x' into the locals of - // the block, then there would be no collision. - // - // By not creating a new block-scoped-container here, we ensure that both 'var x' - // and 'let x' go into the Function-container's locals, and we do get a collision - // conflict. - return isFunctionLike(node.parent) ? ContainerFlags.None : ContainerFlags.IsBlockScopedContainer; - } - - return ContainerFlags.None; - } - - function addToContainerChain(next: Node) { - if (lastContainer) { - lastContainer.nextContainer = next; - } - - lastContainer = next; - } - - function declareSymbolAndAddToSymbolTable(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - // Just call this directly so that the return type of this function stays "void". - return declareSymbolAndAddToSymbolTableWorker(node, symbolFlags, symbolExcludes); - } - - function declareSymbolAndAddToSymbolTableWorker(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - switch (container.kind) { - // Modules, source files, and classes need specialized handling for how their - // members are declared (for example, a member of a class will go into a specific - // symbol table depending on if it is static or not). We defer to specialized - // handlers to take care of declaring these child members. - case SyntaxKind.ModuleDeclaration: - return declareModuleMember(node, symbolFlags, symbolExcludes); - - case SyntaxKind.SourceFile: - return declareSourceFileMember(node, symbolFlags, symbolExcludes); - - case SyntaxKind.ClassExpression: - case SyntaxKind.ClassDeclaration: - return declareClassMember(node, symbolFlags, symbolExcludes); - - case SyntaxKind.EnumDeclaration: - return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); - - case SyntaxKind.TypeLiteral: - case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.JSDocRecordType: - case SyntaxKind.JSDocTypeLiteral: - // Interface/Object-types always have their children added to the 'members' of - // their container. They are only accessible through an instance of their - // container, and are never in scope otherwise (even inside the body of the - // object / type / interface declaring them). An exception is type parameters, - // which are in scope without qualification (similar to 'locals'). - return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.Constructor: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - case SyntaxKind.JSDocFunctionType: - case SyntaxKind.TypeAliasDeclaration: - // All the children of these container types are never visible through another - // symbol (i.e. through another symbol's 'exports' or 'members'). Instead, - // they're only accessed 'lexically' (i.e. from code that exists underneath - // their container in the tree. To accomplish this, we simply add their declared - // symbol to the 'locals' of the container. These symbols can then be found as - // the type checker walks up the containers, checking them for matching names. - return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes); - } - } - - function declareClassMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - return hasModifier(node, ModifierFlags.Static) - ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) - : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); - } - - function declareSourceFileMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - return isExternalModule(file) - ? declareModuleMember(node, symbolFlags, symbolExcludes) - : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); - } - - function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean { - const body = node.kind === SyntaxKind.SourceFile ? node : (node).body; - if (body && (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock)) { - for (const stat of (body).statements) { - if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) { - return true; - } - } - } - return false; - } - - function setExportContextFlag(node: ModuleDeclaration | SourceFile) { - // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular - // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (isInAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= NodeFlags.ExportContext; - } - else { - node.flags &= ~NodeFlags.ExportContext; - } - } - - function bindModuleDeclaration(node: ModuleDeclaration) { - setExportContextFlag(node); - if (isAmbientModule(node)) { - if (hasModifier(node, ModifierFlags.Export)) { - errorOnFirstToken(node, Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible); - } - if (isExternalModuleAugmentation(node)) { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); - } - else { - let pattern: Pattern | undefined; - if (node.name.kind === SyntaxKind.StringLiteral) { - const text = (node.name).text; - if (hasZeroOrOneAsteriskCharacter(text)) { - pattern = tryParsePattern(text); - } - else { - errorOnFirstToken(node.name, Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text); - } - } - - const symbol = declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); - - if (pattern) { - (file.patternAmbientModules || (file.patternAmbientModules = [])).push({ pattern, symbol }); - } - } - } - else { - const state = getModuleInstanceState(node); - if (state === ModuleInstanceState.NonInstantiated) { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); - } - else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); - if (node.symbol.flags & (SymbolFlags.Function | SymbolFlags.Class | SymbolFlags.RegularEnum)) { - // if module was already merged with some function, class or non-const enum - // treat is a non-const-enum-only - node.symbol.constEnumOnlyModule = false; - } - else { - const currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; - if (node.symbol.constEnumOnlyModule === undefined) { - // non-merged case - use the current state - node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; - } - else { - // merged case: module is const enum only if all its pieces are non-instantiated or const enum - node.symbol.constEnumOnlyModule = node.symbol.constEnumOnlyModule && currentModuleIsConstEnumOnly; - } - } - } - } - } - - function bindFunctionOrConstructorType(node: SignatureDeclaration): void { - // For a given function symbol "<...>(...) => T" we want to generate a symbol identical - // to the one we would get for: { <...>(...): T } - // - // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable - // from an actual type literal symbol you would have gotten had you used the long form. - const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); - addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); - - const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); - addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); - typeLiteralSymbol.members = createMap(); - typeLiteralSymbol.members[symbol.name] = symbol; - } - - function bindObjectLiteralExpression(node: ObjectLiteralExpression) { - const enum ElementKind { - Property = 1, - Accessor = 2 - } - - if (inStrictMode) { - const seen = createMap(); - - for (const prop of node.properties) { - if (prop.name.kind !== SyntaxKind.Identifier) { - continue; - } - - const identifier = prop.name; - - // ECMA-262 11.1.5 Object Initializer - // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true - // a.This production is contained in strict code and IsDataDescriptor(previous) is true and - // IsDataDescriptor(propId.descriptor) is true. - // b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true. - // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. - // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true - // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - const currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration - ? ElementKind.Property - : ElementKind.Accessor; - - const existingKind = seen[identifier.text]; - if (!existingKind) { - seen[identifier.text] = currentKind; - continue; - } - - if (currentKind === ElementKind.Property && existingKind === ElementKind.Property) { - const span = getErrorSpanForNode(file, identifier); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, - Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); - } - } - } - - return bindAnonymousDeclaration(node, SymbolFlags.ObjectLiteral, "__object"); - } - - function bindAnonymousDeclaration(node: Declaration, symbolFlags: SymbolFlags, name: string) { - const symbol = createSymbol(symbolFlags, name); - addDeclarationToSymbol(symbol, node, symbolFlags); - } - - function bindBlockScopedDeclaration(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - switch (blockScopeContainer.kind) { - case SyntaxKind.ModuleDeclaration: - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - case SyntaxKind.SourceFile: - if (isExternalModule(container)) { - declareModuleMember(node, symbolFlags, symbolExcludes); - break; - } - // fall through. - default: - if (!blockScopeContainer.locals) { - blockScopeContainer.locals = createMap(); - addToContainerChain(blockScopeContainer); - } - declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); - } - } - - function bindBlockScopedVariableDeclaration(node: Declaration) { - bindBlockScopedDeclaration(node, SymbolFlags.BlockScopedVariable, SymbolFlags.BlockScopedVariableExcludes); - } - - // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized - // check for reserved words used as identifiers in strict mode code. - function checkStrictModeIdentifier(node: Identifier) { - if (inStrictMode && - node.originalKeywordKind >= SyntaxKind.FirstFutureReservedWord && - node.originalKeywordKind <= SyntaxKind.LastFutureReservedWord && - !isIdentifierName(node) && - !isInAmbientContext(node)) { - - // Report error only if there are no parse errors in file - if (!file.parseDiagnostics.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, - getStrictModeIdentifierMessage(node), declarationNameToString(node))); - } - } - } - - function getStrictModeIdentifierMessage(node: Node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (getContainingClass(node)) { - return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode; - } - - if (file.externalModuleIndicator) { - return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode; - } - - return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode; - } - - function checkStrictModeBinaryExpression(node: BinaryExpression) { - if (inStrictMode && isLeftHandSideExpression(node.left) && isAssignmentOperator(node.operatorToken.kind)) { - // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) - checkStrictModeEvalOrArguments(node, node.left); - } - } - - function checkStrictModeCatchClause(node: CatchClause) { - // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the - // Catch production is eval or arguments - if (inStrictMode && node.variableDeclaration) { - checkStrictModeEvalOrArguments(node, node.variableDeclaration.name); - } - } - - function checkStrictModeDeleteExpression(node: DeleteExpression) { - // Grammar checking - if (inStrictMode && node.expression.kind === SyntaxKind.Identifier) { - // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its - // UnaryExpression is a direct reference to a variable, function argument, or function name - const span = getErrorSpanForNode(file, node.expression); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); - } - } - - function isEvalOrArgumentsIdentifier(node: Node): boolean { - return node.kind === SyntaxKind.Identifier && - ((node).text === "eval" || (node).text === "arguments"); - } - - function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { - if (name && name.kind === SyntaxKind.Identifier) { - const identifier = name; - if (isEvalOrArgumentsIdentifier(identifier)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - const span = getErrorSpanForNode(file, name); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, - getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); - } - } - } - - function getStrictModeEvalOrArgumentsMessage(node: Node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (getContainingClass(node)) { - return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode; - } - - if (file.externalModuleIndicator) { - return Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode; - } - - return Diagnostics.Invalid_use_of_0_in_strict_mode; - } - - function checkStrictModeFunctionName(node: FunctionLikeDeclaration) { - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)) - checkStrictModeEvalOrArguments(node, node.name); - } - } - - function getStrictModeBlockScopeFunctionDeclarationMessage(node: Node) { - // Provide specialized messages to help the user understand why we think they're in - // strict mode. - if (getContainingClass(node)) { - return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Class_definitions_are_automatically_in_strict_mode; - } - - if (file.externalModuleIndicator) { - return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode; - } - - return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5; - } - - function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) { - if (languageVersion < ScriptTarget.ES2015) { - // Report error if function is not top level function declaration - if (blockScopeContainer.kind !== SyntaxKind.SourceFile && - blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration && - !isFunctionLike(blockScopeContainer)) { - // We check first if the name is inside class declaration or class expression; if so give explicit message - // otherwise report generic error message. - const errorSpan = getErrorSpanForNode(file, node); - file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length, - getStrictModeBlockScopeFunctionDeclarationMessage(node))); - } - } - } - - function checkStrictModeNumericLiteral(node: NumericLiteral) { - if (inStrictMode && node.isOctalLiteral) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); - } - } - - function checkStrictModePostfixUnaryExpression(node: PostfixUnaryExpression) { - // Grammar checking - // The identifier eval or arguments may not appear as the LeftHandSideExpression of an - // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression - // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator. - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - - function checkStrictModePrefixUnaryExpression(node: PrefixUnaryExpression) { - // Grammar checking - if (inStrictMode) { - if (node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken) { - checkStrictModeEvalOrArguments(node, node.operand); - } - } - } - - function checkStrictModeWithStatement(node: WithStatement) { - // Grammar checking for withStatement - if (inStrictMode) { - errorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); - } - } - - function errorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { - const span = getSpanOfTokenAtPosition(file, node.pos); - file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); - } - - function getDestructuringParameterName(node: Declaration) { - return "__" + indexOf((node.parent).parameters, node); - } - - function bind(node: Node): void { - if (!node) { - return; - } - node.parent = parent; - const saveInStrictMode = inStrictMode; - // First we bind declaration nodes to a symbol if possible. We'll both create a symbol - // and then potentially add the symbol to an appropriate symbol table. Possible - // destination symbol tables are: - // - // 1) The 'exports' table of the current container's symbol. - // 2) The 'members' table of the current container's symbol. - // 3) The 'locals' table of the current container. - // - // However, not all symbols will end up in any of these tables. 'Anonymous' symbols - // (like TypeLiterals for example) will not be put in any table. - bindWorker(node); - // Then we recurse into the children of the node to bind them as well. For certain - // symbols we do specialized work when we recurse. For example, we'll keep track of - // the current 'container' node when it changes. This helps us know which symbol table - // a local should go into for example. Since terminal nodes are known not to have - // children, as an optimization we don't process those. - if (node.kind > SyntaxKind.LastToken) { - const saveParent = parent; - parent = node; - const containerFlags = getContainerFlags(node); - if (containerFlags === ContainerFlags.None) { - bindChildren(node); - } - else { - bindContainer(node, containerFlags); - } - parent = saveParent; - } - else if (!skipTransformFlagAggregation && (node.transformFlags & TransformFlags.HasComputedFlags) === 0) { - subtreeTransformFlags |= computeTransformFlagsForNode(node, 0); - } - inStrictMode = saveInStrictMode; - } - - function updateStrictModeStatementList(statements: NodeArray) { - if (!inStrictMode) { - for (const statement of statements) { - if (!isPrologueDirective(statement)) { - return; - } - - if (isUseStrictPrologueDirective(statement)) { - inStrictMode = true; - return; - } - } - } - } - - /// Should be called only on prologue directives (isPrologueDirective(node) should be true) - function isUseStrictPrologueDirective(node: ExpressionStatement): boolean { - const nodeText = getTextOfNodeFromSourceText(file.text, node.expression); - - // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the - // string to contain unicode escapes (as per ES5). - return nodeText === '"use strict"' || nodeText === "'use strict'"; - } - - function bindWorker(node: Node) { - switch (node.kind) { - /* Strict mode checks */ - case SyntaxKind.Identifier: - case SyntaxKind.ThisKeyword: - if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) { - node.flowNode = currentFlow; - } - return checkStrictModeIdentifier(node); - case SyntaxKind.PropertyAccessExpression: - if (currentFlow && isNarrowableReference(node)) { - node.flowNode = currentFlow; - } - break; - case SyntaxKind.BinaryExpression: - if (isInJavaScriptFile(node)) { - const specialKind = getSpecialPropertyAssignmentKind(node); - switch (specialKind) { - case SpecialPropertyAssignmentKind.ExportsProperty: - bindExportsPropertyAssignment(node); - break; - case SpecialPropertyAssignmentKind.ModuleExports: - bindModuleExportsAssignment(node); - break; - case SpecialPropertyAssignmentKind.PrototypeProperty: - bindPrototypePropertyAssignment(node); - break; - case SpecialPropertyAssignmentKind.ThisProperty: - bindThisPropertyAssignment(node); - break; - case SpecialPropertyAssignmentKind.None: - // Nothing to do - break; - default: - Debug.fail("Unknown special property assignment kind"); - } - } - return checkStrictModeBinaryExpression(node); - case SyntaxKind.CatchClause: - return checkStrictModeCatchClause(node); - case SyntaxKind.DeleteExpression: - return checkStrictModeDeleteExpression(node); - case SyntaxKind.NumericLiteral: - return checkStrictModeNumericLiteral(node); - case SyntaxKind.PostfixUnaryExpression: - return checkStrictModePostfixUnaryExpression(node); - case SyntaxKind.PrefixUnaryExpression: - return checkStrictModePrefixUnaryExpression(node); - case SyntaxKind.WithStatement: - return checkStrictModeWithStatement(node); - case SyntaxKind.ThisType: - seenThisKeyword = true; - return; - case SyntaxKind.TypePredicate: - return checkTypePredicate(node as TypePredicateNode); - case SyntaxKind.TypeParameter: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes); - case SyntaxKind.Parameter: - return bindParameter(node); - case SyntaxKind.VariableDeclaration: - case SyntaxKind.BindingElement: - return bindVariableDeclarationOrBindingElement(node); - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - case SyntaxKind.JSDocRecordMember: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); - case SyntaxKind.JSDocPropertyTag: - return bindJSDocProperty(node); - case SyntaxKind.PropertyAssignment: - case SyntaxKind.ShorthandPropertyAssignment: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); - case SyntaxKind.EnumMember: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes); - - case SyntaxKind.JsxSpreadAttribute: - emitFlags |= NodeFlags.HasJsxSpreadAttributes; - return; - - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Signature, SymbolFlags.None); - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - // If this is an ObjectLiteralExpression method, then it sits in the same space - // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes - // so that it will conflict with any other object literal members with the same - // name. - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.Method | ((node).questionToken ? SymbolFlags.Optional : SymbolFlags.None), - isObjectLiteralMethod(node) ? SymbolFlags.PropertyExcludes : SymbolFlags.MethodExcludes); - case SyntaxKind.FunctionDeclaration: - return bindFunctionDeclaration(node); - case SyntaxKind.Constructor: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Constructor, /*symbolExcludes:*/ SymbolFlags.None); - case SyntaxKind.GetAccessor: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.GetAccessor, SymbolFlags.GetAccessorExcludes); - case SyntaxKind.SetAccessor: - return bindPropertyOrMethodOrAccessor(node, SymbolFlags.SetAccessor, SymbolFlags.SetAccessorExcludes); - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - case SyntaxKind.JSDocFunctionType: - return bindFunctionOrConstructorType(node); - case SyntaxKind.TypeLiteral: - case SyntaxKind.JSDocTypeLiteral: - case SyntaxKind.JSDocRecordType: - return bindAnonymousDeclaration(node, SymbolFlags.TypeLiteral, "__type"); - case SyntaxKind.ObjectLiteralExpression: - return bindObjectLiteralExpression(node); - case SyntaxKind.FunctionExpression: - case SyntaxKind.ArrowFunction: - return bindFunctionExpression(node); - - case SyntaxKind.CallExpression: - if (isInJavaScriptFile(node)) { - bindCallExpression(node); - } - break; - - // Members of classes, interfaces, and modules - case SyntaxKind.ClassExpression: - case SyntaxKind.ClassDeclaration: - // All classes are automatically in strict mode in ES6. - inStrictMode = true; - return bindClassLikeDeclaration(node); - case SyntaxKind.InterfaceDeclaration: - return bindBlockScopedDeclaration(node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes); - case SyntaxKind.JSDocTypedefTag: - case SyntaxKind.TypeAliasDeclaration: - return bindBlockScopedDeclaration(node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes); - case SyntaxKind.EnumDeclaration: - return bindEnumDeclaration(node); - case SyntaxKind.ModuleDeclaration: - return bindModuleDeclaration(node); - - // Imports and exports - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.NamespaceImport: - case SyntaxKind.ImportSpecifier: - case SyntaxKind.ExportSpecifier: - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); - case SyntaxKind.NamespaceExportDeclaration: - return bindNamespaceExportDeclaration(node); - case SyntaxKind.ImportClause: - return bindImportClause(node); - case SyntaxKind.ExportDeclaration: - return bindExportDeclaration(node); - case SyntaxKind.ExportAssignment: - return bindExportAssignment(node); - case SyntaxKind.SourceFile: - updateStrictModeStatementList((node).statements); - return bindSourceFileIfExternalModule(); - case SyntaxKind.Block: - if (!isFunctionLike(node.parent)) { - return; - } - // Fall through - case SyntaxKind.ModuleBlock: - return updateStrictModeStatementList((node).statements); - } - } - - function checkTypePredicate(node: TypePredicateNode) { - const { parameterName, type } = node; - if (parameterName && parameterName.kind === SyntaxKind.Identifier) { - checkStrictModeIdentifier(parameterName as Identifier); - } - if (parameterName && parameterName.kind === SyntaxKind.ThisType) { - seenThisKeyword = true; - } - bind(type); - } - - function bindSourceFileIfExternalModule() { - setExportContextFlag(file); - if (isExternalModule(file)) { - bindSourceFileAsExternalModule(); - } - } - - function bindSourceFileAsExternalModule() { - bindAnonymousDeclaration(file, SymbolFlags.ValueModule, `"${removeFileExtension(file.fileName) }"`); - } - - function bindExportAssignment(node: ExportAssignment | BinaryExpression) { - if (!container.symbol || !container.symbol.exports) { - // Export assignment in some sort of block construct - bindAnonymousDeclaration(node, SymbolFlags.Alias, getDeclarationName(node)); - } - else { - // An export default clause with an expression exports a value - // We want to exclude both class and function here, this is necessary to issue an error when there are both - // default export-assignment and default export function and class declaration. - const flags = node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) - // An export default clause with an EntityNameExpression exports all meanings of that identifier - ? SymbolFlags.Alias - // An export default clause with any other expression exports a value - : SymbolFlags.Property; - declareSymbol(container.symbol.exports, container.symbol, node, flags, SymbolFlags.Property | SymbolFlags.AliasExcludes | SymbolFlags.Class | SymbolFlags.Function); - } - } - - function bindNamespaceExportDeclaration(node: NamespaceExportDeclaration) { - if (node.modifiers && node.modifiers.length) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Modifiers_cannot_appear_here)); - } - - if (node.parent.kind !== SyntaxKind.SourceFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_at_top_level)); - return; - } - else { - const parent = node.parent as SourceFile; - - if (!isExternalModule(parent)) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_module_files)); - return; - } - - if (!parent.isDeclarationFile) { - file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); - return; - } - } - - file.symbol.globalExports = file.symbol.globalExports || createMap(); - declareSymbol(file.symbol.globalExports, file.symbol, node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); - } - - function bindExportDeclaration(node: ExportDeclaration) { - if (!container.symbol || !container.symbol.exports) { - // Export * in some sort of block construct - bindAnonymousDeclaration(node, SymbolFlags.ExportStar, getDeclarationName(node)); - } - else if (!node.exportClause) { - // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, SymbolFlags.ExportStar, SymbolFlags.None); - } - } - - function bindImportClause(node: ImportClause) { - if (node.name) { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.Alias, SymbolFlags.AliasExcludes); - } - } - - function setCommonJsModuleIndicator(node: Node) { - if (!file.commonJsModuleIndicator) { - file.commonJsModuleIndicator = node; - bindSourceFileAsExternalModule(); - } - } - - function bindExportsPropertyAssignment(node: BinaryExpression) { - // When we create a property via 'exports.foo = bar', the 'exports.foo' property access - // expression is the declaration - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node.left, SymbolFlags.Property | SymbolFlags.Export, SymbolFlags.None); - } - - function bindModuleExportsAssignment(node: BinaryExpression) { - // 'module.exports = expr' assignment - setCommonJsModuleIndicator(node); - declareSymbol(file.symbol.exports, file.symbol, node, SymbolFlags.Property | SymbolFlags.Export | SymbolFlags.ValueModule, SymbolFlags.None); - } - - function bindThisPropertyAssignment(node: BinaryExpression) { - Debug.assert(isInJavaScriptFile(node)); - // Declare a 'member' if the container is an ES5 class or ES6 constructor - if (container.kind === SyntaxKind.FunctionDeclaration || container.kind === SyntaxKind.FunctionExpression) { - container.symbol.members = container.symbol.members || createMap(); - // It's acceptable for multiple 'this' assignments of the same identifier to occur - declareSymbol(container.symbol.members, container.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes & ~SymbolFlags.Property); - } - else if (container.kind === SyntaxKind.Constructor) { - // this.foo assignment in a JavaScript class - // Bind this property to the containing class - const saveContainer = container; - container = container.parent; - const symbol = bindPropertyOrMethodOrAccessor(node, SymbolFlags.Property, SymbolFlags.None); - if (symbol) { - // constructor-declared symbols can be overwritten by subsequent method declarations - (symbol as Symbol).isReplaceableByMethod = true; - } - container = saveContainer; - } - } - - function bindPrototypePropertyAssignment(node: BinaryExpression) { - // We saw a node of the form 'x.prototype.y = z'. Declare a 'member' y on x if x was a function. - - // Look up the function in the local scope, since prototype assignments should - // follow the function declaration - const leftSideOfAssignment = node.left as PropertyAccessExpression; - const classPrototype = leftSideOfAssignment.expression as PropertyAccessExpression; - const constructorFunction = classPrototype.expression as Identifier; - - // Fix up parent pointers since we're going to use these nodes before we bind into them - leftSideOfAssignment.parent = node; - constructorFunction.parent = classPrototype; - classPrototype.parent = leftSideOfAssignment; - - const funcSymbol = container.locals[constructorFunction.text]; - if (!funcSymbol || !(funcSymbol.flags & SymbolFlags.Function || isDeclarationOfFunctionExpression(funcSymbol))) { - return; - } - - // Set up the members collection if it doesn't exist already - if (!funcSymbol.members) { - funcSymbol.members = createMap(); - } - - // Declare the method/property - declareSymbol(funcSymbol.members, funcSymbol, leftSideOfAssignment, SymbolFlags.Property, SymbolFlags.PropertyExcludes); - } - - function bindCallExpression(node: CallExpression) { - // We're only inspecting call expressions to detect CommonJS modules, so we can skip - // this check if we've already seen the module indicator - if (!file.commonJsModuleIndicator && isRequireCall(node, /*checkArgumentIsStringLiteral*/false)) { - setCommonJsModuleIndicator(node); - } - } - - function bindClassLikeDeclaration(node: ClassLikeDeclaration) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (getClassExtendsHeritageClauseElement(node) !== undefined) { - emitFlags |= NodeFlags.HasClassExtends; - } - if (nodeIsDecorated(node)) { - emitFlags |= NodeFlags.HasDecorators; - } - } - - if (node.kind === SyntaxKind.ClassDeclaration) { - bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); - } - else { - const bindingName = node.name ? node.name.text : "__class"; - bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName); - // Add name of class expression into the map for semantic classifier - if (node.name) { - classifiableNames[node.name.text] = node.name.text; - } - } - - const symbol = node.symbol; - - // TypeScript 1.0 spec (April 2014): 8.4 - // Every class automatically contains a static property member named 'prototype', the - // type of which is an instantiation of the class type with type Any supplied as a type - // argument for each type parameter. It is an error to explicitly declare a static - // property member with the name 'prototype'. - // - // Note: we check for this here because this class may be merging into a module. The - // module might have an exported variable called 'prototype'. We can't allow that as - // that would clash with the built-in 'prototype' for the class. - const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); - if (symbol.exports[prototypeSymbol.name]) { - if (node.name) { - node.name.parent = node; - } - file.bindDiagnostics.push(createDiagnosticForNode(symbol.exports[prototypeSymbol.name].declarations[0], - Diagnostics.Duplicate_identifier_0, prototypeSymbol.name)); - } - symbol.exports[prototypeSymbol.name] = prototypeSymbol; - prototypeSymbol.parent = symbol; - } - - function bindEnumDeclaration(node: EnumDeclaration) { - return isConst(node) - ? bindBlockScopedDeclaration(node, SymbolFlags.ConstEnum, SymbolFlags.ConstEnumExcludes) - : bindBlockScopedDeclaration(node, SymbolFlags.RegularEnum, SymbolFlags.RegularEnumExcludes); - } - - function bindVariableDeclarationOrBindingElement(node: VariableDeclaration | BindingElement) { - if (inStrictMode) { - checkStrictModeEvalOrArguments(node, node.name); - } - - if (!isBindingPattern(node.name)) { - if (isBlockOrCatchScoped(node)) { - bindBlockScopedVariableDeclaration(node); - } - else if (isParameterDeclaration(node)) { - // It is safe to walk up parent chain to find whether the node is a destructing parameter declaration - // because its parent chain has already been set up, since parents are set before descending into children. - // - // If node is a binding element in parameter declaration, we need to use ParameterExcludes. - // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration - // For example: - // function foo([a,a]) {} // Duplicate Identifier error - // function bar(a,a) {} // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter - // // which correctly set excluded symbols - declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); - } - else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes); - } - } - } - - function bindParameter(node: ParameterDeclaration) { - if (!isDeclarationFile(file) && - !isInAmbientContext(node) && - nodeIsDecorated(node)) { - emitFlags |= (NodeFlags.HasDecorators | NodeFlags.HasParamDecorators); - } - - if (inStrictMode) { - // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a - // strict mode FunctionLikeDeclaration or FunctionExpression(13.1) - checkStrictModeEvalOrArguments(node, node.name); - } - - if (isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, SymbolFlags.FunctionScopedVariable, getDestructuringParameterName(node)); - } - else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.ParameterExcludes); - } - - // If this is a property-parameter, then also declare the property symbol into the - // containing class. - if (isParameterPropertyDeclaration(node)) { - const classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property | (node.questionToken ? SymbolFlags.Optional : SymbolFlags.None), SymbolFlags.PropertyExcludes); - } - } - - function bindFunctionDeclaration(node: FunctionDeclaration) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (isAsyncFunctionLike(node)) { - emitFlags |= NodeFlags.HasAsyncFunctions; - } - } - - checkStrictModeFunctionName(node); - if (inStrictMode) { - checkStrictModeFunctionDeclaration(node); - bindBlockScopedDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); - } - else { - declareSymbolAndAddToSymbolTable(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes); - } - } - - function bindFunctionExpression(node: FunctionExpression) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (isAsyncFunctionLike(node)) { - emitFlags |= NodeFlags.HasAsyncFunctions; - } - } - if (currentFlow) { - node.flowNode = currentFlow; - } - checkStrictModeFunctionName(node); - const bindingName = node.name ? node.name.text : "__function"; - return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); - } - - function bindPropertyOrMethodOrAccessor(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags) { - if (!isDeclarationFile(file) && !isInAmbientContext(node)) { - if (isAsyncFunctionLike(node)) { - emitFlags |= NodeFlags.HasAsyncFunctions; - } - if (nodeIsDecorated(node)) { - emitFlags |= NodeFlags.HasDecorators; - } - } - - if (currentFlow && isObjectLiteralOrClassExpressionMethod(node)) { - node.flowNode = currentFlow; - } - - return hasDynamicName(node) - ? bindAnonymousDeclaration(node, symbolFlags, "__computed") - : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); - } - - function bindJSDocProperty(node: JSDocPropertyTag) { - return declareSymbolAndAddToSymbolTable(node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); - } - - // reachability checks - - function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean { - const instanceState = getModuleInstanceState(node); - return instanceState === ModuleInstanceState.Instantiated || (instanceState === ModuleInstanceState.ConstEnumOnly && options.preserveConstEnums); - } - - function checkUnreachable(node: Node): boolean { - if (!(currentFlow.flags & FlowFlags.Unreachable)) { - return false; - } - if (currentFlow === unreachableFlow) { - const reportError = - // report error on all statements except empty ones - (isStatementButNotDeclaration(node) && node.kind !== SyntaxKind.EmptyStatement) || - // 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 - (node.kind === SyntaxKind.EnumDeclaration && (!isConstEnumDeclaration(node) || options.preserveConstEnums)); - - if (reportError) { - currentFlow = reportedUnreachableFlow; - - // unreachable code is reported if - // - user has explicitly asked about it AND - // - statement is in not ambient context (statements in ambient context is already an error - // so we should not report extras) AND - // - node is not variable statement OR - // - node is block scoped variable statement OR - // - node is not block scoped variable statement and at least one variable declaration has initializer - // Rationale: we don't want to report errors on non-initialized var's since they are hoisted - // On the other side we do want to report errors on non-initialized 'lets' because of TDZ - const reportUnreachableCode = - !options.allowUnreachableCode && - !isInAmbientContext(node) && - ( - node.kind !== SyntaxKind.VariableStatement || - getCombinedNodeFlags((node).declarationList) & NodeFlags.BlockScoped || - forEach((node).declarationList.declarations, d => d.initializer) - ); - - if (reportUnreachableCode) { - errorOnFirstToken(node, Diagnostics.Unreachable_code_detected); - } - } - } - return true; - } - } - - /** - * Computes the transform flags for a node, given the transform flags of its subtree - * - * @param node The node to analyze - * @param subtreeFlags Transform flags computed for this node's subtree - */ - export function computeTransformFlagsForNode(node: Node, subtreeFlags: TransformFlags): TransformFlags { - const kind = node.kind; - switch (kind) { - case SyntaxKind.CallExpression: - return computeCallExpression(node, subtreeFlags); - - case SyntaxKind.NewExpression: - return computeNewExpression(node, subtreeFlags); - - case SyntaxKind.ModuleDeclaration: - return computeModuleDeclaration(node, subtreeFlags); - - case SyntaxKind.ParenthesizedExpression: - return computeParenthesizedExpression(node, subtreeFlags); - - case SyntaxKind.BinaryExpression: - return computeBinaryExpression(node, subtreeFlags); - - case SyntaxKind.ExpressionStatement: - return computeExpressionStatement(node, subtreeFlags); - - case SyntaxKind.Parameter: - return computeParameter(node, subtreeFlags); - - case SyntaxKind.ArrowFunction: - return computeArrowFunction(node, subtreeFlags); - - case SyntaxKind.FunctionExpression: - return computeFunctionExpression(node, subtreeFlags); - - case SyntaxKind.FunctionDeclaration: - return computeFunctionDeclaration(node, subtreeFlags); - - case SyntaxKind.VariableDeclaration: - return computeVariableDeclaration(node, subtreeFlags); - - case SyntaxKind.VariableDeclarationList: - return computeVariableDeclarationList(node, subtreeFlags); - - case SyntaxKind.VariableStatement: - return computeVariableStatement(node, subtreeFlags); - - case SyntaxKind.LabeledStatement: - return computeLabeledStatement(node, subtreeFlags); - - case SyntaxKind.ClassDeclaration: - return computeClassDeclaration(node, subtreeFlags); - - case SyntaxKind.ClassExpression: - return computeClassExpression(node, subtreeFlags); - - case SyntaxKind.HeritageClause: - return computeHeritageClause(node, subtreeFlags); - - case SyntaxKind.ExpressionWithTypeArguments: - return computeExpressionWithTypeArguments(node, subtreeFlags); - - case SyntaxKind.Constructor: - return computeConstructor(node, subtreeFlags); - - case SyntaxKind.PropertyDeclaration: - return computePropertyDeclaration(node, subtreeFlags); - - case SyntaxKind.MethodDeclaration: - return computeMethod(node, subtreeFlags); - - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return computeAccessor(node, subtreeFlags); - - case SyntaxKind.ImportEqualsDeclaration: - return computeImportEquals(node, subtreeFlags); - - case SyntaxKind.PropertyAccessExpression: - return computePropertyAccess(node, subtreeFlags); - - default: - return computeOther(node, kind, subtreeFlags); - } - } - - function computeCallExpression(node: CallExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const expression = node.expression; - const expressionKind = expression.kind; - - if (node.typeArguments) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression - || isSuperOrSuperProperty(expression, expressionKind)) { - // If the this node contains a SpreadElementExpression, or is a super call, then it is an ES6 - // node. - transformFlags |= TransformFlags.AssertES2015; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; - } - - function isSuperOrSuperProperty(node: Node, kind: SyntaxKind) { - switch (kind) { - case SyntaxKind.SuperKeyword: - return true; - - case SyntaxKind.PropertyAccessExpression: - case SyntaxKind.ElementAccessExpression: - const expression = (node).expression; - const expressionKind = expression.kind; - return expressionKind === SyntaxKind.SuperKeyword; - } - - return false; - } - - function computeNewExpression(node: NewExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - if (node.typeArguments) { - transformFlags |= TransformFlags.AssertTypeScript; - } - if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { - // If the this node contains a SpreadElementExpression then it is an ES6 - // node. - transformFlags |= TransformFlags.AssertES6; - } - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ArrayLiteralOrCallOrNewExcludes; - } - - - function computeBinaryExpression(node: BinaryExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const operatorTokenKind = node.operatorToken.kind; - const leftKind = node.left.kind; - - if (operatorTokenKind === SyntaxKind.EqualsToken - && (leftKind === SyntaxKind.ObjectLiteralExpression - || leftKind === SyntaxKind.ArrayLiteralExpression)) { - // Destructuring assignments are ES6 syntax. - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.DestructuringAssignment; - } - else if (operatorTokenKind === SyntaxKind.AsteriskAsteriskToken - || operatorTokenKind === SyntaxKind.AsteriskAsteriskEqualsToken) { - // Exponentiation is ES2016 syntax. - transformFlags |= TransformFlags.AssertES2016; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeParameter(node: ParameterDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const modifierFlags = getModifierFlags(node); - const name = node.name; - const initializer = node.initializer; - const dotDotDotToken = node.dotDotDotToken; - - // The '?' token, type annotations, decorators, and 'this' parameters are TypeSCript - // syntax. - if (node.questionToken - || node.type - || subtreeFlags & TransformFlags.ContainsDecorators - || isThisIdentifier(name)) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - // If a parameter has an accessibility modifier, then it is TypeScript syntax. - if (modifierFlags & ModifierFlags.ParameterPropertyModifier) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsParameterPropertyAssignments; - } - - // If a parameter has an initializer, a binding pattern or a dotDotDot token, then - // it is ES6 syntax and its container must emit default value assignments or parameter destructuring downlevel. - if (subtreeFlags & TransformFlags.ContainsBindingPattern || initializer || dotDotDotToken) { - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsDefaultValueAssignments; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ParameterExcludes; - } - - function computeParenthesizedExpression(node: ParenthesizedExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const expression = node.expression; - const expressionKind = expression.kind; - const expressionTransformFlags = expression.transformFlags; - - // If the node is synthesized, it means the emitter put the parentheses there, - // not the user. If we didn't want them, the emitter would not have put them - // there. - if (expressionKind === SyntaxKind.AsExpression - || expressionKind === SyntaxKind.TypeAssertionExpression) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - // If the expression of a ParenthesizedExpression is a destructuring assignment, - // then the ParenthesizedExpression is a destructuring assignment. - if (expressionTransformFlags & TransformFlags.DestructuringAssignment) { - transformFlags |= TransformFlags.DestructuringAssignment; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeClassDeclaration(node: ClassDeclaration, subtreeFlags: TransformFlags) { - let transformFlags: TransformFlags; - const modifierFlags = getModifierFlags(node); - - if (modifierFlags & ModifierFlags.Ambient) { - // An ambient declaration is TypeScript syntax. - transformFlags = TransformFlags.AssertTypeScript; - } - else { - // A ClassDeclaration is ES6 syntax. - transformFlags = subtreeFlags | TransformFlags.AssertES2015; - - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - // An exported declaration may be TypeScript syntax. - if ((subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask) - || (modifierFlags & ModifierFlags.Export) - || node.typeParameters) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= TransformFlags.ContainsLexicalThis; - } - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ClassExcludes; - } - - function computeClassExpression(node: ClassExpression, subtreeFlags: TransformFlags) { - // A ClassExpression is ES6 syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - - // A class with a parameter property assignment, property initializer, or decorator is - // TypeScript syntax. - if (subtreeFlags & TransformFlags.TypeScriptClassSyntaxMask - || node.typeParameters) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= TransformFlags.ContainsLexicalThis; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ClassExcludes; - } - - function computeHeritageClause(node: HeritageClause, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - - switch (node.token) { - case SyntaxKind.ExtendsKeyword: - // An `extends` HeritageClause is ES6 syntax. - transformFlags |= TransformFlags.AssertES2015; - break; - - case SyntaxKind.ImplementsKeyword: - // An `implements` HeritageClause is TypeScript syntax. - transformFlags |= TransformFlags.AssertTypeScript; - break; - - default: - Debug.fail("Unexpected token for heritage clause"); - break; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) { - // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the - // extends clause of a class. - let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - - // If an ExpressionWithTypeArguments contains type arguments, then it - // is TypeScript syntax. - if (node.typeArguments) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeConstructor(node: ConstructorDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - - // TypeScript-specific modifiers and overloads are TypeScript syntax - if (hasModifier(node, ModifierFlags.TypeScriptModifier) - || !node.body) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ConstructorExcludes; - } - - function computeMethod(node: MethodDeclaration, subtreeFlags: TransformFlags) { - // A MethodDeclaration is ES6 syntax. -<<<<<<< HEAD - let transformFlags = subtreeFlags | TransformFlags.AssertES6; - - // Decorators, TypeScript-specific modifiers, type parameters, type annotations, and - // overloads are TypeScript syntax. - if (node.decorators - || hasModifier(node, ModifierFlags.TypeScriptModifier) - || node.typeParameters - || node.type - || !node.body) { -======= - let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - const modifierFlags = getModifierFlags(node); - const body = node.body; - const typeParameters = node.typeParameters; - const asteriskToken = node.asteriskToken; - - // A MethodDeclaration is TypeScript syntax if it is either abstract, overloaded, - // generic, or has a decorator. - if (!body - || typeParameters - || (modifierFlags & ModifierFlags.Abstract) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { ->>>>>>> master - transformFlags |= TransformFlags.AssertTypeScript; - } - - // An async method declaration is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertES2017; - } - - // Currently, we only support generators that were originally async function bodies. - if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { - transformFlags |= TransformFlags.AssertGenerator; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.MethodOrAccessorExcludes; - } - - function computeAccessor(node: AccessorDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - -<<<<<<< HEAD - // Decorators, TypeScript-specific modifiers, type annotations, and overloads are - // TypeScript syntax. - if (node.decorators - || hasModifier(node, ModifierFlags.TypeScriptModifier) - || node.type - || !node.body) { -======= - // An accessor is TypeScript syntax if it is either abstract, overloaded, - // generic, or has a decorator. - if (!body - || (modifierFlags & ModifierFlags.Abstract) - || (subtreeFlags & TransformFlags.ContainsDecorators)) { ->>>>>>> master - transformFlags |= TransformFlags.AssertTypeScript; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.MethodOrAccessorExcludes; - } - - function computePropertyDeclaration(node: PropertyDeclaration, subtreeFlags: TransformFlags) { - // A PropertyDeclaration is TypeScript syntax. - let transformFlags = subtreeFlags | TransformFlags.AssertTypeScript; - - // If the PropertyDeclaration has an initializer, we need to inform its ancestor - // so that it handle the transformation. - if (node.initializer) { - transformFlags |= TransformFlags.ContainsPropertyInitializer; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeFunctionDeclaration(node: FunctionDeclaration, subtreeFlags: TransformFlags) { - let transformFlags: TransformFlags; - const modifierFlags = getModifierFlags(node); - const body = node.body; - - if (!body || (modifierFlags & ModifierFlags.Ambient)) { - // An ambient declaration is TypeScript syntax. - // A FunctionDeclaration without a body is an overload and is TypeScript syntax. - transformFlags = TransformFlags.AssertTypeScript; - } - else { - transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; - - // If a FunctionDeclaration is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.AssertES2015; - } - -<<<<<<< HEAD - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (modifierFlags & ModifierFlags.TypeScriptModifier - || node.typeParameters - || node.type) { - transformFlags |= TransformFlags.AssertTypeScript; -======= - // An async function declaration is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertES2017; ->>>>>>> master - } - - // If a FunctionDeclaration's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES2015; - } - - // If a FunctionDeclaration is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { - transformFlags |= TransformFlags.AssertGenerator; - } - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.FunctionExcludes; - } - - function computeFunctionExpression(node: FunctionExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - -<<<<<<< HEAD - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (hasModifier(node, ModifierFlags.TypeScriptModifier) - || node.typeParameters - || node.type) { - transformFlags |= TransformFlags.AssertTypeScript; -======= - // An async function expression is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertES2017; ->>>>>>> master - } - - // If a FunctionExpression's subtree has marked the container as needing to capture the - // lexical this, or the function contains parameters with initializers, then this node is - // ES6 syntax. - if (subtreeFlags & TransformFlags.ES2015FunctionSyntaxMask) { - transformFlags |= TransformFlags.AssertES2015; - } - - // If a FunctionExpression is generator function and is the body of a - // transformed async function, then this node can be transformed to a - // down-level generator. - // Currently we do not support transforming any other generator fucntions - // down level. - if (node.asteriskToken && getEmitFlags(node) & EmitFlags.AsyncFunctionBody) { - transformFlags |= TransformFlags.AssertGenerator; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.FunctionExcludes; - } - - function computeArrowFunction(node: ArrowFunction, subtreeFlags: TransformFlags) { - // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. -<<<<<<< HEAD - let transformFlags = subtreeFlags | TransformFlags.AssertES6; - - // TypeScript-specific modifiers, type parameters, and type annotations are TypeScript - // syntax. - if (hasModifier(node, ModifierFlags.TypeScriptModifier) - || node.typeParameters - || node.type) { - transformFlags |= TransformFlags.AssertTypeScript; -======= - let transformFlags = subtreeFlags | TransformFlags.AssertES2015; - const modifierFlags = getModifierFlags(node); - - // An async arrow function is ES2017 syntax. - if (modifierFlags & ModifierFlags.Async) { - transformFlags |= TransformFlags.AssertES2017; ->>>>>>> master - } - - // If an ArrowFunction contains a lexical this, its container must capture the lexical this. - if (subtreeFlags & TransformFlags.ContainsLexicalThis) { - transformFlags |= TransformFlags.ContainsCapturedLexicalThis; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ArrowFunctionExcludes; - } - - function computePropertyAccess(node: PropertyAccessExpression, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const expression = node.expression; - const expressionKind = expression.kind; - - // If a PropertyAccessExpression starts with a super keyword, then it is - // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === SyntaxKind.SuperKeyword) { - transformFlags |= TransformFlags.ContainsLexicalThis; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeVariableDeclaration(node: VariableDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - const nameKind = node.name.kind; - - // A VariableDeclaration with a binding pattern is ES6 syntax. - if (nameKind === SyntaxKind.ObjectBindingPattern || nameKind === SyntaxKind.ArrayBindingPattern) { - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; - } - - // Type annotations are TypeScript syntax. - if (node.type) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeVariableStatement(node: VariableStatement, subtreeFlags: TransformFlags) { - let transformFlags: TransformFlags; - const modifierFlags = getModifierFlags(node); - const declarationListTransformFlags = node.declarationList.transformFlags; - - // An ambient declaration is TypeScript syntax. - if (modifierFlags & ModifierFlags.Ambient) { - transformFlags = TransformFlags.AssertTypeScript; - } - else { - transformFlags = subtreeFlags; - - // If a VariableStatement is exported, then it is either ES6 or TypeScript syntax. - if (modifierFlags & ModifierFlags.Export) { - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript; - } - - if (declarationListTransformFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES2015; - } - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeLabeledStatement(node: LabeledStatement, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - - // A labeled statement containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding - && isIterationStatement(node, /*lookInLabeledStatements*/ true)) { - transformFlags |= TransformFlags.AssertES2015; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeImportEquals(node: ImportEqualsDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - - // An ImportEqualsDeclaration with a namespace reference is TypeScript. - if (!isExternalModuleImportEqualsDeclaration(node)) { - transformFlags |= TransformFlags.AssertTypeScript; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeExpressionStatement(node: ExpressionStatement, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags; - - // If the expression of an expression statement is a destructuring assignment, - // then we treat the statement as ES6 so that we can indicate that we do not - // need to hold on to the right-hand side. - if (node.expression.transformFlags & TransformFlags.DestructuringAssignment) { - transformFlags |= TransformFlags.AssertES2015; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.NodeExcludes; - } - - function computeModuleDeclaration(node: ModuleDeclaration, subtreeFlags: TransformFlags) { - let transformFlags = TransformFlags.AssertTypeScript; - const modifierFlags = getModifierFlags(node); - - if ((modifierFlags & ModifierFlags.Ambient) === 0) { - transformFlags |= subtreeFlags; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.ModuleExcludes; - } - - function computeVariableDeclarationList(node: VariableDeclarationList, subtreeFlags: TransformFlags) { - let transformFlags = subtreeFlags | TransformFlags.ContainsHoistedDeclarationOrCompletion; - - if (subtreeFlags & TransformFlags.ContainsBindingPattern) { - transformFlags |= TransformFlags.AssertES2015; - } - - // If a VariableDeclarationList is `let` or `const`, then it is ES6 syntax. - if (node.flags & NodeFlags.BlockScoped) { - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBlockScopedBinding; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~TransformFlags.VariableDeclarationListExcludes; - } - - function computeOther(node: Node, kind: SyntaxKind, subtreeFlags: TransformFlags) { - // Mark transformations needed for each node - let transformFlags = subtreeFlags; - let excludeFlags = TransformFlags.NodeExcludes; - - switch (kind) { - case SyntaxKind.AsyncKeyword: - case SyntaxKind.AwaitExpression: - // async/await is ES2017 syntax - transformFlags |= TransformFlags.AssertES2017; - break; - - case SyntaxKind.PublicKeyword: - case SyntaxKind.PrivateKeyword: - case SyntaxKind.ProtectedKeyword: - case SyntaxKind.AbstractKeyword: - case SyntaxKind.DeclareKeyword: - case SyntaxKind.ConstKeyword: - case SyntaxKind.EnumDeclaration: - case SyntaxKind.EnumMember: - case SyntaxKind.TypeAssertionExpression: - case SyntaxKind.AsExpression: - case SyntaxKind.NonNullExpression: - case SyntaxKind.ReadonlyKeyword: - // These nodes are TypeScript syntax. - transformFlags |= TransformFlags.AssertTypeScript; - break; - - case SyntaxKind.JsxElement: - case SyntaxKind.JsxSelfClosingElement: - case SyntaxKind.JsxOpeningElement: - case SyntaxKind.JsxText: - case SyntaxKind.JsxClosingElement: - case SyntaxKind.JsxAttribute: - case SyntaxKind.JsxSpreadAttribute: - case SyntaxKind.JsxExpression: - // These nodes are Jsx syntax. - transformFlags |= TransformFlags.AssertJsx; - break; - - case SyntaxKind.ExportKeyword: - // This node is both ES6 and TypeScript syntax. - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.AssertTypeScript; - break; - - case SyntaxKind.DefaultKeyword: - case SyntaxKind.NoSubstitutionTemplateLiteral: - case SyntaxKind.TemplateHead: - case SyntaxKind.TemplateMiddle: - case SyntaxKind.TemplateTail: - case SyntaxKind.TemplateExpression: - case SyntaxKind.TaggedTemplateExpression: - case SyntaxKind.ShorthandPropertyAssignment: - case SyntaxKind.ForOfStatement: - // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES2015; - break; - - case SyntaxKind.YieldExpression: - // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsYield; - break; - - case SyntaxKind.AnyKeyword: - case SyntaxKind.NumberKeyword: - case SyntaxKind.NeverKeyword: - case SyntaxKind.StringKeyword: - case SyntaxKind.BooleanKeyword: - case SyntaxKind.SymbolKeyword: - case SyntaxKind.VoidKeyword: - case SyntaxKind.TypeParameter: - case SyntaxKind.PropertySignature: - case SyntaxKind.MethodSignature: - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - case SyntaxKind.TypePredicate: - case SyntaxKind.TypeReference: - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - case SyntaxKind.TypeQuery: - case SyntaxKind.TypeLiteral: - case SyntaxKind.ArrayType: - case SyntaxKind.TupleType: - case SyntaxKind.UnionType: - case SyntaxKind.IntersectionType: - case SyntaxKind.ParenthesizedType: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.TypeAliasDeclaration: - case SyntaxKind.ThisType: - case SyntaxKind.LiteralType: - // Types and signatures are TypeScript syntax, and exclude all other facts. - transformFlags = TransformFlags.AssertTypeScript; - excludeFlags = TransformFlags.TypeExcludes; - break; - - case SyntaxKind.ComputedPropertyName: - // Even though computed property names are ES6, we don't treat them as such. - // This is so that they can flow through PropertyName transforms unaffected. - // Instead, we mark the container as ES6, so that it can properly handle the transform. - transformFlags |= TransformFlags.ContainsComputedPropertyName; - if (subtreeFlags & TransformFlags.ContainsLexicalThis) { - // A computed method name like `[this.getName()](x: string) { ... }` needs to - // distinguish itself from the normal case of a method body containing `this`: - // `this` inside a method doesn't need to be rewritten (the method provides `this`), - // whereas `this` inside a computed name *might* need to be rewritten if the class/object - // is inside an arrow function: - // `_this = this; () => class K { [_this.getName()]() { ... } }` - // To make this distinction, use ContainsLexicalThisInComputedPropertyName - // instead of ContainsLexicalThis for computed property names - transformFlags |= TransformFlags.ContainsLexicalThisInComputedPropertyName; - } - break; - - case SyntaxKind.SpreadElementExpression: - // This node is ES6 syntax, but is handled by a containing node. - transformFlags |= TransformFlags.ContainsSpreadElementExpression; - break; - - case SyntaxKind.SuperKeyword: - // This node is ES6 syntax. - transformFlags |= TransformFlags.AssertES2015; - break; - - case SyntaxKind.ThisKeyword: - // Mark this node and its ancestors as containing a lexical `this` keyword. - transformFlags |= TransformFlags.ContainsLexicalThis; - break; - - case SyntaxKind.ObjectBindingPattern: - case SyntaxKind.ArrayBindingPattern: - // These nodes are ES6 syntax. - transformFlags |= TransformFlags.AssertES2015 | TransformFlags.ContainsBindingPattern; - break; - - case SyntaxKind.Decorator: - // This node is TypeScript syntax, and marks its container as also being TypeScript syntax. - transformFlags |= TransformFlags.AssertTypeScript | TransformFlags.ContainsDecorators; - break; - - case SyntaxKind.ObjectLiteralExpression: - excludeFlags = TransformFlags.ObjectLiteralExcludes; - if (subtreeFlags & TransformFlags.ContainsComputedPropertyName) { - // If an ObjectLiteralExpression contains a ComputedPropertyName, then it - // is an ES6 node. - transformFlags |= TransformFlags.AssertES2015; - } - - if (subtreeFlags & TransformFlags.ContainsLexicalThisInComputedPropertyName) { - // A computed property name containing `this` might need to be rewritten, - // so propagate the ContainsLexicalThis flag upward. - transformFlags |= TransformFlags.ContainsLexicalThis; - } - - break; - - case SyntaxKind.ArrayLiteralExpression: - case SyntaxKind.NewExpression: - excludeFlags = TransformFlags.ArrayLiteralOrCallOrNewExcludes; - if (subtreeFlags & TransformFlags.ContainsSpreadElementExpression) { - // If the this node contains a SpreadElementExpression, then it is an ES6 - // node. - transformFlags |= TransformFlags.AssertES2015; - } - - break; - - case SyntaxKind.DoStatement: - case SyntaxKind.WhileStatement: - case SyntaxKind.ForStatement: - case SyntaxKind.ForInStatement: - // A loop containing a block scoped binding *may* need to be transformed from ES6. - if (subtreeFlags & TransformFlags.ContainsBlockScopedBinding) { - transformFlags |= TransformFlags.AssertES2015; - } - - break; - - case SyntaxKind.SourceFile: - if (subtreeFlags & TransformFlags.ContainsCapturedLexicalThis) { - transformFlags |= TransformFlags.AssertES2015; - } - - break; - - case SyntaxKind.ReturnStatement: - case SyntaxKind.ContinueStatement: - case SyntaxKind.BreakStatement: - transformFlags |= TransformFlags.ContainsHoistedDeclarationOrCompletion; - break; - } - - node.transformFlags = transformFlags | TransformFlags.HasComputedFlags; - return transformFlags & ~excludeFlags; - } -} From db76a9ca0720199852c39eef1c8956d5c55bacb7 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Sat, 15 Oct 2016 17:29:03 -0700 Subject: [PATCH 74/74] More tests --- .../transformsElideNullUndefinedType.js | 68 ++++++++++-- .../transformsElideNullUndefinedType.symbols | 101 ++++++++++++++--- .../transformsElideNullUndefinedType.types | 102 ++++++++++++++++-- .../transformsElideNullUndefinedType.ts | 36 ++++++- 4 files changed, 272 insertions(+), 35 deletions(-) diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.js b/tests/baselines/reference/transformsElideNullUndefinedType.js index a5e27eee08b..63bc77559c1 100644 --- a/tests/baselines/reference/transformsElideNullUndefinedType.js +++ b/tests/baselines/reference/transformsElideNullUndefinedType.js @@ -15,21 +15,49 @@ var f5 = (): undefined => undefined; function f6(p0: null) { } function f7(p1: undefined) { } -class C { +var f8 = function (p2: null) { } +var f9 = function (p3: undefined) { } + +var f10 = (p4: null) => { } +var f11 = (p5: undefined) => { } + +class C1 { m0(): null { return null; } m1(): undefined { return undefined; } + m3(p6: null) { } + m4(p7: undefined) { } + get a0(): null { return null; } get a1(): undefined { return undefined; } + + set a2(p8: null) { } + set a3(p9: undefined) { } } -declare function fn(); +class C2 { constructor(p10: null) { } } +class C3 { constructor(p11: undefined) { } } +class C4 { + f1; + constructor(p12: null) { } +} + +class C5 { + f2; + constructor(p13: undefined) { } +} + +var C6 = class { constructor(p12: null) { } } +var C7 = class { constructor(p13: undefined) { } } + +declare function fn(); fn(); fn(); -new C(); -new C(); +declare class D {} +new D(); +new D(); //// [transformsElideNullUndefinedType.js] var v0; @@ -42,13 +70,39 @@ var f4 = () => null; var f5 = () => undefined; function f6(p0) { } function f7(p1) { } -class C { +var f8 = function (p2) { }; +var f9 = function (p3) { }; +var f10 = (p4) => { }; +var f11 = (p5) => { }; +class C1 { m0() { return null; } m1() { return undefined; } + m3(p6) { } + m4(p7) { } get a0() { return null; } get a1() { return undefined; } + set a2(p8) { } + set a3(p9) { } } +class C2 { + constructor(p10) { } +} +class C3 { + constructor(p11) { } +} +class C4 { + constructor(p12) { } +} +class C5 { + constructor(p13) { } +} +var C6 = class { + constructor(p12) { } +}; +var C7 = class { + constructor(p13) { } +}; fn(); fn(); -new C(); -new C(); +new D(); +new D(); diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.symbols b/tests/baselines/reference/transformsElideNullUndefinedType.symbols index 0c9333d9820..b651784a61c 100644 --- a/tests/baselines/reference/transformsElideNullUndefinedType.symbols +++ b/tests/baselines/reference/transformsElideNullUndefinedType.symbols @@ -35,38 +35,109 @@ function f7(p1: undefined) { } >f7 : Symbol(f7, Decl(transformsElideNullUndefinedType.ts, 13, 25)) >p1 : Symbol(p1, Decl(transformsElideNullUndefinedType.ts, 14, 12)) -class C { ->C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) ->T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 16, 8)) +var f8 = function (p2: null) { } +>f8 : Symbol(f8, Decl(transformsElideNullUndefinedType.ts, 16, 3)) +>p2 : Symbol(p2, Decl(transformsElideNullUndefinedType.ts, 16, 19)) + +var f9 = function (p3: undefined) { } +>f9 : Symbol(f9, Decl(transformsElideNullUndefinedType.ts, 17, 3)) +>p3 : Symbol(p3, Decl(transformsElideNullUndefinedType.ts, 17, 19)) + +var f10 = (p4: null) => { } +>f10 : Symbol(f10, Decl(transformsElideNullUndefinedType.ts, 19, 3)) +>p4 : Symbol(p4, Decl(transformsElideNullUndefinedType.ts, 19, 11)) + +var f11 = (p5: undefined) => { } +>f11 : Symbol(f11, Decl(transformsElideNullUndefinedType.ts, 20, 3)) +>p5 : Symbol(p5, Decl(transformsElideNullUndefinedType.ts, 20, 11)) + +class C1 { +>C1 : Symbol(C1, Decl(transformsElideNullUndefinedType.ts, 20, 32)) m0(): null { return null; } ->m0 : Symbol(C.m0, Decl(transformsElideNullUndefinedType.ts, 16, 12)) +>m0 : Symbol(C1.m0, Decl(transformsElideNullUndefinedType.ts, 22, 10)) m1(): undefined { return undefined; } ->m1 : Symbol(C.m1, Decl(transformsElideNullUndefinedType.ts, 17, 31)) +>m1 : Symbol(C1.m1, Decl(transformsElideNullUndefinedType.ts, 23, 31)) >undefined : Symbol(undefined) + m3(p6: null) { } +>m3 : Symbol(C1.m3, Decl(transformsElideNullUndefinedType.ts, 24, 41)) +>p6 : Symbol(p6, Decl(transformsElideNullUndefinedType.ts, 26, 7)) + + m4(p7: undefined) { } +>m4 : Symbol(C1.m4, Decl(transformsElideNullUndefinedType.ts, 26, 20)) +>p7 : Symbol(p7, Decl(transformsElideNullUndefinedType.ts, 27, 7)) + get a0(): null { return null; } ->a0 : Symbol(C.a0, Decl(transformsElideNullUndefinedType.ts, 18, 41)) +>a0 : Symbol(C1.a0, Decl(transformsElideNullUndefinedType.ts, 27, 25)) get a1(): undefined { return undefined; } ->a1 : Symbol(C.a1, Decl(transformsElideNullUndefinedType.ts, 20, 35)) +>a1 : Symbol(C1.a1, Decl(transformsElideNullUndefinedType.ts, 29, 35)) >undefined : Symbol(undefined) + + set a2(p8: null) { } +>a2 : Symbol(C1.a2, Decl(transformsElideNullUndefinedType.ts, 30, 45)) +>p8 : Symbol(p8, Decl(transformsElideNullUndefinedType.ts, 32, 11)) + + set a3(p9: undefined) { } +>a3 : Symbol(C1.a3, Decl(transformsElideNullUndefinedType.ts, 32, 24)) +>p9 : Symbol(p9, Decl(transformsElideNullUndefinedType.ts, 33, 11)) } +class C2 { constructor(p10: null) { } } +>C2 : Symbol(C2, Decl(transformsElideNullUndefinedType.ts, 34, 1)) +>p10 : Symbol(p10, Decl(transformsElideNullUndefinedType.ts, 36, 23)) + +class C3 { constructor(p11: undefined) { } } +>C3 : Symbol(C3, Decl(transformsElideNullUndefinedType.ts, 36, 39)) +>p11 : Symbol(p11, Decl(transformsElideNullUndefinedType.ts, 37, 23)) + +class C4 { +>C4 : Symbol(C4, Decl(transformsElideNullUndefinedType.ts, 37, 44)) + + f1; +>f1 : Symbol(C4.f1, Decl(transformsElideNullUndefinedType.ts, 39, 10)) + + constructor(p12: null) { } +>p12 : Symbol(p12, Decl(transformsElideNullUndefinedType.ts, 41, 16)) +} + +class C5 { +>C5 : Symbol(C5, Decl(transformsElideNullUndefinedType.ts, 42, 1)) + + f2; +>f2 : Symbol(C5.f2, Decl(transformsElideNullUndefinedType.ts, 44, 10)) + + constructor(p13: undefined) { } +>p13 : Symbol(p13, Decl(transformsElideNullUndefinedType.ts, 46, 16)) +} + +var C6 = class { constructor(p12: null) { } } +>C6 : Symbol(C6, Decl(transformsElideNullUndefinedType.ts, 49, 3)) +>p12 : Symbol(p12, Decl(transformsElideNullUndefinedType.ts, 49, 29)) + +var C7 = class { constructor(p13: undefined) { } } +>C7 : Symbol(C7, Decl(transformsElideNullUndefinedType.ts, 50, 3)) +>p13 : Symbol(p13, Decl(transformsElideNullUndefinedType.ts, 50, 29)) + declare function fn(); ->fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) ->T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 24, 20)) +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 52, 20)) fn(); ->fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) fn(); ->fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 22, 1)) +>fn : Symbol(fn, Decl(transformsElideNullUndefinedType.ts, 50, 50)) -new C(); ->C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) +declare class D {} +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) +>T : Symbol(T, Decl(transformsElideNullUndefinedType.ts, 56, 16)) -new C(); ->C : Symbol(C, Decl(transformsElideNullUndefinedType.ts, 14, 30)) +new D(); +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) + +new D(); +>D : Symbol(D, Decl(transformsElideNullUndefinedType.ts, 54, 16)) diff --git a/tests/baselines/reference/transformsElideNullUndefinedType.types b/tests/baselines/reference/transformsElideNullUndefinedType.types index 66a73c83141..7f48d8a00e9 100644 --- a/tests/baselines/reference/transformsElideNullUndefinedType.types +++ b/tests/baselines/reference/transformsElideNullUndefinedType.types @@ -47,9 +47,30 @@ function f7(p1: undefined) { } >f7 : (p1: undefined) => void >p1 : undefined -class C { ->C : C ->T : T +var f8 = function (p2: null) { } +>f8 : (p2: null) => void +>function (p2: null) { } : (p2: null) => void +>p2 : null +>null : null + +var f9 = function (p3: undefined) { } +>f9 : (p3: undefined) => void +>function (p3: undefined) { } : (p3: undefined) => void +>p3 : undefined + +var f10 = (p4: null) => { } +>f10 : (p4: null) => void +>(p4: null) => { } : (p4: null) => void +>p4 : null +>null : null + +var f11 = (p5: undefined) => { } +>f11 : (p5: undefined) => void +>(p5: undefined) => { } : (p5: undefined) => void +>p5 : undefined + +class C1 { +>C1 : C1 m0(): null { return null; } >m0 : () => null @@ -60,6 +81,15 @@ class C { >m1 : () => undefined >undefined : undefined + m3(p6: null) { } +>m3 : (p6: null) => void +>p6 : null +>null : null + + m4(p7: undefined) { } +>m4 : (p7: undefined) => void +>p7 : undefined + get a0(): null { return null; } >a0 : null >null : null @@ -68,8 +98,58 @@ class C { get a1(): undefined { return undefined; } >a1 : undefined >undefined : undefined + + set a2(p8: null) { } +>a2 : null +>p8 : null +>null : null + + set a3(p9: undefined) { } +>a3 : undefined +>p9 : undefined } +class C2 { constructor(p10: null) { } } +>C2 : C2 +>p10 : null +>null : null + +class C3 { constructor(p11: undefined) { } } +>C3 : C3 +>p11 : undefined + +class C4 { +>C4 : C4 + + f1; +>f1 : any + + constructor(p12: null) { } +>p12 : null +>null : null +} + +class C5 { +>C5 : C5 + + f2; +>f2 : any + + constructor(p13: undefined) { } +>p13 : undefined +} + +var C6 = class { constructor(p12: null) { } } +>C6 : typeof (Anonymous class) +>class { constructor(p12: null) { } } : typeof (Anonymous class) +>p12 : null +>null : null + +var C7 = class { constructor(p13: undefined) { } } +>C7 : typeof (Anonymous class) +>class { constructor(p13: undefined) { } } : typeof (Anonymous class) +>p13 : undefined + declare function fn(); >fn : () => any >T : T @@ -83,12 +163,16 @@ fn(); >fn() : any >fn : () => any -new C(); ->new C() : C ->C : typeof C +declare class D {} +>D : D +>T : T + +new D(); +>new D() : D +>D : typeof D >null : null -new C(); ->new C() : C ->C : typeof C +new D(); +>new D() : D +>D : typeof D diff --git a/tests/cases/compiler/transformsElideNullUndefinedType.ts b/tests/cases/compiler/transformsElideNullUndefinedType.ts index 244f2ea9c75..4a493a91d88 100644 --- a/tests/cases/compiler/transformsElideNullUndefinedType.ts +++ b/tests/cases/compiler/transformsElideNullUndefinedType.ts @@ -15,18 +15,46 @@ var f5 = (): undefined => undefined; function f6(p0: null) { } function f7(p1: undefined) { } -class C { +var f8 = function (p2: null) { } +var f9 = function (p3: undefined) { } + +var f10 = (p4: null) => { } +var f11 = (p5: undefined) => { } + +class C1 { m0(): null { return null; } m1(): undefined { return undefined; } + m3(p6: null) { } + m4(p7: undefined) { } + get a0(): null { return null; } get a1(): undefined { return undefined; } + + set a2(p8: null) { } + set a3(p9: undefined) { } } -declare function fn(); +class C2 { constructor(p10: null) { } } +class C3 { constructor(p11: undefined) { } } +class C4 { + f1; + constructor(p12: null) { } +} + +class C5 { + f2; + constructor(p13: undefined) { } +} + +var C6 = class { constructor(p12: null) { } } +var C7 = class { constructor(p13: undefined) { } } + +declare function fn(); fn(); fn(); -new C(); -new C(); \ No newline at end of file +declare class D {} +new D(); +new D(); \ No newline at end of file