diff --git a/.npmignore b/.npmignore index 99b51a2b65..98c50479c6 100644 --- a/.npmignore +++ b/.npmignore @@ -1,5 +1,7 @@ built doc +scripts src tests Jakefile +.travis.yml \ No newline at end of file diff --git a/Jakefile b/Jakefile index c994273daa..b752e3cd8a 100644 --- a/Jakefile +++ b/Jakefile @@ -39,6 +39,7 @@ var compilerSources = [ "binder.ts", "checker.ts", "emitter.ts", + "program.ts", "commandLineParser.ts", "tsc.ts", "diagnosticInformationMap.generated.ts" @@ -56,6 +57,7 @@ var servicesSources = [ "binder.ts", "checker.ts", "emitter.ts", + "program.ts", "diagnosticInformationMap.generated.ts" ].map(function (f) { return path.join(compilerDirectory, f); @@ -92,6 +94,7 @@ var definitionsRoots = [ "compiler/scanner.d.ts", "compiler/parser.d.ts", "compiler/checker.d.ts", + "compiler/program.d.ts", "services/services.d.ts", ]; @@ -189,8 +192,7 @@ var compilerFilename = "tsc.js"; * @param keepComments: false to compile using --removeComments * @param callback: a function to execute after the compilation process ends */ - -function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, keepComments, noResolve, callback) { +function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, callback) { file(outFile, prereqs, function() { var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory; var options = "--module commonjs -noImplicitAny"; @@ -203,7 +205,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOu options += " --declaration"; } - if (useDebugMode) { + if (useDebugMode || preserveConstEnums) { options += " --preserveConstEnums"; } @@ -319,7 +321,15 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename); compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false); var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js"); -compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), [copyright], /*useBuiltCompiler*/ true); +compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), + /*prefixes*/ [copyright], + /*useBuiltCompiler*/ true, + /*noOutFile*/ false, + /*generateDeclarations*/ false, + /*outDir*/ undefined, + /*preserveConstEnums*/ true, + /*keepComments*/ false, + /*noResolve*/ false); var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts"); var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts"); @@ -332,6 +342,7 @@ compileFile(nodeDefinitionsFile, servicesSources,[builtLocalDirectory, copyright /*noOutFile*/ true, /*generateDeclarations*/ true, /*outDir*/ tempDirPath, + /*preserveConstEnums*/ true, /*keepComments*/ true, /*noResolve*/ true, /*callback*/ function () { @@ -380,7 +391,7 @@ task("clean", function() { var analyzerFile = path.join(builtLocalDirectory, "analyzer.js"); var analyserSourceFile = "src/services/analyzer.ts"; -compileFile(analyzerFile, [analyserSourceFile], [builtLocalDirectory, analyserSourceFile].concat(servicesSources), [], true, false, true); +compileFile(analyzerFile, [analyserSourceFile], [builtLocalDirectory, analyserSourceFile].concat(servicesSources), [], false, false, true); desc("Builds analyzer"); task("analyzer", [analyzerFile]); diff --git a/bin/tsc.js b/bin/tsc.js index e1b93961fc..b547abd246 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -36,7 +36,7 @@ var ts; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i]); + var result = callback(array[i], i); if (result) { return result; } @@ -943,7 +943,9 @@ var ts; A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: 1 /* Error */, key: "A destructuring declaration must have an initializer.", isEarly: true }, Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: 1 /* Error */, key: "Destructuring declarations are not allowed in ambient contexts.", isEarly: true }, An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: 1 /* Error */, key: "An implementation cannot be declared in ambient contexts.", isEarly: true }, - Merge_conflict_marker_encountered: { code: 1184, category: 1 /* Error */, key: "Merge conflict marker encountered." }, + Modifiers_cannot_appear_here: { code: 1184, category: 1 /* Error */, key: "Modifiers cannot appear here." }, + Merge_conflict_marker_encountered: { code: 1185, category: 1 /* Error */, key: "Merge conflict marker encountered." }, + A_rest_element_cannot_have_an_initializer: { code: 1186, category: 1 /* Error */, key: "A rest element cannot have an initializer." }, Duplicate_identifier_0: { code: 2300, category: 1 /* Error */, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: 1 /* Error */, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: 1 /* Error */, key: "Static members cannot reference class type parameters." }, @@ -1094,6 +1096,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: 1 /* Error */, key: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: 1 /* Error */, key: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: 1 /* Error */, key: "Type '{0}' is not an array type." }, + A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: 1 /* Error */, key: "A rest element must be last in an array destructuring pattern" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: 1 /* Error */, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1177,6 +1180,8 @@ var ts; Could_not_write_file_0_Colon_1: { code: 5033, category: 1 /* Error */, key: "Could not write file '{0}': {1}" }, Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, + Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option noEmit cannot be specified with option out or outDir." }, + Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option noEmit cannot be specified with option declaration." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: 2 /* Message */, key: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: 2 /* Message */, key: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: 2 /* Message */, key: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1186,6 +1191,7 @@ var ts; Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: 2 /* Message */, key: "Do not erase const enum declarations in generated code." }, Do_not_emit_outputs_if_any_type_checking_errors_were_reported: { code: 6008, category: 2 /* Message */, key: "Do not emit outputs if any type checking errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: 2 /* Message */, key: "Do not emit comments to output." }, + Do_not_emit_outputs: { code: 6010, category: 2 /* Message */, key: "Do not emit outputs." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: 2 /* Message */, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" }, Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: 2 /* Message */, key: "Specify module code generation: 'commonjs' or 'amd'" }, Print_this_message: { code: 6017, category: 2 /* Message */, key: "Print this message." }, @@ -1521,25 +1527,42 @@ var ts; } } ts.skipTrivia = skipTrivia; + var mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text, pos) { - if (pos > 0 && isLineBreak(text.charCodeAt(pos - 1))) { + ts.Debug.assert(pos >= 0); + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { var ch = text.charCodeAt(pos); - var markerLength = "<<<<<<<".length; - if ((pos + markerLength) < text.length) { - for (var i = 0, n = markerLength; i < n; i++) { + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) { if (text.charCodeAt(pos + i) !== ch) { return false; } } - return ch === 61 /* equals */ || text.charCodeAt(pos + markerLength) === 32 /* space */; + return ch === 61 /* equals */ || text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; } } return false; } - function scanConflictMarkerTrivia(text, pos) { + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); var len = text.length; - while (pos < len && !isLineBreak(text.charCodeAt(pos))) { - pos++; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 61 /* equals */); + while (pos < len) { + var ch = text.charCodeAt(pos); + if (ch === 62 /* greaterThan */ && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } } return pos; } @@ -1638,9 +1661,9 @@ var ts; var tokenValue; var precedingLineBreak; var tokenIsUnterminated; - function error(message) { + function error(message, length) { if (onError) { - onError(message); + onError(message, length || 0); } } function isIdentifierStart(ch) { @@ -2103,8 +2126,7 @@ var ts; return pos++, token = 22 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2124,8 +2146,7 @@ var ts; return pos++, token = 24 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2145,8 +2166,7 @@ var ts; return pos++, token = 52 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2392,17 +2412,14 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasFlag(val, flag) { - return (val & flag) !== 0; - } function containsParseError(node) { aggregateChildData(node); - return hasFlag(node.parserContextFlags, 32 /* ThisNodeOrAnySubNodesHasError */); + return (node.parserContextFlags & 32 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!hasFlag(node.parserContextFlags, 64 /* HasAggregatedChildData */)) { - var thisNodeOrAnySubNodesHasError = hasFlag(node.parserContextFlags, 16 /* ThisNodeHasError */) || ts.forEachChild(node, containsParseError); + if (!(node.parserContextFlags & 64 /* HasAggregatedChildData */)) { + var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { node.parserContextFlags |= 32 /* ThisNodeOrAnySubNodesHasError */; } @@ -2426,19 +2443,26 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; - function isMissingNode(node) { + function nodeIsMissing(node) { + if (!node) { + return true; + } return node.pos === node.end && node.kind !== 1 /* EndOfFileToken */; } - ts.isMissingNode = isMissingNode; + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; function getTokenPosOfNode(node, sourceFile) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return node.pos; } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } var text = sourceFile.text; @@ -2446,7 +2470,7 @@ var ts; } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; function getTextOfNodeFromSourceText(sourceText, node) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); @@ -2487,7 +2511,7 @@ var ts; function getErrorSpanForNode(node) { var errorSpan; switch (node.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 191 /* ClassDeclaration */: case 192 /* InterfaceDeclaration */: @@ -2512,16 +2536,38 @@ var ts; return node.kind === 194 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 146 /* BindingElement */ || isBindingPattern(node))) { + node = node.parent; + } + return node; + } + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 188 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 189 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 171 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(node.flags & 4096 /* Const */); + return !!(getCombinedNodeFlags(node) & 4096 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(node.flags & 2048 /* Let */); + return !!(getCombinedNodeFlags(node) & 2048 /* Let */); } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 172 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; + return node.kind === 173 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -2546,23 +2592,21 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return visitor(node); - case 169 /* Block */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return ts.forEachChild(node, traverse); } } @@ -2594,7 +2638,7 @@ var ts; } ts.isAnyFunction = isAnyFunction; function isFunctionBlock(node) { - return node && node.kind === 169 /* Block */ && isAnyFunction(node.parent); + return node && node.kind === 170 /* Block */ && isAnyFunction(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -2690,9 +2734,10 @@ var ts; case 162 /* PostfixUnaryExpression */: case 163 /* BinaryExpression */: case 164 /* ConditionalExpression */: + case 167 /* SpreadElementExpression */: case 165 /* TemplateExpression */: case 10 /* NoSubstitutionTemplateLiteral */: - case 167 /* OmittedExpression */: + case 168 /* OmittedExpression */: return true; case 121 /* QualifiedName */: while (node.parent.kind === 121 /* QualifiedName */) { @@ -2707,7 +2752,7 @@ var ts; case 8 /* StringLiteral */: var parent = node.parent; switch (parent.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 124 /* Parameter */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: @@ -2715,24 +2760,26 @@ var ts; case 204 /* PropertyAssignment */: case 146 /* BindingElement */: return parent.initializer === node; - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 180 /* ReturnStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 181 /* ReturnStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: - case 184 /* ThrowStatement */: - case 182 /* SwitchStatement */: + case 185 /* ThrowStatement */: + case 183 /* SwitchStatement */: return parent.expression === node; - case 176 /* ForStatement */: - return parent.initializer === node || parent.condition === node || parent.iterator === node; - case 177 /* ForInStatement */: - return parent.variable === node || parent.expression === node; + case 177 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 189 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.iterator === node; + case 178 /* ForInStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 189 /* VariableDeclarationList */) || forInStatement.expression === node; case 154 /* TypeAssertionExpression */: return node === parent.expression; - case 168 /* TemplateSpan */: + case 169 /* TemplateSpan */: return node === parent.expression; default: if (isExpression(parent)) { @@ -2800,8 +2847,9 @@ var ts; ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 /* Ambient */ | 1024 /* DeclarationFile */)) + if (node.flags & (2 /* Ambient */ | 1024 /* DeclarationFile */)) { return true; + } node = node.parent; } return false; @@ -2811,7 +2859,7 @@ var ts; switch (node.kind) { case 123 /* TypeParameter */: case 124 /* Parameter */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: @@ -2837,23 +2885,23 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 179 /* BreakStatement */: - case 178 /* ContinueStatement */: - case 188 /* DebuggerStatement */: - case 174 /* DoStatement */: - case 172 /* ExpressionStatement */: - case 171 /* EmptyStatement */: - case 177 /* ForInStatement */: - case 176 /* ForStatement */: - case 173 /* IfStatement */: - case 183 /* LabeledStatement */: - case 180 /* ReturnStatement */: - case 182 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 187 /* DebuggerStatement */: + case 175 /* DoStatement */: + case 173 /* ExpressionStatement */: + case 172 /* EmptyStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 174 /* IfStatement */: + case 184 /* LabeledStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: case 93 /* ThrowKeyword */: - case 185 /* TryStatement */: - case 170 /* VariableStatement */: - case 175 /* WhileStatement */: - case 181 /* WithStatement */: + case 186 /* TryStatement */: + case 171 /* VariableStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: case 198 /* ExportAssignment */: return true; default: @@ -2901,11 +2949,11 @@ var ts; return undefined; } ts.getHeritageClause = getHeritageClause; - function tryResolveScriptReference(program, sourceFile, reference) { - if (!program.getCompilerOptions().noResolve) { + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.filename) ? reference.filename : ts.combinePaths(ts.getDirectoryPath(sourceFile.filename), reference.filename); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, program.getCompilerHost().getCurrentDirectory()); - return program.getSourceFile(referenceFileName); + referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); + return host.getSourceFile(referenceFileName); } } ts.tryResolveScriptReference = tryResolveScriptReference; @@ -2996,10 +3044,134 @@ var ts; return false; } ts.isModifier = isModifier; + function createEmitHostFromProgram(program) { + var compilerHost = program.getCompilerHost(); + return { + getCanonicalFileName: compilerHost.getCanonicalFileName, + getCommonSourceDirectory: program.getCommonSourceDirectory, + getCompilerOptions: program.getCompilerOptions, + getCurrentDirectory: compilerHost.getCurrentDirectory, + getNewLine: compilerHost.getNewLine, + getSourceFile: program.getSourceFile, + getSourceFiles: program.getSourceFiles, + isEmitBlocked: program.isEmitBlocked, + writeFile: compilerHost.writeFile + }; + } + ts.createEmitHostFromProgram = createEmitHostFromProgram; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; })(ts || (ts = {})); var ts; (function (ts) { - var nodeConstructors = new Array(210 /* Count */); + var nodeConstructors = new Array(209 /* Count */); function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); } @@ -3041,7 +3213,7 @@ var ts; case 125 /* PropertySignature */: case 204 /* PropertyAssignment */: case 205 /* ShorthandPropertyAssignment */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: return children(node.modifiers) || child(node.propertyName) || child(node.dotDotDotToken) || child(node.name) || child(node.questionToken) || child(node.type) || child(node.initializer); case 136 /* FunctionType */: @@ -3109,45 +3281,47 @@ var ts; return child(node.left) || child(node.right); case 164 /* ConditionalExpression */: return child(node.condition) || child(node.whenTrue) || child(node.whenFalse); - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: + case 167 /* SpreadElementExpression */: + return child(node.expression); + case 170 /* Block */: case 196 /* ModuleBlock */: return children(node.statements); case 207 /* SourceFile */: return children(node.statements) || child(node.endOfFileToken); - case 170 /* VariableStatement */: - return children(node.modifiers) || children(node.declarations); - case 172 /* ExpressionStatement */: + case 171 /* VariableStatement */: + return children(node.modifiers) || child(node.declarationList); + case 189 /* VariableDeclarationList */: + return children(node.declarations); + case 173 /* ExpressionStatement */: return child(node.expression); - case 173 /* IfStatement */: + case 174 /* IfStatement */: return child(node.expression) || child(node.thenStatement) || child(node.elseStatement); - case 174 /* DoStatement */: + case 175 /* DoStatement */: return child(node.statement) || child(node.expression); - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return child(node.expression) || child(node.statement); - case 176 /* ForStatement */: - return children(node.declarations) || child(node.initializer) || child(node.condition) || child(node.iterator) || child(node.statement); - case 177 /* ForInStatement */: - return children(node.declarations) || child(node.variable) || child(node.expression) || child(node.statement); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: + case 177 /* ForStatement */: + return child(node.initializer) || child(node.condition) || child(node.iterator) || child(node.statement); + case 178 /* ForInStatement */: + return child(node.initializer) || child(node.expression) || child(node.statement); + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: return child(node.label); - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return child(node.expression); - case 181 /* WithStatement */: + case 182 /* WithStatement */: return child(node.expression) || child(node.statement); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return child(node.expression) || children(node.clauses); case 200 /* CaseClause */: return child(node.expression) || children(node.statements); case 201 /* DefaultClause */: return children(node.statements); - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return child(node.label) || child(node.statement); - case 184 /* ThrowStatement */: + case 185 /* ThrowStatement */: return child(node.expression); - case 185 /* TryStatement */: + case 186 /* TryStatement */: return child(node.tryBlock) || child(node.catchClause) || child(node.finallyBlock); case 203 /* CatchClause */: return child(node.name) || child(node.type) || child(node.block); @@ -3169,7 +3343,7 @@ var ts; return children(node.modifiers) || child(node.exportName); case 165 /* TemplateExpression */: return child(node.head) || children(node.templateSpans); - case 168 /* TemplateSpan */: + case 169 /* TemplateSpan */: return child(node.expression) || child(node.literal); case 122 /* ComputedPropertyName */: return child(node.expression); @@ -3180,64 +3354,6 @@ var ts; } } ts.forEachChild = forEachChild; - function createCompilerHost(options) { - var currentDirectory; - var existingDirectories = {}; - function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } - var unsupportedFileEncodingErrorCode = -2147024809; - function getSourceFile(filename, languageVersion, onError) { - try { - var text = ts.sys.readFile(filename, options.charset); - } - catch (e) { - if (onError) { - onError(e.number === unsupportedFileEncodingErrorCode ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText : e.message); - } - text = ""; - } - return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; - } - function writeFile(fileName, data, writeByteOrderMark, onError) { - function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { - return true; - } - if (ts.sys.directoryExists(directoryPath)) { - existingDirectories[directoryPath] = true; - return true; - } - return false; - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); - } - } - try { - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - ts.sys.writeFile(fileName, data, writeByteOrderMark); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } - return { - getSourceFile: getSourceFile, - getDefaultLibFilename: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"); }, - writeFile: writeFile, - getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } - }; - } - ts.createCompilerHost = createCompilerHost; function parsingContextErrors(context) { switch (context) { case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected; @@ -3298,45 +3414,265 @@ var ts; var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, node.expression); return nodeText === '"use strict"' || nodeText === "'use strict'"; } + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < currentArray.length) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0, n = array.length; i < n; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } function createSourceFile(filename, sourceText, languageVersion, setParentNodes) { if (setParentNodes === void 0) { setParentNodes = false; } var parsingContext; - var identifiers = {}; + var identifiers; var identifierCount = 0; var nodeCount = 0; var lineStarts; - var contextFlags = 0; - var parseErrorBeforeNextFinishedNode = false; - var sourceFile = createNode(207 /* SourceFile */, 0); - if (ts.fileExtensionIs(filename, ".d.ts")) { - sourceFile.flags = 1024 /* DeclarationFile */; + var syntacticDiagnostics; + var scanner; + var token; + var syntaxCursor; + var contextFlags; + var parseErrorBeforeNextFinishedNode; + var sourceFile; + return parseSourceFile(sourceText, setParentNodes); + function parseSourceFile(text, setParentNodes) { + sourceText = text; + parsingContext = 0; + identifiers = {}; + lineStarts = undefined; + syntacticDiagnostics = undefined; + contextFlags = 0; + parseErrorBeforeNextFinishedNode = false; + sourceFile = createNode(207 /* SourceFile */, 0); + sourceFile.referenceDiagnostics = []; + sourceFile.parseDiagnostics = []; + sourceFile.semanticDiagnostics = []; + scanner = ts.createScanner(languageVersion, true, sourceText, scanError); + token = nextToken(); + sourceFile.flags = ts.fileExtensionIs(filename, ".d.ts") ? 1024 /* DeclarationFile */ : 0; + sourceFile.end = sourceText.length; + sourceFile.filename = ts.normalizePath(filename); + sourceFile.text = sourceText; + sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; + sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; + sourceFile.getLineStarts = getLineStarts; + sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; + sourceFile.update = update; + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); + ts.Debug.assert(token === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = parseTokenNode(); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.languageVersion = languageVersion; + sourceFile.identifiers = identifiers; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; } - sourceFile.end = sourceText.length; - sourceFile.filename = ts.normalizePath(filename); - sourceFile.text = sourceText; - sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; - sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; - sourceFile.getLineStarts = getLineStarts; - sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; - sourceFile.referenceDiagnostics = []; - sourceFile.parseDiagnostics = []; - sourceFile.grammarDiagnostics = []; - sourceFile.semanticDiagnostics = []; - processReferenceComments(); - var scanner = ts.createScanner(languageVersion, true, sourceText, scanError); - var token = nextToken(); - sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); - ts.Debug.assert(token === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); - sourceFile.externalModuleIndicator = getExternalModuleIndicator(); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.languageVersion = languageVersion; - sourceFile.identifiers = identifiers; - if (setParentNodes) { - fixupParentReferences(sourceFile); + function update(newText, textChangeRange) { + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return parseSourceFile(newText, true); + } + syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(textChangeRange); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(sourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta); + var result = parseSourceFile(newText, true); + syntaxCursor = undefined; + return result; + } + function updateTokenPositionsAndMarkElements(node, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + visitNode(node); + function visitNode(child) { + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, delta); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + return; + } + } + function visitArray(array) { + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, delta); + } + else { + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + } + } + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function moveElementEntirelyPastChangeRange(element, delta) { + if (element.length) { + visitArray(element); + } + else { + visitNode(element); + } + function visitNode(node) { + node._children = undefined; + node.pos += delta; + node.end += delta; + forEachChild(node, visitNode, visitArray); + } + function visitArray(array) { + array.pos += delta; + array.end += delta; + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + } + function extendToAffectedRange(changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } } - return sourceFile; function setContextFlag(val, flag) { if (val) { contextFlags |= flag; @@ -3426,9 +3762,9 @@ var ts; } parseErrorBeforeNextFinishedNode = true; } - function scanError(message) { + function scanError(message, length) { var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, 0, message); + parseErrorAtPosition(pos, length || 0, message); } function getNodePos() { return scanner.getStartPos(); @@ -3480,13 +3816,13 @@ var ts; } return inStrictModeContext() ? token > 109 /* LastFutureReservedWord */ : token > 100 /* LastReservedWord */; } - function parseExpected(kind, diagnosticMessage, arg0) { + function parseExpected(kind, diagnosticMessage) { if (token === kind) { nextToken(); return true; } if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage, arg0); + parseErrorAtCurrentToken(diagnosticMessage); } else { parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); @@ -3514,7 +3850,7 @@ var ts; } return token === 15 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } - function parseSemicolon(diagnosticMessage) { + function parseSemicolon() { if (canParseSemicolon()) { if (token === 22 /* SemicolonToken */) { nextToken(); @@ -3522,7 +3858,7 @@ var ts; return true; } else { - return parseExpected(22 /* SemicolonToken */, diagnosticMessage); + return parseExpected(22 /* SemicolonToken */); } } function createNode(kind, pos) { @@ -3623,14 +3959,18 @@ var ts; function canFollowModifier() { return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); } - function isListElement(kind, inErrorRecovery) { - switch (kind) { + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { case 0 /* SourceElements */: case 1 /* ModuleElements */: return isSourceElement(inErrorRecovery); case 2 /* BlockStatements */: case 4 /* SwitchClauseStatements */: - return isStatement(inErrorRecovery); + return isStartOfStatement(inErrorRecovery); case 3 /* SwitchClauses */: return token === 66 /* CaseKeyword */ || token === 72 /* DefaultKeyword */; case 5 /* TypeMembers */: @@ -3648,13 +3988,13 @@ var ts; case 9 /* VariableDeclarations */: return isIdentifierOrPattern(); case 11 /* ArrayBindingElements */: - return token === 23 /* CommaToken */ || isIdentifierOrPattern(); + return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isIdentifierOrPattern(); case 16 /* TypeParameters */: return isIdentifier(); case 12 /* ArgumentExpressions */: return token === 23 /* CommaToken */ || isStartOfExpression(); case 14 /* ArrayLiteralMembers */: - return token === 23 /* CommaToken */ || isStartOfExpression(); + return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isStartOfExpression(); case 15 /* Parameters */: return isStartOfParameter(); case 17 /* TypeArguments */: @@ -3741,7 +4081,7 @@ var ts; var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { - var element = parseElement(); + var element = parseListElement(kind, parseElement); result.push(element); if (checkForStrictMode && !inStrictModeContext()) { if (ts.isPrologueDirective(element)) { @@ -3765,6 +4105,183 @@ var ts; parsingContext = saveParsingContext; return result; } + function parseListElement(kind, parseElement) { + var node = currentNode(kind); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.parserContextFlags & 31 /* ParserGeneratedFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 1 /* ModuleElements */: + return isReusableModuleElement(node); + case 6 /* ClassMembers */: + return isReusableClassMember(node); + case 3 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 2 /* BlockStatements */: + case 4 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 7 /* EnumMembers */: + return isReusableEnumMember(node); + case 5 /* TypeMembers */: + return isReusableTypeMember(node); + case 9 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 15 /* Parameters */: + return isReusableParameter(node); + case 19 /* HeritageClauses */: + case 8 /* TypeReferences */: + case 16 /* TypeParameters */: + case 18 /* TupleElementTypes */: + case 17 /* TypeArguments */: + case 12 /* ArgumentExpressions */: + case 13 /* ObjectLiteralMembers */: + } + return false; + } + function isReusableModuleElement(node) { + if (node) { + switch (node.kind) { + case 197 /* ImportDeclaration */: + case 198 /* ExportAssignment */: + case 191 /* ClassDeclaration */: + case 192 /* InterfaceDeclaration */: + case 195 /* ModuleDeclaration */: + case 194 /* EnumDeclaration */: + case 190 /* FunctionDeclaration */: + case 171 /* VariableStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 173 /* ExpressionStatement */: + case 185 /* ThrowStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 172 /* EmptyStatement */: + case 186 /* TryStatement */: + case 184 /* LabeledStatement */: + case 175 /* DoStatement */: + case 187 /* DebuggerStatement */: + return true; + } + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 129 /* Constructor */: + case 134 /* IndexSignature */: + case 128 /* MethodDeclaration */: + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + case 126 /* PropertyDeclaration */: + return true; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 200 /* CaseClause */: + case 201 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 190 /* FunctionDeclaration */: + case 171 /* VariableStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 173 /* ExpressionStatement */: + case 185 /* ThrowStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 172 /* EmptyStatement */: + case 186 /* TryStatement */: + case 184 /* LabeledStatement */: + case 175 /* DoStatement */: + case 187 /* DebuggerStatement */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 206 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 133 /* ConstructSignature */: + case 127 /* MethodSignature */: + case 134 /* IndexSignature */: + case 125 /* PropertySignature */: + case 132 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 188 /* VariableDeclaration */) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + return node.kind === 124 /* Parameter */; + } function abortParsingListOrMoveToNextToken(kind) { parseErrorAtCurrentToken(parsingContextErrors(kind)); if (isInSomeParsingContext()) { @@ -3781,7 +4298,7 @@ var ts; var commaStart = -1; while (true) { if (isListElement(kind, false)) { - result.push(parseElement()); + result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(23 /* CommaToken */)) { continue; @@ -3860,7 +4377,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(168 /* TemplateSpan */); + var span = createNode(169 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 15 /* CloseBraceToken */) { @@ -4026,7 +4543,8 @@ var ts; nextToken(); return token === 51 /* ColonToken */ || token === 23 /* CommaToken */ || token === 19 /* CloseBracketToken */; } - function parseIndexSignatureDeclaration(fullStart, modifiers) { + function parseIndexSignatureDeclaration(modifiers) { + var fullStart = modifiers ? modifiers.pos : scanner.getStartPos(); var node = createNode(134 /* IndexSignature */, fullStart); setModifiers(node, modifiers); node.parameters = parseBracketedList(15 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); @@ -4062,9 +4580,21 @@ var ts; case 18 /* OpenBracketToken */: return true; default: + if (ts.isModifier(token)) { + var result = lookAhead(isStartOfIndexSignatureDeclaration); + if (result) { + return result; + } + } return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); } } + function isStartOfIndexSignatureDeclaration() { + while (ts.isModifier(token)) { + nextToken(); + } + return isIndexSignature(); + } function isTypeMemberWithLiteralPropertyName() { nextToken(); return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */ || token === 50 /* QuestionToken */ || token === 51 /* ColonToken */ || canParseSemicolon(); @@ -4075,7 +4605,7 @@ var ts; case 24 /* LessThanToken */: return parseSignatureMember(132 /* CallSignature */); case 18 /* OpenBracketToken */: - return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined) : parsePropertyOrMethodSignature(); + return isIndexSignature() ? parseIndexSignatureDeclaration(undefined) : parsePropertyOrMethodSignature(); case 87 /* NewKeyword */: if (lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(133 /* ConstructSignature */); @@ -4084,11 +4614,21 @@ var ts; case 7 /* NumericLiteral */: return parsePropertyOrMethodSignature(); default: + if (ts.isModifier(token)) { + var result = tryParse(parseIndexSignatureWithModifiers); + if (result) { + return result; + } + } if (isIdentifierOrKeyword()) { return parsePropertyOrMethodSignature(); } } } + function parseIndexSignatureWithModifiers() { + var modifiers = parseModifiers(); + return isIndexSignature() ? parseIndexSignatureDeclaration(modifiers) : undefined; + } function isStartOfConstructSignature() { nextToken(); return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */; @@ -4445,7 +4985,7 @@ var ts; if (token === 14 /* OpenBraceToken */) { return parseFunctionBlock(false, false); } - if (isStatement(true) && !isStartOfExpressionStatement() && token !== 82 /* FunctionKeyword */) { + if (isStartOfStatement(true) && !isStartOfExpressionStatement() && token !== 82 /* FunctionKeyword */) { return parseFunctionBlock(false, true); } return parseAssignmentExpressionOrHigher(); @@ -4720,16 +5260,16 @@ var ts; } function parsePrimaryExpression() { switch (token) { + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); case 92 /* ThisKeyword */: case 90 /* SuperKeyword */: case 88 /* NullKeyword */: case 94 /* TrueKeyword */: case 79 /* FalseKeyword */: return parseTokenNode(); - case 7 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 10 /* NoSubstitutionTemplateLiteral */: - return parseLiteralNode(); case 16 /* OpenParenToken */: return parseParenthesizedExpression(); case 18 /* OpenBracketToken */: @@ -4759,10 +5299,16 @@ var ts; return finishNode(node); } function parseAssignmentExpressionOrOmittedExpression() { - return token === 23 /* CommaToken */ ? createNode(167 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); + return token === 23 /* CommaToken */ ? createNode(168 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); + } + function parseSpreadElement() { + var node = createNode(167 /* SpreadElementExpression */); + parseExpected(21 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } function parseArrayLiteralElement() { - return parseAssignmentExpressionOrOmittedExpression(); + return token === 21 /* DotDotDotToken */ ? parseSpreadElement() : parseAssignmentExpressionOrOmittedExpression(); } function parseArgumentExpression() { return allowInAnd(parseAssignmentExpressionOrOmittedExpression); @@ -4776,21 +5322,30 @@ var ts; parseExpected(19 /* CloseBracketToken */); return finishNode(node); } + function tryParseAccessorDeclaration(fullStart, modifiers) { + if (parseContextualModifier(114 /* GetKeyword */)) { + return parseAccessorDeclaration(130 /* GetAccessor */, fullStart, modifiers); + } + else if (parseContextualModifier(118 /* SetKeyword */)) { + return parseAccessorDeclaration(131 /* SetAccessor */, fullStart, modifiers); + } + return undefined; + } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); - var initialToken = token; - if (parseContextualModifier(114 /* GetKeyword */) || parseContextualModifier(118 /* SetKeyword */)) { - var kind = initialToken === 114 /* GetKeyword */ ? 130 /* GetAccessor */ : 131 /* SetAccessor */; - return parseAccessorDeclaration(kind, fullStart, undefined); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } var asteriskToken = parseOptionalToken(35 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); var nameToken = token; var propertyName = parsePropertyName(); - if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, undefined, asteriskToken, propertyName, undefined, true); - } var questionToken = parseOptionalToken(50 /* QuestionToken */); + if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, propertyName, questionToken); + } if ((token === 23 /* CommaToken */ || token === 15 /* CloseBraceToken */) && tokenIsIdentifier) { var shorthandDeclaration = createNode(205 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -4838,9 +5393,9 @@ var ts; } return finishNode(node); } - function parseBlock(kind, ignoreMissingOpenBrace, checkForStrictMode) { - var node = createNode(kind); - if (parseExpected(14 /* OpenBraceToken */) || ignoreMissingOpenBrace) { + function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { + var node = createNode(170 /* Block */); + if (parseExpected(14 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(2 /* BlockStatements */, checkForStrictMode, parseStatement); parseExpected(15 /* CloseBraceToken */); } @@ -4849,20 +5404,20 @@ var ts; } return finishNode(node); } - function parseFunctionBlock(allowYield, ignoreMissingOpenBrace) { + function parseFunctionBlock(allowYield, ignoreMissingOpenBrace, diagnosticMessage) { var savedYieldContext = inYieldContext(); setYieldContext(allowYield); - var block = parseBlock(169 /* Block */, ignoreMissingOpenBrace, true); + var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); setYieldContext(savedYieldContext); return block; } function parseEmptyStatement() { - var node = createNode(171 /* EmptyStatement */); + var node = createNode(172 /* EmptyStatement */); parseExpected(22 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(173 /* IfStatement */); + var node = createNode(174 /* IfStatement */); parseExpected(83 /* IfKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4872,7 +5427,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(174 /* DoStatement */); + var node = createNode(175 /* DoStatement */); parseExpected(74 /* DoKeyword */); node.statement = parseStatement(); parseExpected(99 /* WhileKeyword */); @@ -4883,7 +5438,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(175 /* WhileStatement */); + var node = createNode(176 /* WhileStatement */); parseExpected(99 /* WhileKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4895,41 +5450,26 @@ var ts; var pos = getNodePos(); parseExpected(81 /* ForKeyword */); parseExpected(16 /* OpenParenToken */); + var initializer = undefined; if (token !== 22 /* SemicolonToken */) { - if (parseOptional(97 /* VarKeyword */)) { - var declarations = disallowInAnd(parseVariableDeclarationList); - } - else if (parseOptional(103 /* LetKeyword */)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), 2048 /* Let */); - } - else if (parseOptional(69 /* ConstKeyword */)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), 4096 /* Const */); + if (token === 97 /* VarKeyword */ || token === 103 /* LetKeyword */ || token === 69 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(true); } else { - var varOrInit = disallowInAnd(parseExpression); + initializer = disallowInAnd(parseExpression); } } var forOrForInStatement; if (parseOptional(85 /* InKeyword */)) { - var forInStatement = createNode(177 /* ForInStatement */, pos); - if (declarations) { - forInStatement.declarations = declarations; - } - else { - forInStatement.variable = varOrInit; - } + var forInStatement = createNode(178 /* ForInStatement */, pos); + forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); forOrForInStatement = forInStatement; } else { - var forStatement = createNode(176 /* ForStatement */, pos); - if (declarations) { - forStatement.declarations = declarations; - } - if (varOrInit) { - forStatement.initializer = varOrInit; - } + var forStatement = createNode(177 /* ForStatement */, pos); + forStatement.initializer = initializer; parseExpected(22 /* SemicolonToken */); if (token !== 22 /* SemicolonToken */ && token !== 17 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); @@ -4946,7 +5486,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 179 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */); + parseExpected(kind === 180 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -4954,7 +5494,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(180 /* ReturnStatement */); + var node = createNode(181 /* ReturnStatement */); parseExpected(89 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -4963,7 +5503,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(181 /* WithStatement */); + var node = createNode(182 /* WithStatement */); parseExpected(100 /* WithKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4990,7 +5530,7 @@ var ts; return token === 66 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(182 /* SwitchStatement */); + var node = createNode(183 /* SwitchStatement */); parseExpected(91 /* SwitchKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -5001,26 +5541,23 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(184 /* ThrowStatement */); + var node = createNode(185 /* ThrowStatement */); parseExpected(93 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(185 /* TryStatement */); - node.tryBlock = parseTokenAndBlock(95 /* TryKeyword */); + var node = createNode(186 /* TryStatement */); + parseExpected(95 /* TryKeyword */); + node.tryBlock = parseBlock(false, false); node.catchClause = token === 67 /* CatchKeyword */ ? parseCatchClause() : undefined; - node.finallyBlock = !node.catchClause || token === 80 /* FinallyKeyword */ ? parseTokenAndBlock(80 /* FinallyKeyword */) : undefined; + if (!node.catchClause || token === 80 /* FinallyKeyword */) { + parseExpected(80 /* FinallyKeyword */); + node.finallyBlock = parseBlock(false, false); + } return finishNode(node); } - function parseTokenAndBlock(token) { - var pos = getNodePos(); - parseExpected(token); - var result = parseBlock(token === 95 /* TryKeyword */ ? 186 /* TryBlock */ : 187 /* FinallyBlock */, false, false); - result.pos = pos; - return result; - } function parseCatchClause() { var result = createNode(203 /* CatchClause */); parseExpected(67 /* CatchKeyword */); @@ -5028,11 +5565,11 @@ var ts; result.name = parseIdentifier(); result.type = parseTypeAnnotation(); parseExpected(17 /* CloseParenToken */); - result.block = parseBlock(169 /* Block */, false, false); + result.block = parseBlock(false, false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(188 /* DebuggerStatement */); + var node = createNode(187 /* DebuggerStatement */); parseExpected(71 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -5041,19 +5578,25 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 64 /* Identifier */ && parseOptional(51 /* ColonToken */)) { - var labeledStatement = createNode(183 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(184 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(172 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(173 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStatement(inErrorRecovery) { + function isStartOfStatement(inErrorRecovery) { + if (ts.isModifier(token)) { + var result = lookAhead(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return true; + } + } switch (token) { case 22 /* SemicolonToken */: return !inErrorRecovery; @@ -5109,7 +5652,7 @@ var ts; function parseStatement() { switch (token) { case 14 /* OpenBraceToken */: - return parseBlock(169 /* Block */, false, false); + return parseBlock(false, false); case 97 /* VarKeyword */: case 69 /* ConstKeyword */: return parseVariableStatement(scanner.getStartPos(), undefined); @@ -5126,9 +5669,9 @@ var ts; case 81 /* ForKeyword */: return parseForOrForInStatement(); case 70 /* ContinueKeyword */: - return parseBreakOrContinueStatement(178 /* ContinueStatement */); + return parseBreakOrContinueStatement(179 /* ContinueStatement */); case 65 /* BreakKeyword */: - return parseBreakOrContinueStatement(179 /* BreakStatement */); + return parseBreakOrContinueStatement(180 /* BreakStatement */); case 89 /* ReturnKeyword */: return parseReturnStatement(); case 100 /* WithKeyword */: @@ -5148,21 +5691,50 @@ var ts; return parseVariableStatement(scanner.getStartPos(), undefined); } default: + if (ts.isModifier(token)) { + var result = tryParse(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return result; + } + } return parseExpressionOrLabeledStatement(); } } - function parseFunctionBlockOrSemicolon(isGenerator) { - if (token === 14 /* OpenBraceToken */) { - return parseFunctionBlock(isGenerator, false); + function parseVariableStatementOrFunctionDeclarationWithModifiers() { + var start = scanner.getStartPos(); + var modifiers = parseModifiers(); + switch (token) { + case 69 /* ConstKeyword */: + var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); + if (nextTokenIsEnum) { + return undefined; + } + return parseVariableStatement(start, modifiers); + case 103 /* LetKeyword */: + if (!isLetDeclaration()) { + return undefined; + } + return parseVariableStatement(start, modifiers); + case 97 /* VarKeyword */: + return parseVariableStatement(start, modifiers); + case 82 /* FunctionKeyword */: + return parseFunctionDeclaration(start, modifiers); } - parseSemicolon(ts.Diagnostics.or_expected); return undefined; } + function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { + if (token !== 14 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(isGenerator, false, diagnosticMessage); + } function parseArrayBindingElement() { if (token === 23 /* CommaToken */) { - return createNode(167 /* OmittedExpression */); + return createNode(168 /* OmittedExpression */); } var node = createNode(146 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); @@ -5208,40 +5780,37 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(189 /* VariableDeclaration */); + var node = createNode(188 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); node.initializer = parseInitializer(false); return finishNode(node); } - function setFlag(nodes, flag) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - node.flags |= flag; - if (node.name && ts.isBindingPattern(node.name)) { - setFlag(node.name.elements, flag); - } - } - return nodes; - } - function parseVariableDeclarationList() { - return parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); - } - function parseVariableStatement(fullStart, modifiers) { - var node = createNode(170 /* VariableStatement */, fullStart); - setModifiers(node, modifiers); - if (token === 103 /* LetKeyword */) { - node.flags |= 2048 /* Let */; - } - else if (token === 69 /* ConstKeyword */) { - node.flags |= 4096 /* Const */; - } - else { - ts.Debug.assert(token === 97 /* VarKeyword */); + function parseVariableDeclarationList(disallowIn) { + var node = createNode(189 /* VariableDeclarationList */); + switch (token) { + case 97 /* VarKeyword */: + break; + case 103 /* LetKeyword */: + node.flags |= 2048 /* Let */; + break; + case 69 /* ConstKeyword */: + node.flags |= 4096 /* Const */; + break; + default: + ts.Debug.fail(); } nextToken(); - node.declarations = allowInAnd(parseVariableDeclarationList); - setFlag(node.declarations, node.flags); + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(disallowIn); + node.declarations = parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + return finishNode(node); + } + function parseVariableStatement(fullStart, modifiers) { + var node = createNode(171 /* VariableStatement */, fullStart); + setModifiers(node, modifiers); + node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return finishNode(node); } @@ -5252,7 +5821,7 @@ var ts; node.asteriskToken = parseOptionalToken(35 /* AsteriskToken */); node.name = parseIdentifier(); fillSignature(51 /* ColonToken */, !!node.asteriskToken, false, node); - node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken); + node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(pos, modifiers) { @@ -5260,17 +5829,17 @@ var ts; setModifiers(node, modifiers); parseExpected(112 /* ConstructorKeyword */); fillSignature(51 /* ColonToken */, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false); + node.body = parseFunctionBlockOrSemicolon(false, ts.Diagnostics.or_expected); return finishNode(node); } - function parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, requireBlock) { + function parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(128 /* MethodDeclaration */, fullStart); setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; fillSignature(51 /* ColonToken */, !!asteriskToken, false, method); - method.body = requireBlock ? parseFunctionBlock(!!asteriskToken, false) : parseFunctionBlockOrSemicolon(!!asteriskToken); + method.body = parseFunctionBlockOrSemicolon(!!asteriskToken, diagnosticMessage); return finishNode(method); } function parsePropertyOrMethodDeclaration(fullStart, modifiers) { @@ -5278,7 +5847,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50 /* QuestionToken */); if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, false); + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { var property = createNode(126 /* PropertyDeclaration */, fullStart); @@ -5360,17 +5929,15 @@ var ts; function parseClassElement() { var fullStart = getNodePos(); var modifiers = parseModifiers(); - if (parseContextualModifier(114 /* GetKeyword */)) { - return parseAccessorDeclaration(130 /* GetAccessor */, fullStart, modifiers); - } - if (parseContextualModifier(118 /* SetKeyword */)) { - return parseAccessorDeclaration(131 /* SetAccessor */, fullStart, modifiers); + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } if (token === 112 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, modifiers); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, modifiers); + return parseIndexSignatureDeclaration(modifiers); } if (isIdentifierOrKeyword() || token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */ || token === 35 /* AsteriskToken */ || token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, modifiers); @@ -5606,7 +6173,7 @@ var ts; } } function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStatement(inErrorRecovery); + return isDeclarationStart() || isStartOfStatement(inErrorRecovery); } function parseSourceElement() { return parseSourceElementOrModuleElement(); @@ -5617,7 +6184,7 @@ var ts; function parseSourceElementOrModuleElement() { return isDeclarationStart() ? parseDeclaration() : parseStatement(); } - function processReferenceComments() { + function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(languageVersion, false, sourceText); var referencedFiles = []; var amdDependencies = []; @@ -5664,10 +6231,9 @@ var ts; sourceFile.amdDependencies = amdDependencies; sourceFile.amdModuleName = amdModuleName; } - function getExternalModuleIndicator() { - return ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ || node.kind === 197 /* ImportDeclaration */ && node.moduleReference.kind === 199 /* ExternalModuleReference */ || node.kind === 198 /* ExportAssignment */ ? node : undefined; }); + function setExternalModuleIndicator(sourceFile) { + sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ || node.kind === 197 /* ImportDeclaration */ && node.moduleReference.kind === 199 /* ExternalModuleReference */ || node.kind === 198 /* ExportAssignment */ ? node : undefined; }); } - var syntacticDiagnostics; function getSyntacticDiagnostics() { if (syntacticDiagnostics === undefined) { syntacticDiagnostics = sourceFile.referenceDiagnostics.concat(sourceFile.parseDiagnostics); @@ -5710,225 +6276,6 @@ var ts; return token >= 52 /* FirstAssignment */ && token <= 63 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; - function createProgram(rootNames, options, host) { - var program; - var files = []; - var filesByName = {}; - var errors = []; - var seenNoDefaultLib = options.noLib; - var commonSourceDirectory; - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { - processRootFile(host.getDefaultLibFilename(options), true); - } - verifyCompilerOptions(); - errors.sort(ts.compareDiagnostics); - program = { - getSourceFile: getSourceFile, - getSourceFiles: function () { return files; }, - getCompilerOptions: function () { return options; }, - getCompilerHost: function () { return host; }, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeChecker: function (fullTypeCheckMode) { return ts.createTypeChecker(program, fullTypeCheckMode); }, - getCommonSourceDirectory: function () { return commonSourceDirectory; } - }; - return program; - function getSourceFile(filename) { - filename = host.getCanonicalFileName(filename); - return ts.hasProperty(filesByName, filename) ? filesByName[filename] : undefined; - } - function getDiagnostics(sourceFile) { - return sourceFile ? ts.filter(errors, function (e) { return e.file === sourceFile; }) : errors; - } - function getGlobalDiagnostics() { - return ts.filter(errors, function (e) { return !e.file; }); - } - function hasExtension(filename) { - return ts.getBaseFilename(filename).indexOf(".") >= 0; - } - function processRootFile(filename, isDefaultLib) { - processSourceFile(ts.normalizePath(filename), isDefaultLib); - } - function processSourceFile(filename, isDefaultLib, refFile, refPos, refEnd) { - if (refEnd !== undefined && refPos !== undefined) { - var start = refPos; - var length = refEnd - refPos; - } - var diagnostic; - if (hasExtension(filename)) { - if (!options.allowNonTsExtensions && !ts.fileExtensionIs(filename, ".ts")) { - diagnostic = ts.Diagnostics.File_0_must_have_extension_ts_or_d_ts; - } - else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - } - else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - } - } - else { - if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = ts.Diagnostics.File_0_not_found; - filename += ".ts"; - } - } - if (diagnostic) { - if (refFile) { - errors.push(ts.createFileDiagnostic(refFile, start, length, diagnostic, filename)); - } - else { - errors.push(ts.createCompilerDiagnostic(diagnostic, filename)); - } - } - } - function findSourceFile(filename, isDefaultLib, refFile, refStart, refLength) { - var canonicalName = host.getCanonicalFileName(filename); - if (ts.hasProperty(filesByName, canonicalName)) { - return getSourceFileFromCache(filename, canonicalName, false); - } - else { - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); - var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { - return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); - } - var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, function (hostErrorMessage) { - if (refFile) { - errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - }); - if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; - if (!options.noResolve) { - var basePath = ts.getDirectoryPath(filename); - processReferencedFiles(file, basePath); - processImportedModules(file, basePath); - } - if (isDefaultLib) { - files.unshift(file); - } - else { - files.push(file); - } - ts.forEach(file.getSyntacticDiagnostics(), function (e) { - errors.push(e); - }); - } - } - return file; - function getSourceFileFromCache(filename, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; - if (file && host.useCaseSensitiveFileNames()) { - var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; - if (canonicalName !== sourceFileName) { - errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); - } - } - return file; - } - } - function processReferencedFiles(file, basePath) { - ts.forEach(file.referencedFiles, function (ref) { - var referencedFilename = ts.isRootedDiskPath(ref.filename) ? ref.filename : ts.combinePaths(basePath, ref.filename); - processSourceFile(ts.normalizePath(referencedFilename), false, file, ref.pos, ref.end); - }); - } - function processImportedModules(file, basePath) { - ts.forEach(file.statements, function (node) { - if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { - var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - var searchPath = basePath; - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { - break; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - } - } - else if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { - forEachChild(node.body, function (node) { - if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { - var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - var searchName = ts.normalizePath(ts.combinePaths(basePath, moduleName)); - var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); - if (!tsFile) { - findModuleSourceFile(searchName + ".d.ts", nameLiteral); - } - } - } - }); - } - }); - function findModuleSourceFile(filename, nameLiteral) { - return findSourceFile(filename, false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); - } - } - function verifyCompilerOptions() { - if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { - if (options.mapRoot) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - if (options.sourceRoot) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - return; - } - var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (firstExternalModule && options.module === 0 /* None */) { - var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); - var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); - var errorLength = externalModuleErrorSpan.end - errorStart; - errors.push(ts.createFileDiagnostic(firstExternalModule, errorStart, errorLength, ts.Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); - } - if (options.outDir || options.sourceRoot || (options.mapRoot && (!options.out || firstExternalModule !== undefined))) { - var commonPathComponents; - ts.forEach(files, function (sourceFile) { - if (!(sourceFile.flags & 1024 /* DeclarationFile */) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { - var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); - sourcePathComponents.pop(); - if (commonPathComponents) { - for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { - if (i === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; - } - commonPathComponents.length = i; - break; - } - } - if (sourcePathComponents.length < commonPathComponents.length) { - commonPathComponents.length = sourcePathComponents.length; - } - } - else { - commonPathComponents = sourcePathComponents; - } - } - }); - commonSourceDirectory = ts.getNormalizedPathFromPathComponents(commonPathComponents); - if (commonSourceDirectory) { - commonSourceDirectory += ts.directorySeparator; - } - } - } - } - ts.createProgram = createProgram; })(ts || (ts = {})); var ts; (function (ts) { @@ -6080,7 +6427,7 @@ var ts; if (symbolKind & 1536 /* Namespace */) { exportKind |= 4194304 /* ExportNamespace */; } - if (node.flags & 1 /* Export */ || (node.kind !== 197 /* ImportDeclaration */ && isAmbientContext(container))) { + if (ts.getCombinedNodeFlags(node) & 1 /* Export */ || (node.kind !== 197 /* ImportDeclaration */ && isAmbientContext(container))) { if (exportKind) { var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); @@ -6104,9 +6451,7 @@ var ts; parent = node; if (symbolKind & 262128 /* IsContainer */) { container = node; - ts.Debug.assert(container.nextContainer === undefined); if (lastContainer) { - ts.Debug.assert(lastContainer.nextContainer === undefined); lastContainer.nextContainer = container; } lastContainer = container; @@ -6234,12 +6579,12 @@ var ts; case 124 /* Parameter */: bindParameter(node); break; - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: if (ts.isBindingPattern(node.name)) { bindChildren(node, 0, false); } - else if (node.flags & 6144 /* BlockScoped */) { + else if (ts.getCombinedNodeFlags(node) & 6144 /* BlockScoped */) { bindBlockScopedVariableDeclaration(node); } else { @@ -6323,13 +6668,11 @@ var ts; bindAnonymousDeclaration(node, 512 /* ValueModule */, '"' + ts.removeFileExtension(node.filename) + '"', true); break; } - case 169 /* Block */: - case 186 /* TryBlock */: + case 170 /* Block */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 182 /* SwitchStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 183 /* SwitchStatement */: bindChildren(node, 0, true); break; default: @@ -6355,3434 +6698,27 @@ var ts; ts.bindSourceFile = bindSourceFile; })(ts || (ts = {})); var ts; -(function (ts) { - var indentStrings = ["", " "]; - function getIndentString(level) { - if (indentStrings[level] === undefined) { - indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; - } - return indentStrings[level]; - } - ts.getIndentString = getIndentString; - function getIndentSize() { - return indentStrings[1].length; - } - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!ts.isDeclarationFile(sourceFile)) { - if ((ts.isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { - return true; - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; - function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; - function write(s) { - if (s && s.length) { - if (lineStart) { - output += getIndentString(indent); - lineStart = false; - } - output += s; - } - } - function rawWrite(s) { - if (s !== undefined) { - if (lineStart) { - lineStart = false; - } - output += s; - } - } - function writeLiteral(s) { - if (s && s.length) { - write(s); - var lineStartsOfS = ts.computeLineStarts(s); - if (lineStartsOfS.length > 1) { - lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; - } - } - } - function writeLine() { - if (!lineStart) { - output += newLine; - lineCount++; - linePos = output.length; - lineStart = true; - } - } - function writeTextOfNode(sourceFile, node) { - write(ts.getSourceTextOfNodeFromSourceFile(sourceFile, node)); - } - return { - write: write, - rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, - writeLiteral: writeLiteral, - writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, - getIndent: function () { return indent; }, - getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } - }; - } - function getLineOfLocalPosition(currentSourceFile, pos) { - return currentSourceFile.getLineAndCharacterFromPosition(pos).line; - } - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { - writer.writeLine(); - } - } - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(currentSourceFile, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { - writer.write(" "); - } - else { - emitLeadingSpace = true; - } - }); - } - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); - var firstCommentLineIndent; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); - if (pos !== comment.pos) { - if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); - } - var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); - if (spacesToEmit > 0) { - var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); - writer.rawWrite(indentSizeSpaceString); - while (numberOfSingleSpacesToEmit) { - writer.rawWrite(" "); - numberOfSingleSpacesToEmit--; - } - } - else { - writer.rawWrite(""); - } - } - writeTrimmedCurrentLine(pos, nextLineStart); - pos = nextLineStart; - } - } - else { - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); - if (currentLineText) { - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - currentLineIndent++; - } - } - return currentLineIndent; - } - } - function getFirstConstructorWithBody(node) { - return ts.forEach(node.members, function (member) { - if (member.kind === 129 /* Constructor */ && member.body) { - return member; - } - }); - } - function getAllAccessorDeclarations(node, accessor) { - var firstAccessor; - var getAccessor; - var setAccessor; - if (accessor.name.kind === 122 /* ComputedPropertyName */) { - firstAccessor = accessor; - if (accessor.kind === 130 /* GetAccessor */) { - getAccessor = accessor; - } - else if (accessor.kind === 131 /* SetAccessor */) { - setAccessor = accessor; - } - else { - ts.Debug.fail("Accessor has wrong kind"); - } - } - else { - ts.forEach(node.members, function (member) { - if ((member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) && member.name.text === accessor.name.text && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { - if (!firstAccessor) { - firstAccessor = member; - } - if (member.kind === 130 /* GetAccessor */ && !getAccessor) { - getAccessor = member; - } - if (member.kind === 131 /* SetAccessor */ && !setAccessor) { - setAccessor = member; - } - } - }); - } - return { - firstAccessor: firstAccessor, - getAccessor: getAccessor, - setAccessor: setAccessor - }; - } - function getSourceFilePathInNewDir(sourceFile, program, newDirPath) { - var compilerHost = program.getCompilerHost(); - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, compilerHost.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), ""); - return ts.combinePaths(newDirPath, sourceFilePath); - } - function getOwnEmitOutputFilePath(sourceFile, program, extension) { - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outDir) { - var emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, program, compilerOptions.outDir)); - } - else { - var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.filename); - } - return emitOutputFilePathWithoutExtension + extension; - } - function writeFile(compilerHost, diagnostics, filename, data, writeByteOrderMark) { - compilerHost.writeFile(filename, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); - }); - } - function emitDeclarations(program, resolver, diagnostics, jsFilePath, root) { - var newLine = program.getCompilerHost().getNewLine(); - var compilerOptions = program.getCompilerOptions(); - var compilerHost = program.getCompilerHost(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var currentSourceFile; - var reportedDeclarationError = false; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { - } : writeJsDocComments; - var aliasDeclarationEmitInfo = []; - function createAndSetNewTextWriterWithSymbolWriter() { - var writer = createTextWriter(newLine); - writer.trackSymbol = trackSymbol; - writer.writeKeyword = writer.write; - writer.writeOperator = writer.write; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - return writer; - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsychronousImportDeclarations(importDeclarations) { - var oldWriter = writer; - ts.forEach(importDeclarations, function (aliasToWrite) { - var aliasEmitInfo = ts.forEach(aliasDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined; }); - if (aliasEmitInfo) { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - writeImportDeclaration(aliasToWrite); - aliasEmitInfo.asynchronousOutput = writer.getText(); - } - }); - setWriter(oldWriter); - } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsychronousImportDeclarations(symbolAccesibilityResult.aliasesToMakeVisible); - } - } - else { - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); - } - else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (type) { - emitType(type); - } - else { - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - emitType(signature.type); - } - else { - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); - } - } - function emitLines(nodes) { - for (var i = 0, n = nodes.length; i < n; i++) { - emitNode(nodes[i]); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var i = 0, n = nodes.length; i < n; i++) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(nodes[i]); - } - } - function emitCommaList(nodes, eachNodeEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); - emitComments(currentSourceFile, writer, jsDocComments, true, newLine, writeCommentRange); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 110 /* AnyKeyword */: - case 119 /* StringKeyword */: - case 117 /* NumberKeyword */: - case 111 /* BooleanKeyword */: - case 98 /* VoidKeyword */: - case 8 /* StringLiteral */: - return writeTextOfNode(currentSourceFile, type); - case 135 /* TypeReference */: - return emitTypeReference(type); - case 138 /* TypeQuery */: - return emitTypeQuery(type); - case 140 /* ArrayType */: - return emitArrayType(type); - case 141 /* TupleType */: - return emitTupleType(type); - case 142 /* UnionType */: - return emitUnionType(type); - case 143 /* ParenthesizedType */: - return emitParenType(type); - case 136 /* FunctionType */: - case 137 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 139 /* TypeLiteral */: - return emitTypeLiteral(type); - case 64 /* Identifier */: - return emitEntityName(type); - case 121 /* QualifiedName */: - return emitEntityName(type); - default: - ts.Debug.fail("Unknown type annotation: " + type.kind); - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 197 /* ImportDeclaration */ ? entityName.parent : enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - writeEntityName(entityName); - function writeEntityName(entityName) { - if (entityName.kind === 64 /* Identifier */) { - writeTextOfNode(currentSourceFile, entityName); - } - else { - var qualifiedName = entityName; - writeEntityName(qualifiedName.left); - write("."); - writeTextOfNode(currentSourceFile, qualifiedName.right); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentSourceFile = node; - enclosingDeclaration = node; - emitLines(node.statements); - } - function emitExportAssignment(node) { - write("export = "); - writeTextOfNode(currentSourceFile, node.exportName); - write(";"); - writeLine(); - } - function emitModuleElementDeclarationFlags(node) { - if (node.parent === currentSourceFile) { - if (node.flags & 1 /* Export */) { - write("export "); - } - if (node.kind !== 192 /* InterfaceDeclaration */) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32 /* Private */) { - write("private "); - } - else if (node.flags & 64 /* Protected */) { - write("protected "); - } - if (node.flags & 128 /* Static */) { - write("static "); - } - } - function emitImportDeclaration(node) { - var nodeEmitInfo = { - declaration: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - hasWritten: resolver.isDeclarationVisible(node) - }; - aliasDeclarationEmitInfo.push(nodeEmitInfo); - if (nodeEmitInfo.hasWritten) { - writeImportDeclaration(node); - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (node.flags & 1 /* Export */) { - write("export "); - } - write("import "); - writeTextOfNode(currentSourceFile, node.name); - write(" = "); - if (ts.isInternalModuleImportDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportDeclarationExpression(node)); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function emitModuleDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("module "); - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 196 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentSourceFile, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitTypeAliasDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentSourceFile, node.name); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - } - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function emitEnumDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentSourceFile, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); - var enumMemberValue = resolver.getEnumMemberValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(enumMemberValue.toString()); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 128 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || (node.parent.parent && node.parent.parent.kind === 139 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 128 /* MethodDeclaration */ || node.parent.kind === 127 /* MethodSignature */ || node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.kind === 132 /* CallSignature */ || node.parent.kind === 133 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.parent.kind) { - case 191 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 192 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 133 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 132 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.parent.parent.name - }; - } - } - } - function emitClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { - emitPropertyDeclaration(param); - } - }); - } - } - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("class "); - writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassBaseTypeNode(node); - if (baseTypeNode) { - emitHeritageClause([baseTypeNode], false); - } - emitHeritageClause(ts.getClassImplementedTypeNodes(node), true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitInterfaceDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitPropertyDeclaration(node) { - emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); - emitVariableDeclaration(node); - write(";"); - writeLine(); - } - function emitVariableDeclaration(node) { - if (node.kind !== 189 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { - writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && node.parent.kind === 139 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!(node.flags & 32 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (node.kind === 189 /* VariableDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } - else if (node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) { - if (node.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (node.type) { - write(": "); - emitType(node.type); - } - } - function emitVariableStatement(node) { - var hasDeclarationWithEmit = ts.forEach(node.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); - if (hasDeclarationWithEmit) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node)) { - write("let "); - } - else if (ts.isConst(node)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarations, emitVariableDeclaration); - write(";"); - writeLine(); - } - } - function emitAccessorDeclaration(node) { - var accessors = getAllAccessorDeclarations(node.parent, node); - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32 /* Private */)) { - var accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - var anotherAccessor = node.kind === 130 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 130 /* GetAccessor */ ? accessor.type : accessor.parameters[0].type; - } - } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 131 /* SetAccessor */) { - if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - typeName: accessorWithTypeAnnotation.name - }; - } - else { - if (accessorWithTypeAnnotation.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; - } - } - } - function emitFunctionDeclaration(node) { - if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 190 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 128 /* MethodDeclaration */) { - emitClassMemberDeclarationFlags(node); - } - if (node.kind === 190 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentSourceFile, node.name); - } - else if (node.kind === 129 /* Constructor */) { - write("constructor"); - } - else { - writeTextOfNode(currentSourceFile, node.name); - if (ts.hasQuestionToken(node)) { - write("?"); - } - } - emitSignatureDeclaration(node); - } - } - function emitSignatureDeclarationWithJsDocComments(node) { - emitJsDocComments(node); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - if (node.kind === 133 /* ConstructSignature */ || node.kind === 137 /* ConstructorType */) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 134 /* IndexSignature */) { - write("["); - } - else { - write("("); - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 134 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - var isFunctionTypeOrConstructorType = node.kind === 136 /* FunctionType */ || node.kind === 137 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 139 /* TypeLiteral */) { - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 129 /* Constructor */ && !(node.flags & 32 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 133 /* ConstructSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 132 /* CallSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 134 /* IndexSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - } - else if (node.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - write("_" + ts.indexOf(node.parent.parameters, node)); - } - else { - writeTextOfNode(currentSourceFile, node.name); - } - if (node.initializer || ts.hasQuestionToken(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.parent.kind === 139 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!(node.parent.flags & 32 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.parent.kind) { - case 129 /* Constructor */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - break; - case 133 /* ConstructSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 132 /* CallSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - function emitNode(node) { - switch (node.kind) { - case 129 /* Constructor */: - case 190 /* FunctionDeclaration */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - return emitFunctionDeclaration(node); - case 133 /* ConstructSignature */: - case 132 /* CallSignature */: - case 134 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* VariableStatement */: - return emitVariableStatement(node); - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 192 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 191 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 193 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 206 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 194 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 195 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 197 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 198 /* ExportAssignment */: - return emitExportAssignment(node); - case 207 /* SourceFile */: - return emitSourceFile(node); - } - } - var referencePathsOutput = ""; - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 1024 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile, compilerOptions) ? getOwnEmitOutputFilePath(referencedFile, program, ".d.ts") : ts.removeFileExtension(compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; - } - if (root) { - if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(program, root, fileReference); - if (referencedFile && ((referencedFile.flags & 1024 /* DeclarationFile */) || shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!isExternalModuleOrDeclarationFile(referencedFile)) { - addedGlobalFileReference = true; - } - } - }); - } - emitNode(root); - } - else { - var emittedReferencedFiles = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(program, sourceFile, fileReference); - if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitNode(sourceFile); - } - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - aliasDeclarationEmitInfo: aliasDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencePathsOutput: referencePathsOutput - }; - } - function getDeclarationDiagnostics(program, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); - emitDeclarations(program, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitFiles(resolver, targetSourceFile) { - var program = resolver.getProgram(); - var compilerHost = program.getCompilerHost(); - var compilerOptions = program.getCompilerOptions(); - var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; - var diagnostics = []; - var newLine = program.getCompilerHost().getNewLine(); - function emitJavaScript(jsFilePath, root) { - var writer = createTextWriter(newLine); - var write = writer.write; - var writeTextOfNode = writer.writeTextOfNode; - var writeLine = writer.writeLine; - var increaseIndent = writer.increaseIndent; - var decreaseIndent = writer.decreaseIndent; - var currentSourceFile; - var extendsEmitted = false; - var tempCount = 0; - var tempVariables; - var tempParameters; - var writeEmittedFiles = writeJavaScriptFile; - var emitLeadingComments = compilerOptions.removeComments ? function (node) { - } : emitLeadingDeclarationComments; - var emitTrailingComments = compilerOptions.removeComments ? function (node) { - } : emitTrailingDeclarationComments; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { - } : emitLeadingCommentsOfLocalPosition; - var detachedCommentsInfo; - var emitDetachedComments = compilerOptions.removeComments ? function (node) { - } : emitDetachedCommentsAtPosition; - var emitPinnedOrTripleSlashComments = compilerOptions.removeComments ? function (node) { - } : emitPinnedOrTripleSlashCommentsOfNode; - var writeComment = writeCommentRange; - var emit = emitNode; - var emitStart = function (node) { - }; - var emitEnd = function (node) { - }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { - }; - var scopeEmitEnd = function () { - }; - var sourceMapData; - function initializeEmitterWithSourceMaps() { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; - } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } - } - function recordSourceMapSpan(pos) { - var sourceLinePos = currentSourceFile.getLineAndCharacterFromPosition(pos); - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine != emittedLine || lastRecordedSourceMapSpan.emittedColumn != emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? program.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.filename); - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { - if (node.name) { - scopeName = node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings) { - if (typeof JSON !== "undefined") { - return JSON.stringify({ - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\"}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - writeFile(compilerHost, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings), false); - sourceMapDataList.push(sourceMapData); - writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFilename(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(getSourceFilePathInNewDir(root, program, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(program.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithMap(node) { - if (node) { - if (node.kind != 207 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNode(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNode(node); - } - } - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithMap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - writeFile(compilerHost, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); - } - function createTempVariable(location, forLoopVariable) { - var name = forLoopVariable ? "_i" : undefined; - while (true) { - if (name && resolver.isUnknownIdentifier(location, name)) { - break; - } - name = "_" + (tempCount < 25 ? String.fromCharCode(tempCount + (tempCount < 8 ? 0 : 1) + 97 /* a */) : tempCount - 25); - tempCount++; - } - var result = ts.createNode(64 /* Identifier */); - result.text = name; - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitTokenText(tokenKind, startPos, emitFn) { - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - return startPos + tokenString.length; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } - function emitCommaList(nodes, count) { - if (!(count >= 0)) { - count = nodes.length; - } - if (nodes) { - for (var i = 0; i < count; i++) { - if (i) { - write(", "); - } - emit(nodes[i]); - } - } - } - function emitMultiLineList(nodes) { - if (nodes) { - for (var i = 0; i < nodes.length; i++) { - if (i) { - write(","); - } - writeLine(); - emit(nodes[i]); - } - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(text) { - if (text.length <= 0) { - return false; - } - if (text.charCodeAt(1) === 66 /* B */ || text.charCodeAt(1) === 98 /* b */ || text.charCodeAt(1) === 79 /* O */ || text.charCodeAt(1) === 111 /* o */) { - return true; - } - return false; - } - function emitLiteral(node) { - var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; - if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { - write(node.text); - } - else { - write(text); - } - } - function getTemplateLiteralAsStringLiteral(node) { - return '"' + ts.escapeString(node.text) + '"'; - } - function emitTemplateExpression(node) { - if (compilerOptions.target >= 2 /* ES6 */) { - ts.forEachChild(node, emit); - return; - } - ts.Debug.assert(node.parent.kind !== 153 /* TaggedTemplateExpression */); - var emitOuterParens = ts.isExpression(node.parent) && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - emitLiteral(node.head); - ts.forEach(node.templateSpans, function (templateSpan) { - var needsParens = templateSpan.expression.kind !== 155 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; - write(" + "); - if (needsParens) { - write("("); - } - emit(templateSpan.expression); - if (needsParens) { - write(")"); - } - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - }); - if (emitOuterParens) { - write(")"); - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 151 /* CallExpression */: - case 152 /* NewExpression */: - return parent.expression === template; - case 155 /* ParenthesizedExpression */: - return false; - case 153 /* TaggedTemplateExpression */: - ts.Debug.fail("Path should be unreachable; tagged templates not supported pre-ES6."); - default: - return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; - } - } - function comparePrecedenceToBinaryPlus(expression) { - ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); - switch (expression.kind) { - case 163 /* BinaryExpression */: - switch (expression.operator) { - case 35 /* AsteriskToken */: - case 36 /* SlashToken */: - case 37 /* PercentToken */: - return 1 /* GreaterThan */; - case 33 /* PlusToken */: - return 0 /* EqualTo */; - default: - return -1 /* LessThan */; - } - case 164 /* ConditionalExpression */: - return -1 /* LessThan */; - default: - return 1 /* GreaterThan */; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function emitExpressionForPropertyName(node) { - if (node.kind === 8 /* StringLiteral */) { - emitLiteral(node); - } - else if (node.kind === 122 /* ComputedPropertyName */) { - emit(node.expression); - } - else { - write("\""); - if (node.kind === 7 /* NumericLiteral */) { - write(node.text); - } - else { - writeTextOfNode(currentSourceFile, node); - } - write("\""); - } - } - function isNotExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 124 /* Parameter */: - case 189 /* VariableDeclaration */: - case 146 /* BindingElement */: - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - case 204 /* PropertyAssignment */: - case 205 /* ShorthandPropertyAssignment */: - case 206 /* EnumMember */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - case 190 /* FunctionDeclaration */: - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - case 156 /* FunctionExpression */: - case 191 /* ClassDeclaration */: - case 192 /* InterfaceDeclaration */: - case 194 /* EnumDeclaration */: - case 195 /* ModuleDeclaration */: - case 197 /* ImportDeclaration */: - return parent.name === node; - case 179 /* BreakStatement */: - case 178 /* ContinueStatement */: - case 198 /* ExportAssignment */: - return false; - case 183 /* LabeledStatement */: - return node.parent.label === node; - case 203 /* CatchClause */: - return node.parent.name === node; - } - } - function emitExpressionIdentifier(node) { - var prefix = resolver.getExpressionNamePrefix(node); - if (prefix) { - write(prefix); - write("."); - } - writeTextOfNode(currentSourceFile, node); - } - function emitIdentifier(node) { - if (!node.parent) { - write(node.text); - } - else if (!isNotExpressionIdentifier(node)) { - emitExpressionIdentifier(node); - } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { - write("_this"); - } - else { - write("this"); - } - } - function emitSuper(node) { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 16 /* SuperInstance */) { - write("_super.prototype"); - } - else if (flags & 32 /* SuperStatic */) { - write("_super"); - } - else { - write("super"); - } - } - function emitObjectBindingPattern(node) { - write("{ "); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write("]"); - } - function emitArrayLiteral(node) { - if (node.flags & 256 /* MultiLine */) { - write("["); - increaseIndent(); - emitMultiLineList(node.elements); - emitTrailingCommaIfPresent(node.elements); - decreaseIndent(); - writeLine(); - write("]"); - } - else { - write("["); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write("]"); - } - } - function emitObjectLiteral(node) { - if (!node.properties.length) { - write("{}"); - } - else if (node.flags & 256 /* MultiLine */) { - write("{"); - increaseIndent(); - emitMultiLineList(node.properties); - if (compilerOptions.target >= 1 /* ES5 */) { - emitTrailingCommaIfPresent(node.properties); - } - decreaseIndent(); - writeLine(); - write("}"); - } - else { - write("{ "); - emitCommaList(node.properties); - if (compilerOptions.target >= 1 /* ES5 */) { - emitTrailingCommaIfPresent(node.properties); - } - write(" }"); - } - } - function emitComputedPropertyName(node) { - write("["); - emit(node.expression); - write("]"); - } - function emitMethod(node) { - if (!ts.isObjectLiteralMethod(node)) { - return; - } - emitLeadingComments(node); - emit(node.name); - if (compilerOptions.target < 2 /* ES6 */) { - write(": function "); - } - emitSignatureAndBody(node); - emitTrailingComments(node); - } - function emitPropertyAssignment(node) { - emitLeadingComments(node); - emit(node.name); - write(": "); - emit(node.initializer); - emitTrailingComments(node); - } - function emitShorthandPropertyAssignment(node) { - emitLeadingComments(node); - emit(node.name); - if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { - write(": "); - emitExpressionIdentifier(node.name); - } - emitTrailingComments(node); - } - function tryEmitConstantValue(node) { - var constantValue = resolver.getConstantValue(node); - if (constantValue !== undefined) { - var propertyName = node.kind === 149 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(constantValue.toString() + " /* " + propertyName + " */"); - return true; - } - return false; - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - write("."); - emit(node.name); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function emitCallExpression(node) { - var superCall = false; - if (node.expression.kind === 90 /* SuperKeyword */) { - write("_super"); - superCall = true; - } - else { - emit(node.expression); - superCall = node.expression.kind === 149 /* PropertyAccessExpression */ && node.expression.expression.kind === 90 /* SuperKeyword */; - } - if (superCall) { - write(".call("); - emitThis(node.expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitTaggedTemplateExpression(node) { - ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); - emit(node.tag); - write(" "); - emit(node.template); - } - function emitParenExpression(node) { - if (node.expression.kind === 154 /* TypeAssertionExpression */) { - var operand = node.expression.expression; - while (operand.kind == 154 /* TypeAssertionExpression */) { - operand = operand.expression; - } - if (operand.kind !== 161 /* PrefixUnaryExpression */ && operand.kind !== 160 /* VoidExpression */ && operand.kind !== 159 /* TypeOfExpression */ && operand.kind !== 158 /* DeleteExpression */ && operand.kind !== 162 /* PostfixUnaryExpression */ && operand.kind !== 152 /* NewExpression */ && !(operand.kind === 151 /* CallExpression */ && node.parent.kind === 152 /* NewExpression */) && !(operand.kind === 156 /* FunctionExpression */ && node.parent.kind === 151 /* CallExpression */)) { - emit(operand); - return; - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(73 /* DeleteKeyword */)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(98 /* VoidKeyword */)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(96 /* TypeOfKeyword */)); - write(" "); - emit(node.expression); - } - function emitPrefixUnaryExpression(node) { - write(ts.tokenToString(node.operator)); - if (node.operand.kind === 161 /* PrefixUnaryExpression */) { - var operand = node.operand; - if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { - write(" "); - } - else if (node.operator === 34 /* MinusToken */ && (operand.operator === 34 /* MinusToken */ || operand.operator === 39 /* MinusMinusToken */)) { - write(" "); - } - } - emit(node.operand); - } - function emitPostfixUnaryExpression(node) { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - function emitBinaryExpression(node) { - if (node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { - emitDestructuring(node); - } - else { - emit(node.left); - if (node.operator !== 23 /* CommaToken */) - write(" "); - write(ts.tokenToString(node.operator)); - write(" "); - emit(node.right); - } - } - function emitConditionalExpression(node) { - emit(node.condition); - write(" ? "); - emit(node.whenTrue); - write(" : "); - emit(node.whenFalse); - } - function emitBlock(node) { - emitToken(14 /* OpenBraceToken */, node.pos); - increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 196 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 195 /* ModuleDeclaration */); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 196 /* ModuleBlock */) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); - } - function emitEmbeddedStatement(node) { - if (node.kind === 169 /* Block */) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - var isArrowExpression = node.expression.kind === 157 /* ArrowFunction */; - emitLeadingComments(node); - if (isArrowExpression) - write("("); - emit(node.expression); - if (isArrowExpression) - write(")"); - write(";"); - emitTrailingComments(node); - } - function emitIfStatement(node) { - emitLeadingComments(node); - var endPos = emitToken(83 /* IfKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(75 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 173 /* IfStatement */) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - emitTrailingComments(node); - } - function emitDoStatement(node) { - write("do"); - emitEmbeddedStatement(node.statement); - if (node.statement.kind === 169 /* Block */) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - write("while ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitForStatement(node) { - var endPos = emitToken(81 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.declarations) { - if (node.declarations[0] && ts.isLet(node.declarations[0])) { - emitToken(103 /* LetKeyword */, endPos); - } - else if (node.declarations[0] && ts.isConst(node.declarations[0])) { - emitToken(69 /* ConstKeyword */, endPos); - } - else { - emitToken(97 /* VarKeyword */, endPos); - } - write(" "); - emitCommaList(node.declarations); - } - if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.iterator); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitForInStatement(node) { - var endPos = emitToken(81 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; - if (ts.isLet(decl)) { - emitToken(103 /* LetKeyword */, endPos); - } - else { - emitToken(97 /* VarKeyword */, endPos); - } - write(" "); - emit(decl); - } - } - else { - emit(node.variable); - } - write(" in "); - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.statement); - } - function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 179 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - emitLeadingComments(node); - emitToken(89 /* ReturnKeyword */, node.pos); - emitOptional(" ", node.expression); - write(";"); - emitTrailingComments(node); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(91 /* SwitchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - endPos = emitToken(17 /* CloseParenToken */, node.expression.end); - write(" "); - emitToken(14 /* OpenBraceToken */, endPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.clauses.end); - } - function isOnSameLine(node1, node2) { - return getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 200 /* CaseClause */) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && isOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(67 /* CatchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.name); - emitToken(17 /* CloseParenToken */, node.name.end); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(71 /* DebuggerKeyword */, node.pos); - write(";"); - } - function emitLabelledStatement(node) { - emit(node.label); - write(": "); - emit(node.statement); - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 195 /* ModuleDeclaration */); - return node; - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (node.flags & 1 /* Export */) { - var container = getContainingModule(node); - write(container ? resolver.getLocalNameOfContainer(container) : "exports"); - write("."); - } - emitNode(node.name); - emitEnd(node.name); - } - function emitDestructuring(root, value) { - var emitCount = 0; - var isDeclaration = (root.kind === 189 /* VariableDeclaration */ && !(root.flags & 1 /* Export */)) || root.kind === 124 /* Parameter */; - if (root.kind === 163 /* BinaryExpression */) { - emitAssignmentExpression(root); - } - else { - emitBindingElement(root, value); - } - function emitAssignment(name, value) { - if (emitCount++) { - write(", "); - } - if (name.parent && (name.parent.kind === 189 /* VariableDeclaration */ || name.parent.kind === 146 /* BindingElement */)) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - } - function ensureIdentifier(expr) { - if (expr.kind !== 64 /* Identifier */) { - var identifier = createTempVariable(root); - if (!isDeclaration) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expr); - expr = identifier; - } - return expr; - } - function createVoidZero() { - var zero = ts.createNode(7 /* NumericLiteral */); - zero.text = "0"; - var result = ts.createNode(160 /* VoidExpression */); - result.expression = zero; - return result; - } - function createDefaultValueCheck(value, defaultValue) { - value = ensureIdentifier(value); - var equals = ts.createNode(163 /* BinaryExpression */); - equals.left = value; - equals.operator = 30 /* EqualsEqualsEqualsToken */; - equals.right = createVoidZero(); - var cond = ts.createNode(164 /* ConditionalExpression */); - cond.condition = equals; - cond.whenTrue = defaultValue; - cond.whenFalse = value; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createNode(7 /* NumericLiteral */); - node.text = "" + value; - return node; - } - function parenthesizeForAccess(expr) { - if (expr.kind === 64 /* Identifier */ || expr.kind === 149 /* PropertyAccessExpression */ || expr.kind === 150 /* ElementAccessExpression */) { - return expr; - } - var node = ts.createNode(155 /* ParenthesizedExpression */); - node.expression = expr; - return node; - } - function createPropertyAccess(object, propName) { - if (propName.kind !== 64 /* Identifier */) { - return createElementAccess(object, propName); - } - var node = ts.createNode(149 /* PropertyAccessExpression */); - node.expression = parenthesizeForAccess(object); - node.name = propName; - return node; - } - function createElementAccess(object, index) { - var node = ts.createNode(150 /* ElementAccessExpression */); - node.expression = parenthesizeForAccess(object); - node.argumentExpression = index; - return node; - } - function emitObjectLiteralAssignment(target, value) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < properties.length; i++) { - var p = properties[i]; - if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { - var propName = (p.name); - emitDestructuringAssignment(p.initializer || propName, createPropertyAccess(value, propName)); - } - } - } - function emitArrayLiteralAssignment(target, value) { - var elements = target.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 167 /* OmittedExpression */) { - emitDestructuringAssignment(e, createElementAccess(value, createNumericLiteral(i))); - } - } - } - function emitDestructuringAssignment(target, value) { - if (target.kind === 163 /* BinaryExpression */ && target.operator === 52 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); - target = target.left; - } - if (target.kind === 148 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); - } - else if (target.kind === 147 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); - } - else { - emitAssignment(target, value); - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (root.parent.kind === 172 /* ExpressionStatement */) { - emitDestructuringAssignment(target, value); - } - else { - if (root.parent.kind !== 155 /* ParenthesizedExpression */) { - write("("); - } - value = ensureIdentifier(value); - emitDestructuringAssignment(target, value); - write(", "); - emit(value); - if (root.parent.kind !== 155 /* ParenthesizedExpression */) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; - } - else if (!value) { - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if (pattern.kind === 144 /* ObjectBindingPattern */) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccess(value, propName)); - } - else if (element.kind !== 167 /* OmittedExpression */) { - emitBindingElement(element, createElementAccess(value, createNumericLiteral(i))); - } - } - } - else { - emitAssignment(target.name, value); - } - } - } - function emitVariableDeclaration(node) { - emitLeadingComments(node); - if (ts.isBindingPattern(node.name)) { - emitDestructuring(node); - } - else { - emitModuleMemberName(node); - emitOptional(" = ", node.initializer); - } - emitTrailingComments(node); - } - function emitVariableStatement(node) { - emitLeadingComments(node); - if (!(node.flags & 1 /* Export */)) { - if (ts.isLet(node)) { - write("let "); - } - else if (ts.isConst(node)) { - write("const "); - } - else { - write("var "); - } - } - emitCommaList(node.declarations); - write(";"); - emitTrailingComments(node); - } - function emitParameter(node) { - emitLeadingComments(node); - if (ts.isBindingPattern(node.name)) { - var name = createTempVariable(node); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name); - emit(name); - } - else { - emit(node.name); - } - emitTrailingComments(node); - } - function emitDefaultValueAssignments(node) { - var tempIndex = 0; - ts.forEach(node.parameters, function (p) { - if (ts.isBindingPattern(p.name)) { - writeLine(); - write("var "); - emitDestructuring(p, tempParameters[tempIndex]); - write(";"); - tempIndex++; - } - else if (p.initializer) { - writeLine(); - emitStart(p); - write("if ("); - emitNode(p.name); - write(" === void 0)"); - emitEnd(p); - write(" { "); - emitStart(p); - emitNode(p.name); - write(" = "); - emitNode(p.initializer); - emitEnd(p); - write("; }"); - } - }); - } - function emitRestParameter(node) { - if (ts.hasRestParameters(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - var tempName = createTempVariable(node, true).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNode(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNode(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - emitLeadingComments(node); - write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - emitTrailingComments(node); - } - function emitFunctionDeclaration(node) { - if (!node.body) { - return emitPinnedOrTripleSlashComments(node); - } - if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { - emitLeadingComments(node); - } - write("function "); - if (node.kind === 190 /* FunctionDeclaration */ || (node.kind === 156 /* FunctionExpression */ && node.name)) { - emit(node.name); - } - emitSignatureAndBody(node); - if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - emitCommaList(node.parameters, node.parameters.length - (ts.hasRestParameters(node) ? 1 : 0)); - } - write(")"); - decreaseIndent(); - } - function emitSignatureAndBody(node) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempCount = 0; - tempVariables = undefined; - tempParameters = undefined; - emitSignatureParameters(node); - write(" {"); - scopeEmitStart(node); - increaseIndent(); - emitDetachedComments(node.body.kind === 169 /* Block */ ? node.body.statements : node.body); - var startIndex = 0; - if (node.body.kind === 169 /* Block */) { - startIndex = emitDirectivePrologues(node.body.statements, true); - } - var outPos = writer.getTextPos(); - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - if (node.body.kind !== 169 /* Block */ && outPos === writer.getTextPos()) { - decreaseIndent(); - write(" "); - emitStart(node.body); - write("return "); - emitNode(node.body); - emitEnd(node.body); - write(";"); - emitTempDeclarations(false); - write(" "); - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - else { - if (node.body.kind === 169 /* Block */) { - emitLinesStartingAt(node.body.statements, startIndex); - } - else { - writeLine(); - emitLeadingComments(node.body); - write("return "); - emit(node.body); - write(";"); - emitTrailingComments(node.body); - } - emitTempDeclarations(true); - writeLine(); - if (node.body.kind === 169 /* Block */) { - emitLeadingCommentsOfPosition(node.body.statements.end); - decreaseIndent(); - emitToken(15 /* CloseBraceToken */, node.body.statements.end); - } - else { - decreaseIndent(); - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - } - scopeEmitEnd(); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - emitEnd(node); - write(";"); - } - tempCount = saveTempCount; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 172 /* ExpressionStatement */) { - var expr = statement.expression; - if (expr && expr.kind === 151 /* CallExpression */) { - var func = expr.expression; - if (func && func.kind === 90 /* SuperKeyword */) { - return statement; - } - } - } - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNode(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - if (memberName.kind === 8 /* StringLiteral */ || memberName.kind === 7 /* NumericLiteral */) { - write("["); - emitNode(memberName); - write("]"); - } - else if (memberName.kind === 122 /* ComputedPropertyName */) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNode(memberName); - } - } - function emitMemberAssignments(node, staticFlag) { - ts.forEach(node.members, function (member) { - if (member.kind === 126 /* PropertyDeclaration */ && (member.flags & 128 /* Static */) === staticFlag && member.initializer) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - if (staticFlag) { - emitNode(node.name); - } - else { - write("this"); - } - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emit(member.initializer); - write(";"); - emitEnd(member); - emitTrailingComments(member); - } - }); - } - function emitMemberFunctions(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */) { - if (!member.body) { - return emitPinnedOrTripleSlashComments(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitNode(node.name); - if (!(member.flags & 128 /* Static */)) { - write(".prototype"); - } - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitStart(member); - emitFunctionDeclaration(member); - emitEnd(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) { - var accessors = getAllAccessorDeclarations(node, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitNode(node.name); - if (!(member.flags & 128 /* Static */)) { - write(".prototype"); - } - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitClassDeclaration(node) { - emitLeadingComments(node); - write("var "); - emit(node.name); - write(" = (function ("); - var baseTypeNode = ts.getClassBaseTypeNode(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - increaseIndent(); - scopeEmitStart(node); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emit(node.name); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructorOfClass(); - emitMemberFunctions(node); - emitMemberAssignments(node, 128 /* Static */); - writeLine(); - function emitClassReturnStatement() { - write("return "); - emitNode(node.name); - } - emitToken(15 /* CloseBraceToken */, node.members.end, emitClassReturnStatement); - write(";"); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - emitStart(node); - write(")("); - if (baseTypeNode) { - emit(baseTypeNode.typeName); - } - write(");"); - emitEnd(node); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - emitEnd(node); - write(";"); - } - emitTrailingComments(node); - function emitConstructorOfClass() { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempCount = 0; - tempVariables = undefined; - tempParameters = undefined; - ts.forEach(node.members, function (member) { - if (member.kind === 129 /* Constructor */ && !member.body) { - emitPinnedOrTripleSlashComments(member); - } - }); - var ctor = getFirstConstructorWithBody(node); - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - write("function "); - emit(node.name); - emitSignatureParameters(ctor); - write(" {"); - scopeEmitStart(node, "constructor"); - increaseIndent(); - if (ctor) { - emitDetachedComments(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeNode) { - var superCall = findInitialSuperCall(ctor); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("_super.apply(this, arguments);"); - emitEnd(baseTypeNode); - } - } - emitMemberAssignments(node, 0); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) - statements = statements.slice(1); - emitLines(statements); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(15 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - tempCount = saveTempCount; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - } - function emitInterfaceDeclaration(node) { - emitPinnedOrTripleSlashComments(node); - } - function emitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - if (isConstEnum && !compilerOptions.preserveConstEnums) { - return; - } - emitLeadingComments(node); - if (!(node.flags & 1 /* Export */)) { - emitStart(node); - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(resolver.getLocalNameOfContainer(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - scopeEmitStart(node); - emitEnumMemberDeclarations(isConstEnum); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - emitTrailingComments(node); - function emitEnumMemberDeclarations(isConstEnum) { - ts.forEach(node.members, function (member) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - write(resolver.getLocalNameOfContainer(node)); - write("["); - write(resolver.getLocalNameOfContainer(node)); - write("["); - emitExpressionForPropertyName(member.name); - write("] = "); - if (member.initializer && !isConstEnum) { - emit(member.initializer); - } - else { - write(resolver.getEnumMemberValue(member).toString()); - } - write("] = "); - emitExpressionForPropertyName(member.name); - emitEnd(member); - write(";"); - emitTrailingComments(member); - }); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function emitModuleDeclaration(node) { - var shouldEmit = ts.getModuleInstanceState(node) === 1 /* Instantiated */ || (ts.getModuleInstanceState(node) === 2 /* ConstEnumOnly */ && compilerOptions.preserveConstEnums); - if (!shouldEmit) { - return emitPinnedOrTripleSlashComments(node); - } - emitLeadingComments(node); - emitStart(node); - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(resolver.getLocalNameOfContainer(node)); - emitEnd(node.name); - write(") "); - if (node.body.kind === 196 /* ModuleBlock */) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - tempCount = 0; - tempVariables = undefined; - emit(node.body); - tempCount = saveTempCount; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - scopeEmitStart(node); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(15 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); - } - write(")("); - if (node.flags & 1 /* Export */) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - emitTrailingComments(node); - } - function emitImportDeclaration(node) { - var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); - if (!emitImportDeclaration) { - emitImportDeclaration = !ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportWithEntityName(node); - } - if (emitImportDeclaration) { - if (ts.isExternalModuleImportDeclaration(node) && node.parent.kind === 207 /* SourceFile */ && compilerOptions.module === 2 /* AMD */) { - if (node.flags & 1 /* Export */) { - writeLine(); - emitLeadingComments(node); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - write(";"); - emitEnd(node); - emitTrailingComments(node); - } - } - else { - writeLine(); - emitLeadingComments(node); - emitStart(node); - if (!(node.flags & 1 /* Export */)) - write("var "); - emitModuleMemberName(node); - write(" = "); - if (ts.isInternalModuleImportDeclaration(node)) { - emit(node.moduleReference); - } - else { - var literal = ts.getExternalModuleImportDeclarationExpression(node); - write("require("); - emitStart(literal); - emitLiteral(literal); - emitEnd(literal); - emitToken(17 /* CloseParenToken */, literal.end); - } - write(";"); - emitEnd(node); - emitTrailingComments(node); - } - } - } - function getExternalImportDeclarations(node) { - var result = []; - ts.forEach(node.statements, function (statement) { - if (ts.isExternalModuleImportDeclaration(statement) && resolver.isReferencedImportDeclaration(statement)) { - result.push(statement); - } - }); - return result; - } - function getFirstExportAssignment(sourceFile) { - return ts.forEach(sourceFile.statements, function (node) { - if (node.kind === 198 /* ExportAssignment */) { - return node; - } - }); - } - function emitAMDModule(node, startIndex) { - var imports = getExternalImportDeclarations(node); - writeLine(); - write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); - } - write("[\"require\", \"exports\""); - ts.forEach(imports, function (imp) { - write(", "); - emitLiteral(ts.getExternalModuleImportDeclarationExpression(imp)); - }); - ts.forEach(node.amdDependencies, function (amdDependency) { - var text = "\"" + amdDependency + "\""; - write(", "); - write(text); - }); - write("], function (require, exports"); - ts.forEach(imports, function (imp) { - write(", "); - emit(imp.name); - }); - write(") {"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - var exportName = resolver.getExportAssignmentName(node); - if (exportName) { - writeLine(); - var exportAssignement = getFirstExportAssignment(node); - emitStart(exportAssignement); - write("return "); - emitStart(exportAssignement.exportName); - write(exportName); - emitEnd(exportAssignement.exportName); - write(";"); - emitEnd(exportAssignement); - } - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node, startIndex) { - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - var exportName = resolver.getExportAssignmentName(node); - if (exportName) { - writeLine(); - var exportAssignement = getFirstExportAssignment(node); - emitStart(exportAssignement); - write("module.exports = "); - emitStart(exportAssignement.exportName); - write(exportName); - emitEnd(exportAssignement.exportName); - write(";"); - emitEnd(exportAssignement); - } - } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { - if (ts.isPrologueDirective(statements[i])) { - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - return i; - } - } - return statements.length; - } - function emitSourceFile(node) { - currentSourceFile = node; - writeLine(); - emitDetachedComments(node); - var startIndex = emitDirectivePrologues(node.statements, false); - if (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */) { - writeLine(); - write("var __extends = this.__extends || function (d, b) {"); - increaseIndent(); - writeLine(); - write("for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); - writeLine(); - write("function __() { this.constructor = d; }"); - writeLine(); - write("__.prototype = b.prototype;"); - writeLine(); - write("d.prototype = new __();"); - decreaseIndent(); - writeLine(); - write("};"); - extendsEmitted = true; - } - if (ts.isExternalModule(node)) { - if (compilerOptions.module === 2 /* AMD */) { - emitAMDModule(node, startIndex); - } - else { - emitCommonJSModule(node, startIndex); - } - } - else { - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - } - emitLeadingComments(node.endOfFileToken); - } - function emitNode(node) { - if (!node) { - return; - } - if (node.flags & 2 /* Ambient */) { - return emitPinnedOrTripleSlashComments(node); - } - switch (node.kind) { - case 64 /* Identifier */: - return emitIdentifier(node); - case 124 /* Parameter */: - return emitParameter(node); - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - return emitMethod(node); - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return emitAccessor(node); - case 92 /* ThisKeyword */: - return emitThis(node); - case 90 /* SuperKeyword */: - return emitSuper(node); - case 88 /* NullKeyword */: - return write("null"); - case 94 /* TrueKeyword */: - return write("true"); - case 79 /* FalseKeyword */: - return write("false"); - case 7 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 9 /* RegularExpressionLiteral */: - case 10 /* NoSubstitutionTemplateLiteral */: - case 11 /* TemplateHead */: - case 12 /* TemplateMiddle */: - case 13 /* TemplateTail */: - return emitLiteral(node); - case 165 /* TemplateExpression */: - return emitTemplateExpression(node); - case 168 /* TemplateSpan */: - return emitTemplateSpan(node); - case 121 /* QualifiedName */: - return emitQualifiedName(node); - case 144 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 145 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 147 /* ArrayLiteralExpression */: - return emitArrayLiteral(node); - case 148 /* ObjectLiteralExpression */: - return emitObjectLiteral(node); - case 204 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 205 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 122 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - case 149 /* PropertyAccessExpression */: - return emitPropertyAccess(node); - case 150 /* ElementAccessExpression */: - return emitIndexedAccess(node); - case 151 /* CallExpression */: - return emitCallExpression(node); - case 152 /* NewExpression */: - return emitNewExpression(node); - case 153 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 154 /* TypeAssertionExpression */: - return emit(node.expression); - case 155 /* ParenthesizedExpression */: - return emitParenExpression(node); - case 190 /* FunctionDeclaration */: - case 156 /* FunctionExpression */: - case 157 /* ArrowFunction */: - return emitFunctionDeclaration(node); - case 158 /* DeleteExpression */: - return emitDeleteExpression(node); - case 159 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 160 /* VoidExpression */: - return emitVoidExpression(node); - case 161 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 162 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 163 /* BinaryExpression */: - return emitBinaryExpression(node); - case 164 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 167 /* OmittedExpression */: - return; - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: - case 196 /* ModuleBlock */: - return emitBlock(node); - case 170 /* VariableStatement */: - return emitVariableStatement(node); - case 171 /* EmptyStatement */: - return write(";"); - case 172 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 173 /* IfStatement */: - return emitIfStatement(node); - case 174 /* DoStatement */: - return emitDoStatement(node); - case 175 /* WhileStatement */: - return emitWhileStatement(node); - case 176 /* ForStatement */: - return emitForStatement(node); - case 177 /* ForInStatement */: - return emitForInStatement(node); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: - return emitBreakOrContinueStatement(node); - case 180 /* ReturnStatement */: - return emitReturnStatement(node); - case 181 /* WithStatement */: - return emitWithStatement(node); - case 182 /* SwitchStatement */: - return emitSwitchStatement(node); - case 200 /* CaseClause */: - case 201 /* DefaultClause */: - return emitCaseOrDefaultClause(node); - case 183 /* LabeledStatement */: - return emitLabelledStatement(node); - case 184 /* ThrowStatement */: - return emitThrowStatement(node); - case 185 /* TryStatement */: - return emitTryStatement(node); - case 203 /* CatchClause */: - return emitCatchClause(node); - case 188 /* DebuggerStatement */: - return emitDebuggerStatement(node); - case 189 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 191 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 192 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 194 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 195 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 197 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 207 /* SourceFile */: - return emitSourceFile(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function getLeadingCommentsToEmit(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { - var leadingComments; - if (hasDetachedComments(node.pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); - } - return leadingComments; - } - } - function emitLeadingDeclarationComments(node) { - var leadingComments = getLeadingCommentsToEmit(node); - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingDeclarationComments(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); - emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); - } - } - function emitLeadingCommentsOfLocalPosition(pos) { - var leadingComments; - if (hasDetachedComments(pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); - } - emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); - emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedCommentsAtPosition(node) { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); - var astLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (astLine >= lastCommentLine + 2) { - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - } - } - function emitPinnedOrTripleSlashCommentsOfNode(node) { - var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); - function isPinnedOrTripleSlashComment(comment) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - return currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; - } - else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */ && currentSourceFile.text.substring(comment.pos, comment.end).match(ts.fullTripleSlashReferencePathRegEx)) { - return true; - } - } - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, pinnedComments); - emitComments(currentSourceFile, writer, pinnedComments, true, newLine, writeComment); - } - if (compilerOptions.sourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { - emit(root); - } - else { - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emit(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); - } - function writeDeclarationFile(jsFilePath, sourceFile) { - var emitDeclarationResult = emitDeclarations(program, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { - var declarationOutput = emitDeclarationResult.referencePathsOutput; - var appliedSyncOutputPos = 0; - ts.forEach(emitDeclarationResult.aliasDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += aliasEmitInfo.asynchronousOutput; - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos); - writeFile(compilerHost, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); - } - } - var hasSemanticErrors = false; - var isEmitBlocked = false; - if (targetSourceFile === undefined) { - hasSemanticErrors = resolver.hasSemanticErrors(); - isEmitBlocked = resolver.isEmitBlocked(); - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, program, ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.out) { - emitFile(compilerOptions.out); - } - } - else { - if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); - isEmitBlocked = resolver.isEmitBlocked(targetSourceFile); - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && compilerOptions.out) { - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { - hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); - isEmitBlocked = isEmitBlocked || resolver.isEmitBlocked(sourceFile); - } - }); - emitFile(compilerOptions.out); - } - } - function emitFile(jsFilePath, sourceFile) { - if (!isEmitBlocked) { - emitJavaScript(jsFilePath, sourceFile); - if (!hasSemanticErrors && compilerOptions.declaration) { - writeDeclarationFile(jsFilePath, sourceFile); - } - } - } - diagnostics.sort(ts.compareDiagnostics); - diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); - var hasEmitterError = ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === 1 /* Error */; }); - var emitResultStatus; - if (isEmitBlocked) { - emitResultStatus = 1 /* AllOutputGenerationSkipped */; - } - else if (hasEmitterError) { - emitResultStatus = 4 /* EmitErrorsEncountered */; - } - else if (hasSemanticErrors && compilerOptions.declaration) { - emitResultStatus = 3 /* DeclarationGenerationSkipped */; - } - else if (hasSemanticErrors && !compilerOptions.declaration) { - emitResultStatus = 2 /* JSGeneratedWithSemanticErrors */; - } - else { - emitResultStatus = 0 /* Succeeded */; - } - return { - emitResultStatus: emitResultStatus, - diagnostics: diagnostics, - sourceMaps: sourceMapDataList - }; - } - ts.emitFiles = emitFiles; -})(ts || (ts = {})); -var ts; (function (ts) { var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; - function createTypeChecker(program, fullTypeCheck) { + function createTypeChecker(host, produceDiagnostics) { var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var emptyArray = []; var emptySymbols = {}; - var compilerOptions = program.getCompilerOptions(); + var compilerOptions = host.getCompilerOptions(); + var emitResolver = createResolver(); var checker = { - getProgram: function () { return program; }, - getNodeCount: function () { return ts.sum(program.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(program.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(program.getSourceFiles(), "symbolCount"); }, + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount"); }, getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - emitFiles: invokeEmitter, getDiagnostics: getDiagnostics, - getDeclarationDiagnostics: getDeclarationDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getTypeOfSymbolAtLocation, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -9808,8 +6744,7 @@ var ts; getSignatureFromDeclaration: getSignatureFromDeclaration, isImplementationOfOverload: isImplementationOfOverload, getAliasedSymbol: resolveImport, - hasEarlyErrors: hasEarlyErrors, - isEmitBlocked: isEmitBlocked + getEmitResolver: function () { return emitResolver; } }; var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); @@ -10018,7 +6953,7 @@ var ts; if (!compilerOptions.out) { return true; } - var sourceFiles = program.getSourceFiles(); + var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(file1) <= sourceFiles.indexOf(file2); } function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { @@ -10117,7 +7052,7 @@ var ts; return undefined; } if (result.flags & 2 /* BlockScopedVariable */) { - var declaration = ts.forEach(result.declarations, function (d) { return d.flags & 6144 /* BlockScoped */ ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.getCombinedNodeFlags(d) & 6144 /* BlockScoped */ ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); if (!isDefinedBefore(declaration, errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); @@ -10213,7 +7148,7 @@ var ts; } while (true) { var filename = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - var sourceFile = program.getSourceFile(filename + ".ts") || program.getSourceFile(filename + ".d.ts"); + var sourceFile = host.getSourceFile(filename + ".ts") || host.getSourceFile(filename + ".d.ts"); if (sourceFile || isRelative) break; var parentPath = ts.getDirectoryPath(searchPath); @@ -10315,7 +7250,7 @@ var ts; var members = node.members; for (var i = 0; i < members.length; i++) { var member = members[i]; - if (member.kind === 129 /* Constructor */ && member.body) { + if (member.kind === 129 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -10410,7 +7345,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, function (declaration) { return hasExternalModuleSymbol(declaration); }) && canQualifySymbol(symbolFromSymbolTable, meaning); + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); } } if (isAccessible(ts.lookUp(symbols, symbol.name))) { @@ -10474,7 +7409,7 @@ var ts; meaningToLook = getQualifiedLeftMeaning(meaning); symbol = getParentOfSymbol(symbol); } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, function (declaration) { return getExternalModuleContainer(declaration); }); + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { @@ -10627,7 +7562,7 @@ var ts; } } else { - if (!parentSymbol && ts.forEach(symbol.declarations, function (declaration) { return hasExternalModuleSymbol(declaration); })) { + if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { return; } if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { @@ -11016,7 +7951,7 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 195 /* ModuleDeclaration */: case 191 /* ClassDeclaration */: @@ -11026,7 +7961,7 @@ var ts; case 194 /* EnumDeclaration */: case 197 /* ImportDeclaration */: var parent = getDeclarationContainer(node); - if (!(node.flags & 1 /* Export */) && !(node.kind !== 197 /* ImportDeclaration */ && parent.kind !== 207 /* SourceFile */ && ts.isInAmbientContext(parent))) { + if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && !(node.kind !== 197 /* ImportDeclaration */ && parent.kind !== 207 /* SourceFile */ && ts.isInAmbientContext(parent))) { return isGlobalSourceFile(parent) || isUsedInExportAssignment(node); } return isDeclarationVisible(parent); @@ -11077,7 +8012,7 @@ var ts; } function getDeclarationContainer(node) { node = getRootDeclaration(node); - return node.kind === 189 /* VariableDeclaration */ ? node.parent.parent : node.parent; + return node.kind === 188 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -11106,22 +8041,28 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; } - return type; } - if (!isTypeAssignableTo(parentType, anyArrayType)) { - error(pattern, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(parentType)); - return unknownType; - } - var propName = "" + ts.indexOf(pattern.elements, declaration); - var type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : getIndexTypeOfType(parentType, 1 /* Number */); - if (!type) { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - return unknownType; + else { + if (!isTypeAssignableTo(parentType, anyArrayType)) { + error(pattern, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(parentType)); + return unknownType; + } + if (!declaration.dotDotDotToken) { + var propName = "" + ts.indexOf(pattern.elements, declaration); + var type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : getIndexTypeOfType(parentType, 1 /* Number */); + if (!type) { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + return unknownType; + } + } + else { + var type = createArrayType(getIndexTypeOfType(parentType, 1 /* Number */)); + } } return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.kind === 177 /* ForInStatement */) { + if (declaration.parent.parent.kind === 178 /* ForInStatement */) { return anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -11160,10 +8101,7 @@ var ts; } return anyType; } - function getTypeFromBindingPattern(pattern) { - if (pattern.kind === 145 /* ArrayBindingPattern */) { - return createTupleType(ts.map(pattern.elements, function (e) { return e.kind === 167 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e); })); - } + function getTypeFromObjectBindingPattern(pattern) { var members = {}; ts.forEach(pattern.elements, function (e) { var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); @@ -11174,6 +8112,20 @@ var ts; }); return createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); } + function getTypeFromArrayBindingPattern(pattern) { + var hasSpreadElement = false; + var elementTypes = []; + ts.forEach(pattern.elements, function (e) { + elementTypes.push(e.kind === 168 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + if (e.dotDotDotToken) { + hasSpreadElement = true; + } + }); + return !elementTypes.length ? anyArrayType : hasSpreadElement ? createArrayType(getUnionType(elementTypes)) : createTupleType(elementTypes); + } + function getTypeFromBindingPattern(pattern) { + return pattern.kind === 144 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); + } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration); if (type) { @@ -11906,7 +8858,7 @@ var ts; var setter = ts.getDeclarationOfKind(declaration.symbol, 131 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } - if (!returnType && !declaration.body) { + if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } @@ -12519,7 +9471,7 @@ var ts; return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - return !node.typeParameters && !ts.forEach(node.parameters, function (p) { return p.type; }); + return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } function getTypeWithoutConstructors(type) { if (type.flags & 48128 /* ObjectType */) { @@ -12578,7 +9530,7 @@ var ts; if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, host.getCompilerHost().getNewLine())); } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { @@ -13118,7 +10070,7 @@ var ts; result &= related; } } - else if (source.typeParameters || source.typeParameters) { + else if (source.typeParameters || target.typeParameters) { return 0 /* False */; } source = getErasedSignature(source); @@ -13209,7 +10161,7 @@ var ts; return anyType; } if (type.flags & 16384 /* Union */) { - return getUnionType(ts.map(type.types, function (t) { return getWidenedType(t); })); + return getUnionType(ts.map(type.types, getWidenedType)); } if (isTypeOfObjectLiteral(type)) { return getWidenedTypeOfObjectLiteral(type); @@ -13277,7 +10229,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (fullTypeCheck && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -13547,7 +10499,7 @@ var ts; switch (node.kind) { case 163 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: return isAssignedInVariableDeclaration(node); case 144 /* ObjectBindingPattern */: @@ -13566,25 +10518,24 @@ var ts; case 160 /* VoidExpression */: case 162 /* PostfixUnaryExpression */: case 164 /* ConditionalExpression */: - case 169 /* Block */: - case 170 /* VariableStatement */: - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 180 /* ReturnStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 167 /* SpreadElementExpression */: + case 170 /* Block */: + case 171 /* VariableStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 181 /* ReturnStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 184 /* ThrowStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 185 /* ThrowStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -13621,7 +10572,7 @@ var ts; node = node.parent; var narrowedType = type; switch (node.kind) { - case 173 /* IfStatement */: + case 174 /* IfStatement */: if (child !== node.expression) { narrowedType = narrowType(type, node.expression, child === node.thenStatement); } @@ -13965,15 +10916,21 @@ var ts; } return undefined; } - function getContextualTypeForArgument(node) { - var callExpression = node.parent; - var argIndex = ts.indexOf(callExpression.arguments, node); + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); if (argIndex >= 0) { - var signature = getResolvedSignature(callExpression); + var signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 153 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operator; @@ -14024,7 +10981,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfObjectOrUnionType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return isTupleLikeType(t); }) : isTupleLikeType(type)); + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function contextualTypeHasIndexSignature(type, kind) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfObjectOrUnionType(t, kind); }) : getIndexTypeOfObjectOrUnionType(type, kind)); @@ -14067,18 +11024,18 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 124 /* Parameter */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 146 /* BindingElement */: return getContextualTypeForInitializerExpression(node); case 157 /* ArrowFunction */: - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); case 151 /* CallExpression */: case 152 /* NewExpression */: - return getContextualTypeForArgument(node); + return getContextualTypeForArgument(parent, node); case 154 /* TypeAssertionExpression */: return getTypeFromTypeNode(parent.type); case 163 /* BinaryExpression */: @@ -14089,6 +11046,9 @@ var ts; return getContextualTypeForElementExpression(node); case 164 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); + case 169 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 165 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); } return undefined; } @@ -14159,15 +11119,36 @@ var ts; } return false; } + function checkSpreadElementExpression(node, contextualMapper) { + var type = checkExpressionCached(node.expression, contextualMapper); + if (!isTypeAssignableTo(type, anyArrayType)) { + error(node.expression, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(type)); + return unknownType; + } + return type; + } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; if (!elements.length) { return createArrayType(undefinedType); } - var elementTypes = ts.map(elements, function (e) { return checkExpression(e, contextualMapper); }); - var contextualType = getContextualType(node); - if ((contextualType && contextualTypeIsTupleLikeType(contextualType)) || isAssignmentTarget(node)) { - return createTupleType(elementTypes); + var hasSpreadElement = false; + var elementTypes = []; + ts.forEach(elements, function (e) { + var type = checkExpression(e, contextualMapper); + if (e.kind === 167 /* SpreadElementExpression */) { + elementTypes.push(getIndexTypeOfType(type, 1 /* Number */) || anyType); + hasSpreadElement = true; + } + else { + elementTypes.push(type); + } + }); + if (!hasSpreadElement) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType) || isAssignmentTarget(node)) { + return createTupleType(elementTypes); + } } return createArrayType(getUnionType(elementTypes)); } @@ -14246,7 +11227,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 126 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.flags : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); @@ -14461,7 +11442,7 @@ var ts; var context = createInferenceContext(typeParameters, false); var mapper = createInferenceMapper(context); for (var i = 0; i < args.length; i++) { - if (args[i].kind === 167 /* OmittedExpression */) { + if (args[i].kind === 168 /* OmittedExpression */) { continue; } if (!excludeArgument || excludeArgument[i] === undefined) { @@ -14475,7 +11456,7 @@ var ts; } if (excludeArgument) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 167 /* OmittedExpression */) { + if (args[i].kind === 168 /* OmittedExpression */) { continue; } if (excludeArgument[i] === false) { @@ -14513,7 +11494,7 @@ var ts; for (var i = 0; i < args.length; i++) { var arg = args[i]; var argType; - if (arg.kind === 167 /* OmittedExpression */) { + if (arg.kind === 168 /* OmittedExpression */) { continue; } var paramType = getTypeAtPosition(signature, i); @@ -14600,7 +11581,7 @@ var ts; else { error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } - if (!fullTypeCheck) { + if (!produceDiagnostics) { for (var i = 0, n = candidates.length; i < n; i++) { if (hasCorrectArity(node, args, candidates[i])) { return candidates[i]; @@ -14814,7 +11795,7 @@ var ts; function checkTypeAssertion(node) { var exprType = checkExpression(node.expression); var targetType = getTypeFromTypeNode(node.type); - if (fullTypeCheck && targetType !== unknownType) { + if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); @@ -14840,7 +11821,7 @@ var ts; } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (func.body.kind !== 169 /* Block */) { + if (func.body.kind !== 170 /* Block */) { var type = checkExpressionCached(func.body, contextualMapper); } else { @@ -14878,16 +11859,16 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 184 /* ThrowStatement */); + return (body.statements.length === 1) && (body.statements[0].kind === 185 /* ThrowStatement */); } function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } if (returnType === voidType || returnType === anyType) { return; } - if (!func.body || func.body.kind !== 169 /* Block */) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 170 /* Block */) { return; } var bodyBlock = func.body; @@ -14930,7 +11911,7 @@ var ts; checkSignatureDeclaration(node); } } - if (fullTypeCheck && node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -14942,7 +11923,7 @@ var ts; checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 169 /* Block */) { + if (node.body.kind === 170 /* Block */) { checkSourceElement(node.body); } else { @@ -15117,14 +12098,24 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 167 /* OmittedExpression */) { - var propName = "" + i; - var type = sourceType.flags & 1 /* Any */ ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : getIndexTypeOfType(sourceType, 1 /* Number */); - if (type) { - checkDestructuringAssignment(e, type, contextualMapper); + if (e.kind !== 168 /* OmittedExpression */) { + if (e.kind !== 167 /* SpreadElementExpression */) { + var propName = "" + i; + var type = sourceType.flags & 1 /* Any */ ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : getIndexTypeOfType(sourceType, 1 /* Number */); + if (type) { + checkDestructuringAssignment(e, type, contextualMapper); + } + else { + error(e, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } } else { - error(e, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + if (i === elements.length - 1) { + checkReferenceAssignment(e.expression, sourceType, contextualMapper); + } + else { + error(e, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } } } } @@ -15141,6 +12132,9 @@ var ts; if (target.kind === 147 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } + return checkReferenceAssignment(target, sourceType, contextualMapper); + } + function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); @@ -15260,7 +12254,7 @@ var ts; } } function checkAssignmentOperator(valueType) { - if (fullTypeCheck && operator >= 52 /* FirstAssignment */ && operator <= 63 /* LastAssignment */) { + if (produceDiagnostics && operator >= 52 /* FirstAssignment */ && operator <= 63 /* LastAssignment */) { var ok = checkReferenceExpression(node.left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); if (ok) { checkTypeAssignableTo(valueType, leftType, node.left, undefined); @@ -15405,7 +12399,9 @@ var ts; return checkBinaryExpression(node, contextualMapper); case 164 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 167 /* OmittedExpression */: + case 167 /* SpreadElementExpression */: + return checkSpreadElementExpression(node, contextualMapper); + case 168 /* OmittedExpression */: return undefinedType; case 166 /* YieldExpression */: checkYieldExpression(node); @@ -15418,7 +12414,7 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } @@ -15429,7 +12425,7 @@ var ts; var func = ts.getContainingFunction(node); if (node.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */)) { func = ts.getContainingFunction(node); - if (!(func.kind === 129 /* Constructor */ && func.body)) { + if (!(func.kind === 129 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -15451,7 +12447,7 @@ var ts; if (node.type) { checkSourceElement(node.type); } - if (fullTypeCheck) { + if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { @@ -15519,10 +12515,10 @@ var ts; if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); } - if (!node.body) { + if (ts.nodeIsMissing(node.body)) { return; } - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } function isSuperCallExpression(n) { @@ -15556,7 +12552,7 @@ var ts; var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 172 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 173 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } else { @@ -15570,10 +12566,10 @@ var ts; } } function checkAccessorDeclaration(node) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (fullTypeCheck) { + if (produceDiagnostics) { + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 130 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } @@ -15605,7 +12601,7 @@ var ts; for (var i = 0; i < len; i++) { checkSourceElement(node.typeArguments[i]); var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (fullTypeCheck && constraint) { + if (produceDiagnostics && constraint) { var typeArgument = type.typeArguments[i]; checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } @@ -15617,7 +12613,7 @@ var ts; } function checkTypeLiteral(node) { ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -15640,14 +12636,14 @@ var ts; return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } var signature = getSignatureFromDeclaration(signatureDeclarationNode); if (!signature.hasStringLiterals) { return; } - if (signatureDeclarationNode.body) { + if (ts.nodeIsPresent(signatureDeclarationNode.body)) { error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); return; } @@ -15671,7 +12667,7 @@ var ts; error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = n.flags; + var flags = ts.getCombinedNodeFlags(n); if (n.parent.kind !== 192 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { flags |= 1 /* Export */; @@ -15681,7 +12677,7 @@ var ts; return flags & flagsToCheck; } function checkFunctionOrConstructorSymbol(symbol) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } function getCanonicalOverload(overloads, implementation) { @@ -15751,7 +12747,7 @@ var ts; error(errorNode, diagnostic); return; } - else if (subsequentNode.body) { + else if (ts.nodeIsPresent(subsequentNode.body)) { error(errorNode, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); return; } @@ -15781,7 +12777,7 @@ var ts; allNodeFlags &= currentNodeFlags; someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (node.body && bodyDeclaration) { + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { if (isConstructor) { multipleConstructorImplementation = true; } @@ -15792,7 +12788,7 @@ var ts; else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } - if (node.body) { + if (ts.nodeIsPresent(node.body)) { if (!bodyDeclaration) { bodyDeclaration = node; } @@ -15837,7 +12833,7 @@ var ts; } } function checkExportsOnMergedDeclarations(node) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } var symbol; @@ -15892,9 +12888,8 @@ var ts; } } function checkFunctionDeclaration(node) { - checkFunctionLikeDeclaration(node); - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); - if (fullTypeCheck) { + if (produceDiagnostics) { + checkFunctionLikeDeclaration(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -15919,12 +12914,12 @@ var ts; if (node.type && !isAccessor(node.kind)) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } - if (compilerOptions.noImplicitAny && !node.body && !node.type && !isPrivateWithinAmbient(node)) { + if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { reportImplicitAnyError(node, anyType); } } function checkBlock(node) { - if (node.kind === 169 /* Block */) { + if (node.kind === 170 /* Block */) { checkGrammarForStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -15933,7 +12928,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || !node.body) { + if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -15953,7 +12948,7 @@ var ts; return false; } var root = getRootDeclaration(node); - if (root.kind === 124 /* Parameter */ && !root.parent.body) { + if (root.kind === 124 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -16010,7 +13005,7 @@ var ts; } } function checkCollisionWithConstDeclarations(node) { - if (node.initializer && (node.flags & 6144 /* BlockScoped */) === 0) { + if (node.initializer && (ts.getCombinedNodeFlags(node) & 6144 /* BlockScoped */) === 0) { var symbol = getSymbolOfNode(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { var localDeclarationSymbol = resolveName(node, node.name.text, 3 /* Variable */, undefined, undefined); @@ -16055,12 +13050,6 @@ var ts; } } function checkVariableLikeDeclaration(node) { - if (node.kind === 146 /* BindingElement */) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); - } - else if (node.kind === 189 /* VariableDeclaration */) { - checkGrammarVariableDeclaration(node); - } checkSourceElement(node.type); if (ts.hasComputedNameButNotSymbol(node)) { if (node.initializer) { @@ -16071,7 +13060,7 @@ var ts; if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && getRootDeclaration(node).kind === 124 /* Parameter */ && !ts.getContainingFunction(node).body) { + if (node.initializer && getRootDeclaration(node).kind === 124 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -16107,9 +13096,32 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } function checkVariableStatement(node) { - checkGrammarModifiers(node) || checkGrammarVariableDeclarations(node, node.declarations) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarations, checkSourceElement); + checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { + if (node.modifiers) { + if (inBlockOrObjectLiteralExpression(node)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function inBlockOrObjectLiteralExpression(node) { + while (node) { + if (node.kind === 170 /* Block */ || node.kind === 148 /* ObjectLiteralExpression */) { + return true; + } + node = node.parent; + } } function checkExpressionStatement(node) { checkGrammarForStatementInAmbientContext(node); @@ -16132,11 +13144,19 @@ var ts; checkSourceElement(node.statement); } function checkForStatement(node) { - checkGrammarForStatementInAmbientContext(node) || checkGrammarVariableDeclarations(node, node.declarations); - if (node.declarations) - ts.forEach(node.declarations, checkVariableLikeDeclaration); - if (node.initializer) - checkExpression(node.initializer); + if (!checkGrammarForStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind == 189 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } if (node.condition) checkExpression(node.condition); if (node.iterator) @@ -16145,29 +13165,33 @@ var ts; } function checkForInStatement(node) { if (!checkGrammarForStatementInAmbientContext(node)) { - var declarations = node.declarations; - if (!checkGrammarVariableDeclarations(node, declarations)) { - if (declarations && declarations.length > 1) { - grammarErrorOnFirstToken(declarations[1], ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableList = node.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + if (variableList.declarations.length > 1) { + grammarErrorOnFirstToken(variableList.declarations[1], ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + } } } } - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; - checkVariableLikeDeclaration(decl); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); if (decl.type) { error(decl, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation); } } } - if (node.variable) { - var exprType = checkExpression(node.variable); + else { + var varExpr = node.initializer; + var exprType = checkExpression(varExpr); if (exprType !== anyType && exprType !== stringType) { - error(node.variable, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression(node.variable, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); } } var exprType = checkExpression(node.expression); @@ -16237,7 +13261,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (fullTypeCheck && clause.kind === 200 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 200 /* CaseClause */) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { @@ -16254,7 +13278,7 @@ var ts; if (ts.isAnyFunction(current)) { break; } - if (current.kind === 183 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 184 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -16352,7 +13376,7 @@ var ts; for (var i = 0; i < typeParameterDeclarations.length; i++) { var node = typeParameterDeclarations[i]; checkTypeParameter(node); - if (fullTypeCheck) { + if (produceDiagnostics) { for (var j = 0; j < i; j++) { if (typeParameterDeclarations[j].symbol === node.symbol) { error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); @@ -16378,7 +13402,7 @@ var ts; checkTypeReference(baseTypeNode); } if (type.baseTypes.length) { - if (fullTypeCheck) { + if (produceDiagnostics) { var baseType = type.baseTypes[0]; checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); var staticBaseType = getTypeOfSymbol(baseType.symbol); @@ -16394,7 +13418,7 @@ var ts; if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { checkTypeReference(typeRefNode); - if (fullTypeCheck) { + if (produceDiagnostics) { var t = getTypeFromTypeReferenceNode(typeRefNode); if (t !== unknownType) { var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; @@ -16409,7 +13433,7 @@ var ts; }); } ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -16514,7 +13538,7 @@ var ts; var typeName2 = typeToString(base); var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, host.getCompilerHost().getNewLine())); } } } @@ -16524,7 +13548,7 @@ var ts; function checkInterfaceDeclaration(node) { checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); @@ -16546,7 +13570,7 @@ var ts; } ts.forEach(ts.getInterfaceBaseTypeNodes(node), checkTypeReference); ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); } } @@ -16691,10 +13715,10 @@ var ts; } } function checkEnumDeclaration(node) { - checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } + checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -16736,31 +13760,31 @@ var ts; var declarations = symbol.declarations; for (var i = 0; i < declarations.length; i++) { var declaration = declarations[i]; - if ((declaration.kind === 191 /* ClassDeclaration */ || (declaration.kind === 190 /* FunctionDeclaration */ && declaration.body)) && !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 191 /* ClassDeclaration */ || (declaration.kind === 190 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } } return undefined; } function checkModuleDeclaration(node) { - if (!checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - else if (node.name.kind === 64 /* Identifier */ && node.body.kind === 196 /* ModuleBlock */) { - var statements = node.body.statements; - for (var i = 0, n = statements.length; i < n; i++) { - var statement = statements[i]; - if (statement.kind === 198 /* ExportAssignment */) { - grammarErrorOnNode(statement, ts.Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); - } - else if (ts.isExternalModuleImportDeclaration(statement)) { - grammarErrorOnNode(ts.getExternalModuleImportDeclarationExpression(statement), ts.Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + if (produceDiagnostics) { + if (!checkGrammarModifiers(node)) { + if (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + else if (node.name.kind === 64 /* Identifier */ && node.body.kind === 196 /* ModuleBlock */) { + var statements = node.body.statements; + for (var i = 0, n = statements.length; i < n; i++) { + var statement = statements[i]; + if (statement.kind === 198 /* ExportAssignment */) { + grammarErrorOnNode(statement, ts.Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); + } + else if (ts.isExternalModuleImportDeclaration(statement)) { + grammarErrorOnNode(ts.getExternalModuleImportDeclarationExpression(statement), ts.Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + } } } } - } - if (fullTypeCheck) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); @@ -16897,41 +13921,42 @@ var ts; return checkSourceElement(node.type); case 190 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 169 /* Block */: + case 170 /* Block */: case 196 /* ModuleBlock */: return checkBlock(node); - case 170 /* VariableStatement */: + case 171 /* VariableStatement */: return checkVariableStatement(node); - case 172 /* ExpressionStatement */: + case 173 /* ExpressionStatement */: return checkExpressionStatement(node); - case 173 /* IfStatement */: + case 174 /* IfStatement */: return checkIfStatement(node); - case 174 /* DoStatement */: + case 175 /* DoStatement */: return checkDoStatement(node); - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return checkWhileStatement(node); - case 176 /* ForStatement */: + case 177 /* ForStatement */: return checkForStatement(node); - case 177 /* ForInStatement */: + case 178 /* ForInStatement */: return checkForInStatement(node); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return checkReturnStatement(node); - case 181 /* WithStatement */: + case 182 /* WithStatement */: return checkWithStatement(node); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return checkSwitchStatement(node); - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return checkLabeledStatement(node); - case 184 /* ThrowStatement */: + case 185 /* ThrowStatement */: return checkThrowStatement(node); - case 185 /* TryStatement */: + case 186 /* TryStatement */: return checkTryStatement(node); - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: + return checkVariableDeclaration(node); case 146 /* BindingElement */: - return checkVariableLikeDeclaration(node); + return checkBindingElement(node); case 191 /* ClassDeclaration */: return checkClassDeclaration(node); case 192 /* InterfaceDeclaration */: @@ -16946,10 +13971,10 @@ var ts; return checkImportDeclaration(node); case 198 /* ExportAssignment */: return checkExportAssignment(node); - case 171 /* EmptyStatement */: + case 172 /* EmptyStatement */: checkGrammarForStatementInAmbientContext(node); return; - case 188 /* DebuggerStatement */: + case 187 /* DebuggerStatement */: checkGrammarForStatementInAmbientContext(node); return; } @@ -16974,7 +13999,7 @@ var ts; case 190 /* FunctionDeclaration */: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 181 /* WithStatement */: + case 182 /* WithStatement */: checkFunctionExpressionBodies(node.expression); break; case 124 /* Parameter */: @@ -16991,6 +14016,8 @@ var ts; case 151 /* CallExpression */: case 152 /* NewExpression */: case 153 /* TaggedTemplateExpression */: + case 165 /* TemplateExpression */: + case 169 /* TemplateSpan */: case 154 /* TypeAssertionExpression */: case 155 /* ParenthesizedExpression */: case 159 /* TypeOfExpression */: @@ -17000,28 +14027,28 @@ var ts; case 162 /* PostfixUnaryExpression */: case 163 /* BinaryExpression */: case 164 /* ConditionalExpression */: - case 169 /* Block */: + case 167 /* SpreadElementExpression */: + case 170 /* Block */: case 196 /* ModuleBlock */: - case 170 /* VariableStatement */: - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: - case 180 /* ReturnStatement */: - case 182 /* SwitchStatement */: + case 171 /* VariableStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 184 /* ThrowStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 185 /* ThrowStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: + case 189 /* VariableDeclarationList */: case 191 /* ClassDeclaration */: case 194 /* EnumDeclaration */: case 206 /* EnumMember */: @@ -17056,7 +14083,7 @@ var ts; } } function getSortedDiagnostics() { - ts.Debug.assert(fullTypeCheck, "diagnostics are available only in the full typecheck mode"); + ts.Debug.assert(produceDiagnostics, "diagnostics are available only in the full typecheck mode"); if (diagnosticsModified) { diagnostics.sort(ts.compareDiagnostics); diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); @@ -17065,25 +14092,27 @@ var ts; return diagnostics; } function getDiagnostics(sourceFile) { + throwIfNonDiagnosticsProducing(); if (sourceFile) { checkSourceFile(sourceFile); return ts.filter(getSortedDiagnostics(), function (d) { return d.file === sourceFile; }); } - ts.forEach(program.getSourceFiles(), checkSourceFile); + ts.forEach(host.getSourceFiles(), checkSourceFile); return getSortedDiagnostics(); } - function getDeclarationDiagnostics(targetSourceFile) { - var resolver = createResolver(); - checkSourceFile(targetSourceFile); - return ts.getDeclarationDiagnostics(program, resolver, targetSourceFile); - } function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); return ts.filter(getSortedDiagnostics(), function (d) { return !d.file; }); } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 181 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 182 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -17203,7 +14232,7 @@ var ts; case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 124 /* Parameter */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: return node === parent.type; case 190 /* FunctionDeclaration */: case 156 /* FunctionExpression */: @@ -17424,8 +14453,17 @@ var ts; } function isUniqueLocalName(name, container) { for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name) && node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */)) { - return false; + if (node.locals && ts.hasProperty(node.locals, name)) { + var symbolWithRelevantName = node.locals[name]; + if (symbolWithRelevantName.flags & (107455 /* Value */ | 1048576 /* ExportValue */)) { + return false; + } + if (symbolWithRelevantName.flags & 8388608 /* Import */) { + var importDeclarationWithRelevantName = ts.getDeclarationOfKind(symbolWithRelevantName, 197 /* ImportDeclaration */); + if (isReferencedImportDeclaration(importDeclarationWithRelevantName)) { + return false; + } + } } } return true; @@ -17477,12 +14515,6 @@ var ts; function hasSemanticErrors(sourceFile) { return getDiagnostics(sourceFile).length > 0 || getGlobalDiagnostics().length > 0; } - function isEmitBlocked(sourceFile) { - return program.getDiagnostics(sourceFile).length !== 0 || hasEarlyErrors(sourceFile) || (compilerOptions.noEmitOnError && getDiagnostics(sourceFile).length !== 0); - } - function hasEarlyErrors(sourceFile) { - return ts.forEach(getDiagnostics(sourceFile), function (d) { return d.isEarly; }); - } function isImportResolvedToValue(symbol) { var target = resolveImport(symbol); return target !== unknownSymbol && target.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); @@ -17501,7 +14533,7 @@ var ts; return false; } function isImplementationOfOverload(node) { - if (node.body) { + if (ts.nodeIsPresent(node.body)) { var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); @@ -17540,7 +14572,6 @@ var ts; } function createResolver() { return { - getProgram: function () { return program; }, getLocalNameOfContainer: getLocalNameOfContainer, getExpressionNamePrefix: getExpressionNamePrefix, getExportAssignmentName: getExportAssignmentName, @@ -17549,7 +14580,6 @@ var ts; getEnumMemberValue: getEnumMemberValue, isTopLevelValueImportWithEntityName: isTopLevelValueImportWithEntityName, hasSemanticErrors: hasSemanticErrors, - isEmitBlocked: isEmitBlocked, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, writeTypeOfDeclaration: writeTypeOfDeclaration, @@ -17560,16 +14590,12 @@ var ts; isUnknownIdentifier: isUnknownIdentifier }; } - function invokeEmitter(targetSourceFile) { - var resolver = createResolver(); - return ts.emitFiles(resolver, targetSourceFile); - } function initializeTypeChecker() { - ts.forEach(program.getSourceFiles(), function (file) { + ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file); ts.forEach(file.semanticDiagnostics, addDiagnostic); }); - ts.forEach(program.getSourceFiles(), function (file) { + ts.forEach(host.getSourceFiles(), function (file) { if (!ts.isExternalModule(file)) { extendSymbolTable(globals, file.locals); } @@ -17604,7 +14630,7 @@ var ts; case 195 /* ModuleDeclaration */: case 194 /* EnumDeclaration */: case 198 /* ExportAssignment */: - case 170 /* VariableStatement */: + case 171 /* VariableStatement */: case 190 /* FunctionDeclaration */: case 193 /* TypeAliasDeclaration */: case 197 /* ImportDeclaration */: @@ -17821,7 +14847,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var i = 0, n = arguments.length; i < n; i++) { var arg = arguments[i]; - if (arg.kind === 167 /* OmittedExpression */) { + if (arg.kind === 168 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -17929,7 +14955,7 @@ var ts; for (var i = 0, n = node.properties.length; i < n; i++) { var prop = node.properties[i]; var name = prop.name; - if (prop.kind === 167 /* OmittedExpression */ || name.kind === 122 /* ComputedPropertyName */) { + if (prop.kind === 168 /* OmittedExpression */ || name.kind === 122 /* ComputedPropertyName */) { checkGrammarComputedPropertyName(name); continue; } @@ -18024,9 +15050,17 @@ var ts; } } function checkGrammarMethod(node) { - if (checkGrammarFunctionLikeDeclaration(node) || checkGrammarForGenerator(node)) { + if (checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarFunctionLikeDeclaration(node) || checkGrammarForGenerator(node)) { return true; } + if (node.parent.kind === 148 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } if (node.parent.kind === 191 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; @@ -18047,12 +15081,12 @@ var ts; } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: return true; - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -18064,17 +15098,17 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 178 /* ContinueStatement */ && !isIterationStatement(current.statement, true); + var isMisplacedContinueLabel = node.kind === 179 /* ContinueStatement */ && !isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); } return false; } break; - case 182 /* SwitchStatement */: - if (node.kind === 179 /* BreakStatement */ && !node.label) { + case 183 /* SwitchStatement */: + if (node.kind === 180 /* BreakStatement */ && !node.label) { return false; } break; @@ -18087,14 +15121,26 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 179 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + var message = node.kind === 180 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 179 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + var message = node.kind === 180 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== elements[elements.length - 1]) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } + if (node.initializer) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + } function checkGrammarVariableDeclaration(node) { if (ts.isInAmbientContext(node)) { if (ts.isBindingPattern(node.name)) { @@ -18116,45 +15162,43 @@ var ts; } return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } - function checkGrammarVariableDeclarations(container, declarations) { - if (declarations) { - if (checkGrammarForDisallowedTrailingComma(declarations)) { - return true; + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + if (compilerOptions.target < 2 /* ES6 */) { + if (ts.isLet(declarationList)) { + return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } - if (!declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(container), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - var decl = declarations[0]; - if (compilerOptions.target < 2 /* ES6 */) { - if (ts.isLet(decl)) { - return grammarErrorOnFirstToken(decl, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } - else if (ts.isConst(decl)) { - return grammarErrorOnFirstToken(decl, ts.Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } + else if (ts.isConst(declarationList)) { + return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } } } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 181 /* WithStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: return false; - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; } function checkGrammarForDisallowedLetOrConstStatement(node) { if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node)) { + if (ts.isLet(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (ts.isConst(node)) { + else if (ts.isConst(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } @@ -18275,7 +15319,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var i = 0, n = file.statements.length; i < n; i++) { var decl = file.statements[i]; - if (ts.isDeclaration(decl) || decl.kind === 170 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 171 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -18294,7 +15338,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isAnyFunction(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 169 /* Block */ || node.parent.kind === 196 /* ModuleBlock */ || node.parent.kind === 207 /* SourceFile */) { + if (node.parent.kind === 170 /* Block */ || node.parent.kind === 196 /* ModuleBlock */ || node.parent.kind === 207 /* SourceFile */) { var links = getNodeLinks(node.parent); if (!links.hasReportedStatementInAmbientContext) { return links.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -18329,6 +15373,3837 @@ var ts; ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + function shouldEmitToOwnFile(sourceFile, compilerOptions) { + if (!ts.isDeclarationFile(sourceFile)) { + if ((ts.isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + return true; + } + return false; + } + return false; + } + ts.shouldEmitToOwnFile = shouldEmitToOwnFile; + function isExternalModuleOrDeclarationFile(sourceFile) { + return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + } + ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + function createTextWriter(newLine) { + var output = ""; + var indent = 0; + var lineStart = true; + var lineCount = 0; + var linePos = 0; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + function writeTextOfNode(sourceFile, node) { + write(ts.getSourceTextOfNodeFromSourceFile(sourceFile, node)); + } + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { return indent++; }, + decreaseIndent: function () { return indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getText: function () { return output; } + }; + } + function getLineOfLocalPosition(currentSourceFile, pos) { + return currentSourceFile.getLineAndCharacterFromPosition(pos).line; + } + function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + writer.writeLine(); + } + } + function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + var emitLeadingSpace = !trailingSeparator; + ts.forEach(comments, function (comment) { + if (emitLeadingSpace) { + writer.write(" "); + emitLeadingSpace = false; + } + writeComment(currentSourceFile, writer, comment, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else if (trailingSeparator) { + writer.write(" "); + } + else { + emitLeadingSpace = true; + } + }); + } + function writeCommentRange(currentSourceFile, writer, comment, newLine) { + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); + var firstCommentLineIndent; + for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); + if (pos !== comment.pos) { + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); + } + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(pos, nextLineStart); + pos = nextLineStart; + } + } + else { + writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); + } + function writeTrimmedCurrentLine(pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); + if (currentLineText) { + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { + if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } + } + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 129 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + }); + } + function getAllAccessorDeclarations(node, accessor) { + var firstAccessor; + var getAccessor; + var setAccessor; + if (accessor.name.kind === 122 /* ComputedPropertyName */) { + firstAccessor = accessor; + if (accessor.kind === 130 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 131 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(node.members, function (member) { + if ((member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) && member.name.text === accessor.name.text && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { + if (!firstAccessor) { + firstAccessor = member; + } + if (member.kind === 130 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 131 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + }); + } + return { + firstAccessor: firstAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, host.getCurrentDirectory()); + sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + return ts.combinePaths(newDirPath, sourceFilePath); + } + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.outDir) { + var emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + } + else { + var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.filename); + } + return emitOutputFilePathWithoutExtension + extension; + } + function writeFile(host, diagnostics, filename, data, writeByteOrderMark) { + host.writeFile(filename, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); + }); + } + function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + var newLine = host.getNewLine(); + var compilerOptions = host.getCompilerOptions(); + var write; + var writeLine; + var increaseIndent; + var decreaseIndent; + var writeTextOfNode; + var writer = createAndSetNewTextWriterWithSymbolWriter(); + var enclosingDeclaration; + var currentSourceFile; + var reportedDeclarationError = false; + var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { + } : writeJsDocComments; + var aliasDeclarationEmitInfo = []; + function createAndSetNewTextWriterWithSymbolWriter() { + var writer = createTextWriter(newLine); + writer.trackSymbol = trackSymbol; + writer.writeKeyword = writer.write; + writer.writeOperator = writer.write; + writer.writePunctuation = writer.write; + writer.writeSpace = writer.write; + writer.writeStringLiteral = writer.writeLiteral; + writer.writeParameter = writer.write; + writer.writeSymbol = writer.write; + setWriter(writer); + return writer; + } + function setWriter(newWriter) { + writer = newWriter; + write = newWriter.write; + writeTextOfNode = newWriter.writeTextOfNode; + writeLine = newWriter.writeLine; + increaseIndent = newWriter.increaseIndent; + decreaseIndent = newWriter.decreaseIndent; + } + function writeAsychronousImportDeclarations(importDeclarations) { + var oldWriter = writer; + ts.forEach(importDeclarations, function (aliasToWrite) { + var aliasEmitInfo = ts.forEach(aliasDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined; }); + if (aliasEmitInfo) { + createAndSetNewTextWriterWithSymbolWriter(); + for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { + increaseIndent(); + } + writeImportDeclaration(aliasToWrite); + aliasEmitInfo.asynchronousOutput = writer.getText(); + } + }); + setWriter(oldWriter); + } + function handleSymbolAccessibilityError(symbolAccesibilityResult) { + if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { + if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { + writeAsychronousImportDeclarations(symbolAccesibilityResult.aliasesToMakeVisible); + } + } + else { + reportedDeclarationError = true; + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + else { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + } + function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (type) { + emitType(type); + } + else { + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + } + } + function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (signature.type) { + emitType(signature.type); + } + else { + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + } + } + function emitLines(nodes) { + for (var i = 0, n = nodes.length; i < n; i++) { + emitNode(nodes[i]); + } + } + function emitSeparatedList(nodes, separator, eachNodeEmitFn) { + var currentWriterPos = writer.getTextPos(); + for (var i = 0, n = nodes.length; i < n; i++) { + if (currentWriterPos !== writer.getTextPos()) { + write(separator); + } + currentWriterPos = writer.getTextPos(); + eachNodeEmitFn(nodes[i]); + } + } + function emitCommaList(nodes, eachNodeEmitFn) { + emitSeparatedList(nodes, ", ", eachNodeEmitFn); + } + function writeJsDocComments(declaration) { + if (declaration) { + var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); + emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + emitComments(currentSourceFile, writer, jsDocComments, true, newLine, writeCommentRange); + } + } + function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + emitType(type); + } + function emitType(type) { + switch (type.kind) { + case 110 /* AnyKeyword */: + case 119 /* StringKeyword */: + case 117 /* NumberKeyword */: + case 111 /* BooleanKeyword */: + case 98 /* VoidKeyword */: + case 8 /* StringLiteral */: + return writeTextOfNode(currentSourceFile, type); + case 135 /* TypeReference */: + return emitTypeReference(type); + case 138 /* TypeQuery */: + return emitTypeQuery(type); + case 140 /* ArrayType */: + return emitArrayType(type); + case 141 /* TupleType */: + return emitTupleType(type); + case 142 /* UnionType */: + return emitUnionType(type); + case 143 /* ParenthesizedType */: + return emitParenType(type); + case 136 /* FunctionType */: + case 137 /* ConstructorType */: + return emitSignatureDeclarationWithJsDocComments(type); + case 139 /* TypeLiteral */: + return emitTypeLiteral(type); + case 64 /* Identifier */: + return emitEntityName(type); + case 121 /* QualifiedName */: + return emitEntityName(type); + default: + ts.Debug.fail("Unknown type annotation: " + type.kind); + } + function emitEntityName(entityName) { + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 197 /* ImportDeclaration */ ? entityName.parent : enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + writeEntityName(entityName); + function writeEntityName(entityName) { + if (entityName.kind === 64 /* Identifier */) { + writeTextOfNode(currentSourceFile, entityName); + } + else { + var qualifiedName = entityName; + writeEntityName(qualifiedName.left); + write("."); + writeTextOfNode(currentSourceFile, qualifiedName.right); + } + } + } + function emitTypeReference(type) { + emitEntityName(type.typeName); + if (type.typeArguments) { + write("<"); + emitCommaList(type.typeArguments, emitType); + write(">"); + } + } + function emitTypeQuery(type) { + write("typeof "); + emitEntityName(type.exprName); + } + function emitArrayType(type) { + emitType(type.elementType); + write("[]"); + } + function emitTupleType(type) { + write("["); + emitCommaList(type.elementTypes, emitType); + write("]"); + } + function emitUnionType(type) { + emitSeparatedList(type.types, " | ", emitType); + } + function emitParenType(type) { + write("("); + emitType(type.type); + write(")"); + } + function emitTypeLiteral(type) { + write("{"); + if (type.members.length) { + writeLine(); + increaseIndent(); + emitLines(type.members); + decreaseIndent(); + } + write("}"); + } + } + function emitSourceFile(node) { + currentSourceFile = node; + enclosingDeclaration = node; + emitLines(node.statements); + } + function emitExportAssignment(node) { + write("export = "); + writeTextOfNode(currentSourceFile, node.exportName); + write(";"); + writeLine(); + } + function emitModuleElementDeclarationFlags(node) { + if (node.parent === currentSourceFile) { + if (node.flags & 1 /* Export */) { + write("export "); + } + if (node.kind !== 192 /* InterfaceDeclaration */) { + write("declare "); + } + } + } + function emitClassMemberDeclarationFlags(node) { + if (node.flags & 32 /* Private */) { + write("private "); + } + else if (node.flags & 64 /* Protected */) { + write("protected "); + } + if (node.flags & 128 /* Static */) { + write("static "); + } + } + function emitImportDeclaration(node) { + var nodeEmitInfo = { + declaration: node, + outputPos: writer.getTextPos(), + indent: writer.getIndent(), + hasWritten: resolver.isDeclarationVisible(node) + }; + aliasDeclarationEmitInfo.push(nodeEmitInfo); + if (nodeEmitInfo.hasWritten) { + writeImportDeclaration(node); + } + } + function writeImportDeclaration(node) { + emitJsDocComments(node); + if (node.flags & 1 /* Export */) { + write("export "); + } + write("import "); + writeTextOfNode(currentSourceFile, node.name); + write(" = "); + if (ts.isInternalModuleImportDeclaration(node)) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); + write(";"); + } + else { + write("require("); + writeTextOfNode(currentSourceFile, ts.getExternalModuleImportDeclarationExpression(node)); + write(");"); + } + writer.writeLine(); + function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + } + function emitModuleDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("module "); + writeTextOfNode(currentSourceFile, node.name); + while (node.body.kind !== 196 /* ModuleBlock */) { + node = node.body; + write("."); + writeTextOfNode(currentSourceFile, node.name); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitTypeAliasDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("type "); + writeTextOfNode(currentSourceFile, node.name); + write(" = "); + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); + write(";"); + writeLine(); + } + function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + function emitEnumDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isConst(node)) { + write("const "); + } + write("enum "); + writeTextOfNode(currentSourceFile, node.name); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + } + } + function emitEnumMemberDeclaration(node) { + emitJsDocComments(node); + writeTextOfNode(currentSourceFile, node.name); + var enumMemberValue = resolver.getEnumMemberValue(node); + if (enumMemberValue !== undefined) { + write(" = "); + write(enumMemberValue.toString()); + } + write(","); + writeLine(); + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 128 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + } + function emitTypeParameters(typeParameters) { + function emitTypeParameter(node) { + increaseIndent(); + emitJsDocComments(node); + decreaseIndent(); + writeTextOfNode(currentSourceFile, node.name); + if (node.constraint && !isPrivateMethodTypeParameter(node)) { + write(" extends "); + if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || (node.parent.parent && node.parent.parent.kind === 139 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 128 /* MethodDeclaration */ || node.parent.kind === 127 /* MethodSignature */ || node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.kind === 132 /* CallSignature */ || node.parent.kind === 133 /* ConstructSignature */); + emitType(node.constraint); + } + else { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); + } + } + function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.parent.kind) { + case 191 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 192 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 133 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 132 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + } + if (typeParameters) { + write("<"); + emitCommaList(typeParameters, emitTypeParameter); + write(">"); + } + } + function emitHeritageClause(typeReferences, isImplementsList) { + if (typeReferences) { + write(isImplementsList ? " implements " : " extends "); + emitCommaList(typeReferences, emitTypeOfTypeReference); + } + function emitTypeOfTypeReference(node) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); + function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.parent.parent.name + }; + } + } + } + function emitClassDeclaration(node) { + function emitParameterProperties(constructorDeclaration) { + if (constructorDeclaration) { + ts.forEach(constructorDeclaration.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + emitPropertyDeclaration(param); + } + }); + } + } + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("class "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + var baseTypeNode = ts.getClassBaseTypeNode(node); + if (baseTypeNode) { + emitHeritageClause([baseTypeNode], false); + } + emitHeritageClause(ts.getClassImplementedTypeNodes(node), true); + write(" {"); + writeLine(); + increaseIndent(); + emitParameterProperties(getFirstConstructorWithBody(node)); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitInterfaceDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("interface "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitPropertyDeclaration(node) { + emitJsDocComments(node); + emitClassMemberDeclarationFlags(node); + emitVariableDeclaration(node); + write(";"); + writeLine(); + } + function emitVariableDeclaration(node) { + if (node.kind !== 188 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + writeTextOfNode(currentSourceFile, node.name); + if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && ts.hasQuestionToken(node)) { + write("?"); + } + if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && node.parent.kind === 139 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (node.kind === 188 /* VariableDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + else if (node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) { + if (node.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + } + function emitTypeOfVariableDeclarationFromTypeLiteral(node) { + if (node.type) { + write(": "); + emitType(node.type); + } + } + function emitVariableStatement(node) { + var hasDeclarationWithEmit = ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + if (hasDeclarationWithEmit) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isLet(node.declarationList)) { + write("let "); + } + else if (ts.isConst(node.declarationList)) { + write("const "); + } + else { + write("var "); + } + emitCommaList(node.declarationList.declarations, emitVariableDeclaration); + write(";"); + writeLine(); + } + } + function emitAccessorDeclaration(node) { + var accessors = getAllAccessorDeclarations(node.parent, node); + if (node === accessors.firstAccessor) { + emitJsDocComments(accessors.getAccessor); + emitJsDocComments(accessors.setAccessor); + emitClassMemberDeclarationFlags(node); + writeTextOfNode(currentSourceFile, node.name); + if (!(node.flags & 32 /* Private */)) { + var accessorWithTypeAnnotation = node; + var type = getTypeAnnotationFromAccessor(node); + if (!type) { + var anotherAccessor = node.kind === 130 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + type = getTypeAnnotationFromAccessor(anotherAccessor); + if (type) { + accessorWithTypeAnnotation = anotherAccessor; + } + } + writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); + } + write(";"); + writeLine(); + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 130 /* GetAccessor */ ? accessor.type : accessor.parameters[0].type; + } + } + function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (accessorWithTypeAnnotation.kind === 131 /* SetAccessor */) { + if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.parameters[0], + typeName: accessorWithTypeAnnotation.name + }; + } + else { + if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: undefined + }; + } + } + } + function emitFunctionDeclaration(node) { + if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { + emitJsDocComments(node); + if (node.kind === 190 /* FunctionDeclaration */) { + emitModuleElementDeclarationFlags(node); + } + else if (node.kind === 128 /* MethodDeclaration */) { + emitClassMemberDeclarationFlags(node); + } + if (node.kind === 190 /* FunctionDeclaration */) { + write("function "); + writeTextOfNode(currentSourceFile, node.name); + } + else if (node.kind === 129 /* Constructor */) { + write("constructor"); + } + else { + writeTextOfNode(currentSourceFile, node.name); + if (ts.hasQuestionToken(node)) { + write("?"); + } + } + emitSignatureDeclaration(node); + } + } + function emitSignatureDeclarationWithJsDocComments(node) { + emitJsDocComments(node); + emitSignatureDeclaration(node); + } + function emitSignatureDeclaration(node) { + if (node.kind === 133 /* ConstructSignature */ || node.kind === 137 /* ConstructorType */) { + write("new "); + } + emitTypeParameters(node.typeParameters); + if (node.kind === 134 /* IndexSignature */) { + write("["); + } + else { + write("("); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitCommaList(node.parameters, emitParameterDeclaration); + if (node.kind === 134 /* IndexSignature */) { + write("]"); + } + else { + write(")"); + } + var isFunctionTypeOrConstructorType = node.kind === 136 /* FunctionType */ || node.kind === 137 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 139 /* TypeLiteral */) { + if (node.type) { + write(isFunctionTypeOrConstructorType ? " => " : ": "); + emitType(node.type); + } + } + else if (node.kind !== 129 /* Constructor */ && !(node.flags & 32 /* Private */)) { + writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); + } + enclosingDeclaration = prevEnclosingDeclaration; + if (!isFunctionTypeOrConstructorType) { + write(";"); + writeLine(); + } + function getReturnTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 133 /* ConstructSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 132 /* CallSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 134 /* IndexSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + } + function emitParameterDeclaration(node) { + increaseIndent(); + emitJsDocComments(node); + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + write("_" + ts.indexOf(node.parent.parameters, node)); + } + else { + writeTextOfNode(currentSourceFile, node.name); + } + if (node.initializer || ts.hasQuestionToken(node)) { + write("?"); + } + decreaseIndent(); + if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.parent.kind === 139 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.parent.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); + } + function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.parent.kind) { + case 129 /* Constructor */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + break; + case 133 /* ConstructSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 132 /* CallSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + } + function emitNode(node) { + switch (node.kind) { + case 129 /* Constructor */: + case 190 /* FunctionDeclaration */: + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + return emitFunctionDeclaration(node); + case 133 /* ConstructSignature */: + case 132 /* CallSignature */: + case 134 /* IndexSignature */: + return emitSignatureDeclarationWithJsDocComments(node); + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 171 /* VariableStatement */: + return emitVariableStatement(node); + case 126 /* PropertyDeclaration */: + case 125 /* PropertySignature */: + return emitPropertyDeclaration(node); + case 192 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 191 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 193 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 206 /* EnumMember */: + return emitEnumMemberDeclaration(node); + case 194 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 195 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 197 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 198 /* ExportAssignment */: + return emitExportAssignment(node); + case 207 /* SourceFile */: + return emitSourceFile(node); + } + } + var referencePathsOutput = ""; + function writeReferencePath(referencedFile) { + var declFileName = referencedFile.flags & 1024 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile, compilerOptions) ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") : ts.removeFileExtension(compilerOptions.out) + ".d.ts"; + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + if (root) { + if (!compilerOptions.noResolve) { + var addedGlobalFileReference = false; + ts.forEach(root.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); + if (referencedFile && ((referencedFile.flags & 1024 /* DeclarationFile */) || shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { + writeReferencePath(referencedFile); + if (!isExternalModuleOrDeclarationFile(referencedFile)) { + addedGlobalFileReference = true; + } + } + }); + } + emitNode(root); + } + else { + var emittedReferencedFiles = []; + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + if (!compilerOptions.noResolve) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && !ts.contains(emittedReferencedFiles, referencedFile))) { + writeReferencePath(referencedFile); + emittedReferencedFiles.push(referencedFile); + } + }); + } + emitNode(sourceFile); + } + }); + } + return { + reportedDeclarationError: reportedDeclarationError, + aliasDeclarationEmitInfo: aliasDeclarationEmitInfo, + synchronousDeclarationOutput: writer.getText(), + referencePathsOutput: referencePathsOutput + }; + } + function getDeclarationDiagnostics(host, resolver, targetSourceFile) { + var diagnostics = []; + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); + return diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + function emitFiles(resolver, host, targetSourceFile) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; + var diagnostics = []; + var newLine = host.getNewLine(); + function emitJavaScript(jsFilePath, root) { + var writer = createTextWriter(newLine); + var write = writer.write; + var writeTextOfNode = writer.writeTextOfNode; + var writeLine = writer.writeLine; + var increaseIndent = writer.increaseIndent; + var decreaseIndent = writer.decreaseIndent; + var currentSourceFile; + var extendsEmitted = false; + var tempCount = 0; + var tempVariables; + var tempParameters; + var writeEmittedFiles = writeJavaScriptFile; + var emitLeadingComments = compilerOptions.removeComments ? function (node) { + } : emitLeadingDeclarationComments; + var emitTrailingComments = compilerOptions.removeComments ? function (node) { + } : emitTrailingDeclarationComments; + var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { + } : emitLeadingCommentsOfLocalPosition; + var detachedCommentsInfo; + var emitDetachedComments = compilerOptions.removeComments ? function (node) { + } : emitDetachedCommentsAtPosition; + var emitPinnedOrTripleSlashComments = compilerOptions.removeComments ? function (node) { + } : emitPinnedOrTripleSlashCommentsOfNode; + var writeComment = writeCommentRange; + var emit = emitNode; + var emitStart = function (node) { + }; + var emitEnd = function (node) { + }; + var emitToken = emitTokenText; + var scopeEmitStart = function (scopeDeclaration, scopeName) { + }; + var scopeEmitEnd = function () { + }; + var sourceMapData; + function initializeEmitterWithSourceMaps() { + var sourceMapDir; + var sourceMapSourceIndex = -1; + var sourceMapNameIndexMap = {}; + var sourceMapNameIndices = []; + function getSourceMapNameIndex() { + return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + } + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + var lastEncodedNameIndex = 0; + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + function base64VLQFormatEncode(inValue) { + function base64FormatEncode(inValue) { + if (inValue < 64) { + return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } + } + function recordSourceMapSpan(pos) { + var sourceLinePos = currentSourceFile.getLineAndCharacterFromPosition(pos); + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine != emittedLine || lastRecordedSourceMapSpan.emittedColumn != emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + nameIndex: getSourceMapNameIndex(), + sourceIndex: sourceMapSourceIndex + }; + } + else { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function recordEmitNodeStartSpan(node) { + recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); + } + function recordEmitNodeEndSpan(node) { + recordSourceMapSpan(node.end); + } + function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + recordSourceMapSpan(tokenStartPos); + var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + recordSourceMapSpan(tokenEndPos); + return tokenEndPos; + } + function recordNewSourceFileStart(node) { + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, host.getCurrentDirectory(), host.getCanonicalFileName, true)); + sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; + sourceMapData.inputSourceFileNames.push(node.filename); + } + function recordScopeNameOfNode(node, scopeName) { + function recordScopeNameIndex(scopeNameIndex) { + sourceMapNameIndices.push(scopeNameIndex); + } + function recordScopeNameStart(scopeName) { + var scopeNameIndex = -1; + if (scopeName) { + var parentIndex = getSourceMapNameIndex(); + if (parentIndex !== -1) { + scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; + } + scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); + if (scopeNameIndex === undefined) { + scopeNameIndex = sourceMapData.sourceMapNames.length; + sourceMapData.sourceMapNames.push(scopeName); + sourceMapNameIndexMap[scopeName] = scopeNameIndex; + } + } + recordScopeNameIndex(scopeNameIndex); + } + if (scopeName) { + recordScopeNameStart(scopeName); + } + else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { + if (node.name) { + scopeName = node.name.text; + } + recordScopeNameStart(scopeName); + } + else { + recordScopeNameIndex(getSourceMapNameIndex()); + } + } + function recordScopeNameEnd() { + sourceMapNameIndices.pop(); + } + ; + function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { + recordSourceMapSpan(comment.pos); + writeCommentRange(currentSourceFile, writer, comment, newLine); + recordSourceMapSpan(comment.end); + } + function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings) { + if (typeof JSON !== "undefined") { + return JSON.stringify({ + version: version, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings + }); + } + return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\"}"; + function serializeStringArray(list) { + var output = ""; + for (var i = 0, n = list.length; i < n; i++) { + if (i) { + output += ","; + } + output += "\"" + ts.escapeString(list[i]) + "\""; + } + return output; + } + } + function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { + encodeLastRecordedSourceMapSpan(); + writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings), false); + sourceMapDataList.push(sourceMapData); + writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL, writeByteOrderMark); + } + var sourceMapJsFile = ts.getBaseFilename(ts.normalizeSlashes(jsFilePath)); + sourceMapData = { + sourceMapFilePath: jsFilePath + ".map", + jsSourceMappingURL: sourceMapJsFile + ".map", + sourceMapFile: sourceMapJsFile, + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (root) { + sourceMapDir = ts.getDirectoryPath(getSourceFilePathInNewDir(root, host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); + } + function emitNodeWithMap(node) { + if (node) { + if (node.kind != 207 /* SourceFile */) { + recordEmitNodeStartSpan(node); + emitNode(node); + recordEmitNodeEndSpan(node); + } + else { + recordNewSourceFileStart(node); + emitNode(node); + } + } + } + writeEmittedFiles = writeJavaScriptAndSourceMapFile; + emit = emitNodeWithMap; + emitStart = recordEmitNodeStartSpan; + emitEnd = recordEmitNodeEndSpan; + emitToken = writeTextWithSpanRecord; + scopeEmitStart = recordScopeNameOfNode; + scopeEmitEnd = recordScopeNameEnd; + writeComment = writeCommentRangeWithMap; + } + function writeJavaScriptFile(emitOutput, writeByteOrderMark) { + writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + } + function createTempVariable(location, forLoopVariable) { + var name = forLoopVariable ? "_i" : undefined; + while (true) { + if (name && resolver.isUnknownIdentifier(location, name)) { + break; + } + name = "_" + (tempCount < 25 ? String.fromCharCode(tempCount + (tempCount < 8 ? 0 : 1) + 97 /* a */) : tempCount - 25); + tempCount++; + } + var result = ts.createNode(64 /* Identifier */); + result.text = name; + return result; + } + function recordTempDeclaration(name) { + if (!tempVariables) { + tempVariables = []; + } + tempVariables.push(name); + } + function emitTempDeclarations(newLine) { + if (tempVariables) { + if (newLine) { + writeLine(); + } + else { + write(" "); + } + write("var "); + emitCommaList(tempVariables); + write(";"); + } + } + function emitTokenText(tokenKind, startPos, emitFn) { + var tokenString = ts.tokenToString(tokenKind); + if (emitFn) { + emitFn(); + } + else { + write(tokenString); + } + return startPos + tokenString.length; + } + function emitOptional(prefix, node) { + if (node) { + write(prefix); + emit(node); + } + } + function emitParenthesized(node, parenthesized) { + if (parenthesized) { + write("("); + } + emit(node); + if (parenthesized) { + write(")"); + } + } + function emitTrailingCommaIfPresent(nodeList) { + if (nodeList.hasTrailingComma) { + write(","); + } + } + function emitList(nodes, start, count, multiLine, trailingComma) { + if (multiLine) { + increaseIndent(); + } + for (var i = 0; i < count; i++) { + if (multiLine) { + if (i) { + write(","); + } + writeLine(); + } + else { + if (i) { + write(", "); + } + } + emit(nodes[start + i]); + } + if (trailingComma) { + write(","); + } + if (multiLine) { + decreaseIndent(); + writeLine(); + } + } + function emitCommaList(nodes) { + if (nodes) { + emitList(nodes, 0, nodes.length, false, false); + } + } + function emitMultiLineList(nodes) { + if (nodes) { + emitList(nodes, 0, nodes.length, true, false); + } + } + function emitLines(nodes) { + emitLinesStartingAt(nodes, 0); + } + function emitLinesStartingAt(nodes, startIndex) { + for (var i = startIndex; i < nodes.length; i++) { + writeLine(); + emit(nodes[i]); + } + } + function isBinaryOrOctalIntegerLiteral(text) { + if (text.length <= 0) { + return false; + } + if (text.charCodeAt(1) === 66 /* B */ || text.charCodeAt(1) === 98 /* b */ || text.charCodeAt(1) === 79 /* O */ || text.charCodeAt(1) === 111 /* o */) { + return true; + } + return false; + } + function emitLiteral(node) { + var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; + if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { + write(node.text); + } + else { + write(text); + } + } + function getTemplateLiteralAsStringLiteral(node) { + return '"' + ts.escapeString(node.text) + '"'; + } + function emitTemplateExpression(node) { + if (compilerOptions.target >= 2 /* ES6 */) { + ts.forEachChild(node, emit); + return; + } + ts.Debug.assert(node.parent.kind !== 153 /* TaggedTemplateExpression */); + var emitOuterParens = ts.isExpression(node.parent) && templateNeedsParens(node, node.parent); + if (emitOuterParens) { + write("("); + } + emitLiteral(node.head); + ts.forEach(node.templateSpans, function (templateSpan) { + var needsParens = templateSpan.expression.kind !== 155 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; + write(" + "); + emitParenthesized(templateSpan.expression, needsParens); + if (templateSpan.literal.text.length !== 0) { + write(" + "); + emitLiteral(templateSpan.literal); + } + }); + if (emitOuterParens) { + write(")"); + } + function templateNeedsParens(template, parent) { + switch (parent.kind) { + case 151 /* CallExpression */: + case 152 /* NewExpression */: + return parent.expression === template; + case 155 /* ParenthesizedExpression */: + return false; + case 153 /* TaggedTemplateExpression */: + ts.Debug.fail("Path should be unreachable; tagged templates not supported pre-ES6."); + default: + return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; + } + } + function comparePrecedenceToBinaryPlus(expression) { + ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); + switch (expression.kind) { + case 163 /* BinaryExpression */: + switch (expression.operator) { + case 35 /* AsteriskToken */: + case 36 /* SlashToken */: + case 37 /* PercentToken */: + return 1 /* GreaterThan */; + case 33 /* PlusToken */: + return 0 /* EqualTo */; + default: + return -1 /* LessThan */; + } + case 164 /* ConditionalExpression */: + return -1 /* LessThan */; + default: + return 1 /* GreaterThan */; + } + } + } + function emitTemplateSpan(span) { + emit(span.expression); + emit(span.literal); + } + function emitExpressionForPropertyName(node) { + if (node.kind === 8 /* StringLiteral */) { + emitLiteral(node); + } + else if (node.kind === 122 /* ComputedPropertyName */) { + emit(node.expression); + } + else { + write("\""); + if (node.kind === 7 /* NumericLiteral */) { + write(node.text); + } + else { + writeTextOfNode(currentSourceFile, node); + } + write("\""); + } + } + function isNotExpressionIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 124 /* Parameter */: + case 188 /* VariableDeclaration */: + case 146 /* BindingElement */: + case 126 /* PropertyDeclaration */: + case 125 /* PropertySignature */: + case 204 /* PropertyAssignment */: + case 205 /* ShorthandPropertyAssignment */: + case 206 /* EnumMember */: + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + case 190 /* FunctionDeclaration */: + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + case 156 /* FunctionExpression */: + case 191 /* ClassDeclaration */: + case 192 /* InterfaceDeclaration */: + case 194 /* EnumDeclaration */: + case 195 /* ModuleDeclaration */: + case 197 /* ImportDeclaration */: + return parent.name === node; + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 198 /* ExportAssignment */: + return false; + case 184 /* LabeledStatement */: + return node.parent.label === node; + case 203 /* CatchClause */: + return node.parent.name === node; + } + } + function emitExpressionIdentifier(node) { + var prefix = resolver.getExpressionNamePrefix(node); + if (prefix) { + write(prefix); + write("."); + } + writeTextOfNode(currentSourceFile, node); + } + function emitIdentifier(node) { + if (!node.parent) { + write(node.text); + } + else if (!isNotExpressionIdentifier(node)) { + emitExpressionIdentifier(node); + } + else { + writeTextOfNode(currentSourceFile, node); + } + } + function emitThis(node) { + if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { + write("_this"); + } + else { + write("this"); + } + } + function emitSuper(node) { + var flags = resolver.getNodeCheckFlags(node); + if (flags & 16 /* SuperInstance */) { + write("_super.prototype"); + } + else if (flags & 32 /* SuperStatic */) { + write("_super"); + } + else { + write("super"); + } + } + function emitObjectBindingPattern(node) { + write("{ "); + var elements = node.elements; + emitList(elements, 0, elements.length, false, elements.hasTrailingComma); + write(" }"); + } + function emitArrayBindingPattern(node) { + write("["); + var elements = node.elements; + emitList(elements, 0, elements.length, false, elements.hasTrailingComma); + write("]"); + } + function emitBindingElement(node) { + if (node.propertyName) { + emit(node.propertyName); + write(": "); + } + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + emit(node.name); + } + else { + emitModuleMemberName(node); + } + emitOptional(" = ", node.initializer); + } + function emitSpreadElementExpression(node) { + write("..."); + emit(node.expression); + } + function needsParenthesisForPropertyAccess(node) { + switch (node.kind) { + case 64 /* Identifier */: + case 147 /* ArrayLiteralExpression */: + case 149 /* PropertyAccessExpression */: + case 150 /* ElementAccessExpression */: + case 151 /* CallExpression */: + case 155 /* ParenthesizedExpression */: + return false; + } + return true; + } + function emitArrayLiteral(node) { + var elements = node.elements; + var length = elements.length; + if (length === 0) { + write("[]"); + return; + } + if (compilerOptions.target >= 2 /* ES6 */) { + write("["); + emitList(elements, 0, elements.length, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); + write("]"); + return; + } + var pos = 0; + var group = 0; + while (pos < length) { + if (group === 1) { + write(".concat("); + } + else if (group > 1) { + write(", "); + } + var e = elements[pos]; + if (e.kind === 167 /* SpreadElementExpression */) { + e = e.expression; + emitParenthesized(e, group === 0 && needsParenthesisForPropertyAccess(e)); + pos++; + } + else { + var i = pos; + while (i < length && elements[i].kind !== 167 /* SpreadElementExpression */) { + i++; + } + write("["); + emitList(elements, pos, i - pos, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); + write("]"); + pos = i; + } + group++; + } + if (group > 1) { + write(")"); + } + } + function emitObjectLiteral(node) { + write("{"); + var properties = node.properties; + if (properties.length) { + var multiLine = (node.flags & 256 /* MultiLine */) !== 0; + if (!multiLine) { + write(" "); + } + emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && compilerOptions.target >= 1 /* ES5 */); + if (!multiLine) { + write(" "); + } + } + write("}"); + } + function emitComputedPropertyName(node) { + write("["); + emit(node.expression); + write("]"); + } + function emitMethod(node) { + if (!ts.isObjectLiteralMethod(node)) { + return; + } + emitLeadingComments(node); + emit(node.name); + if (compilerOptions.target < 2 /* ES6 */) { + write(": function "); + } + emitSignatureAndBody(node); + emitTrailingComments(node); + } + function emitPropertyAssignment(node) { + emitLeadingComments(node); + emit(node.name); + write(": "); + emit(node.initializer); + emitTrailingComments(node); + } + function emitShorthandPropertyAssignment(node) { + emitLeadingComments(node); + emit(node.name); + if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { + write(": "); + emitExpressionIdentifier(node.name); + } + emitTrailingComments(node); + } + function tryEmitConstantValue(node) { + var constantValue = resolver.getConstantValue(node); + if (constantValue !== undefined) { + var propertyName = node.kind === 149 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + write(constantValue.toString() + " /* " + propertyName + " */"); + return true; + } + return false; + } + function emitPropertyAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + write("."); + emit(node.name); + } + function emitQualifiedName(node) { + emit(node.left); + write("."); + emit(node.right); + } + function emitIndexedAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + write("["); + emit(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + var superCall = false; + if (node.expression.kind === 90 /* SuperKeyword */) { + write("_super"); + superCall = true; + } + else { + emit(node.expression); + superCall = node.expression.kind === 149 /* PropertyAccessExpression */ && node.expression.expression.kind === 90 /* SuperKeyword */; + } + if (superCall) { + write(".call("); + emitThis(node.expression); + if (node.arguments.length) { + write(", "); + emitCommaList(node.arguments); + } + write(")"); + } + else { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitNewExpression(node) { + write("new "); + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitTaggedTemplateExpression(node) { + ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); + emit(node.tag); + write(" "); + emit(node.template); + } + function emitParenExpression(node) { + if (node.expression.kind === 154 /* TypeAssertionExpression */) { + var operand = node.expression.expression; + while (operand.kind == 154 /* TypeAssertionExpression */) { + operand = operand.expression; + } + if (operand.kind !== 161 /* PrefixUnaryExpression */ && operand.kind !== 160 /* VoidExpression */ && operand.kind !== 159 /* TypeOfExpression */ && operand.kind !== 158 /* DeleteExpression */ && operand.kind !== 162 /* PostfixUnaryExpression */ && operand.kind !== 152 /* NewExpression */ && !(operand.kind === 151 /* CallExpression */ && node.parent.kind === 152 /* NewExpression */) && !(operand.kind === 156 /* FunctionExpression */ && node.parent.kind === 151 /* CallExpression */)) { + emit(operand); + return; + } + } + write("("); + emit(node.expression); + write(")"); + } + function emitDeleteExpression(node) { + write(ts.tokenToString(73 /* DeleteKeyword */)); + write(" "); + emit(node.expression); + } + function emitVoidExpression(node) { + write(ts.tokenToString(98 /* VoidKeyword */)); + write(" "); + emit(node.expression); + } + function emitTypeOfExpression(node) { + write(ts.tokenToString(96 /* TypeOfKeyword */)); + write(" "); + emit(node.expression); + } + function emitPrefixUnaryExpression(node) { + write(ts.tokenToString(node.operator)); + if (node.operand.kind === 161 /* PrefixUnaryExpression */) { + var operand = node.operand; + if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { + write(" "); + } + else if (node.operator === 34 /* MinusToken */ && (operand.operator === 34 /* MinusToken */ || operand.operator === 39 /* MinusMinusToken */)) { + write(" "); + } + } + emit(node.operand); + } + function emitPostfixUnaryExpression(node) { + emit(node.operand); + write(ts.tokenToString(node.operator)); + } + function emitBinaryExpression(node) { + if (compilerOptions.target < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { + emitDestructuring(node); + } + else { + emit(node.left); + if (node.operator !== 23 /* CommaToken */) + write(" "); + write(ts.tokenToString(node.operator)); + write(" "); + emit(node.right); + } + } + function emitConditionalExpression(node) { + emit(node.condition); + write(" ? "); + emit(node.whenTrue); + write(" : "); + emit(node.whenFalse); + } + function emitBlock(node) { + emitToken(14 /* OpenBraceToken */, node.pos); + increaseIndent(); + scopeEmitStart(node.parent); + if (node.kind === 196 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 195 /* ModuleDeclaration */); + emitCaptureThisForNodeIfNecessary(node.parent); + } + emitLines(node.statements); + if (node.kind === 196 /* ModuleBlock */) { + emitTempDeclarations(true); + } + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.statements.end); + scopeEmitEnd(); + } + function emitEmbeddedStatement(node) { + if (node.kind === 170 /* Block */) { + write(" "); + emit(node); + } + else { + increaseIndent(); + writeLine(); + emit(node); + decreaseIndent(); + } + } + function emitExpressionStatement(node) { + emitLeadingComments(node); + emitParenthesized(node.expression, node.expression.kind === 157 /* ArrowFunction */); + write(";"); + emitTrailingComments(node); + } + function emitIfStatement(node) { + emitLeadingComments(node); + var endPos = emitToken(83 /* IfKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + emit(node.expression); + emitToken(17 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + emitToken(75 /* ElseKeyword */, node.thenStatement.end); + if (node.elseStatement.kind === 174 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + emitTrailingComments(node); + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (node.statement.kind === 170 /* Block */) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emit(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var endPos = emitToken(81 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + if (node.initializer && node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + var declarations = variableDeclarationList.declarations; + if (declarations[0] && ts.isLet(declarations[0])) { + emitToken(103 /* LetKeyword */, endPos); + } + else if (declarations[0] && ts.isConst(declarations[0])) { + emitToken(69 /* ConstKeyword */, endPos); + } + else { + emitToken(97 /* VarKeyword */, endPos); + } + write(" "); + emitCommaList(variableDeclarationList.declarations); + } + else if (node.initializer) { + emit(node.initializer); + } + write(";"); + emitOptional(" ", node.condition); + write(";"); + emitOptional(" ", node.iterator); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var endPos = emitToken(81 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + if (ts.isLet(decl)) { + emitToken(103 /* LetKeyword */, endPos); + } + else { + emitToken(97 /* VarKeyword */, endPos); + } + write(" "); + emit(decl); + } + } + else { + emit(node.initializer); + } + write(" in "); + emit(node.expression); + emitToken(17 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitBreakOrContinueStatement(node) { + emitToken(node.kind === 180 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */, node.pos); + emitOptional(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + emitLeadingComments(node); + emitToken(89 /* ReturnKeyword */, node.pos); + emitOptional(" ", node.expression); + write(";"); + emitTrailingComments(node); + } + function emitWithStatement(node) { + write("with ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var endPos = emitToken(91 /* SwitchKeyword */, node.pos); + write(" "); + emitToken(16 /* OpenParenToken */, endPos); + emit(node.expression); + endPos = emitToken(17 /* CloseParenToken */, node.expression.end); + write(" "); + emitToken(14 /* OpenBraceToken */, endPos); + increaseIndent(); + emitLines(node.clauses); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.clauses.end); + } + function isOnSameLine(node1, node2) { + return getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + } + function emitCaseOrDefaultClause(node) { + if (node.kind === 200 /* CaseClause */) { + write("case "); + emit(node.expression); + write(":"); + } + else { + write("default:"); + } + if (node.statements.length === 1 && isOnSameLine(node, node.statements[0])) { + write(" "); + emit(node.statements[0]); + } + else { + increaseIndent(); + emitLines(node.statements); + decreaseIndent(); + } + } + function emitThrowStatement(node) { + write("throw "); + emit(node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitCatchClause(node) { + writeLine(); + var endPos = emitToken(67 /* CatchKeyword */, node.pos); + write(" "); + emitToken(16 /* OpenParenToken */, endPos); + emit(node.name); + emitToken(17 /* CloseParenToken */, node.name.end); + write(" "); + emitBlock(node.block); + } + function emitDebuggerStatement(node) { + emitToken(71 /* DebuggerKeyword */, node.pos); + write(";"); + } + function emitLabelledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function getContainingModule(node) { + do { + node = node.parent; + } while (node && node.kind !== 195 /* ModuleDeclaration */); + return node; + } + function emitModuleMemberName(node) { + emitStart(node.name); + if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + var container = getContainingModule(node); + write(container ? resolver.getLocalNameOfContainer(container) : "exports"); + write("."); + } + emitNode(node.name); + emitEnd(node.name); + } + function emitDestructuring(root, value) { + var emitCount = 0; + var isDeclaration = (root.kind === 188 /* VariableDeclaration */ && !(ts.getCombinedNodeFlags(root) & 1 /* Export */)) || root.kind === 124 /* Parameter */; + if (root.kind === 163 /* BinaryExpression */) { + emitAssignmentExpression(root); + } + else { + emitBindingElement(root, value); + } + function emitAssignment(name, value) { + if (emitCount++) { + write(", "); + } + if (name.parent && (name.parent.kind === 188 /* VariableDeclaration */ || name.parent.kind === 146 /* BindingElement */)) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + } + function ensureIdentifier(expr) { + if (expr.kind !== 64 /* Identifier */) { + var identifier = createTempVariable(root); + if (!isDeclaration) { + recordTempDeclaration(identifier); + } + emitAssignment(identifier, expr); + expr = identifier; + } + return expr; + } + function createVoidZero() { + var zero = ts.createNode(7 /* NumericLiteral */); + zero.text = "0"; + var result = ts.createNode(160 /* VoidExpression */); + result.expression = zero; + return result; + } + function createDefaultValueCheck(value, defaultValue) { + value = ensureIdentifier(value); + var equals = ts.createNode(163 /* BinaryExpression */); + equals.left = value; + equals.operator = 30 /* EqualsEqualsEqualsToken */; + equals.right = createVoidZero(); + var cond = ts.createNode(164 /* ConditionalExpression */); + cond.condition = equals; + cond.whenTrue = defaultValue; + cond.whenFalse = value; + return cond; + } + function createNumericLiteral(value) { + var node = ts.createNode(7 /* NumericLiteral */); + node.text = "" + value; + return node; + } + function parenthesizeForAccess(expr) { + if (expr.kind === 64 /* Identifier */ || expr.kind === 149 /* PropertyAccessExpression */ || expr.kind === 150 /* ElementAccessExpression */) { + return expr; + } + var node = ts.createNode(155 /* ParenthesizedExpression */); + node.expression = expr; + return node; + } + function createPropertyAccess(object, propName) { + if (propName.kind !== 64 /* Identifier */) { + return createElementAccess(object, propName); + } + var node = ts.createNode(149 /* PropertyAccessExpression */); + node.expression = parenthesizeForAccess(object); + node.name = propName; + return node; + } + function createElementAccess(object, index) { + var node = ts.createNode(150 /* ElementAccessExpression */); + node.expression = parenthesizeForAccess(object); + node.argumentExpression = index; + return node; + } + function emitObjectLiteralAssignment(target, value) { + var properties = target.properties; + if (properties.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < properties.length; i++) { + var p = properties[i]; + if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { + var propName = (p.name); + emitDestructuringAssignment(p.initializer || propName, createPropertyAccess(value, propName)); + } + } + } + function emitArrayLiteralAssignment(target, value) { + var elements = target.elements; + if (elements.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < elements.length; i++) { + var e = elements[i]; + if (e.kind !== 168 /* OmittedExpression */) { + if (e.kind !== 167 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccess(value, createNumericLiteral(i))); + } + else { + if (i === elements.length - 1) { + value = ensureIdentifier(value); + emitAssignment(e.expression, value); + write(".slice(" + i + ")"); + } + } + } + } + } + function emitDestructuringAssignment(target, value) { + if (target.kind === 163 /* BinaryExpression */ && target.operator === 52 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right); + target = target.left; + } + if (target.kind === 148 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value); + } + else if (target.kind === 147 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value); + } + else { + emitAssignment(target, value); + } + } + function emitAssignmentExpression(root) { + var target = root.left; + var value = root.right; + if (root.parent.kind === 173 /* ExpressionStatement */) { + emitDestructuringAssignment(target, value); + } + else { + if (root.parent.kind !== 155 /* ParenthesizedExpression */) { + write("("); + } + value = ensureIdentifier(value); + emitDestructuringAssignment(target, value); + write(", "); + emit(value); + if (root.parent.kind !== 155 /* ParenthesizedExpression */) { + write(")"); + } + } + } + function emitBindingElement(target, value) { + if (target.initializer) { + value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + } + else if (!value) { + value = createVoidZero(); + } + if (ts.isBindingPattern(target.name)) { + var pattern = target.name; + var elements = pattern.elements; + if (elements.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + if (pattern.kind === 144 /* ObjectBindingPattern */) { + var propName = element.propertyName || element.name; + emitBindingElement(element, createPropertyAccess(value, propName)); + } + else if (element.kind !== 168 /* OmittedExpression */) { + if (!element.dotDotDotToken) { + emitBindingElement(element, createElementAccess(value, createNumericLiteral(i))); + } + else { + if (i === elements.length - 1) { + value = ensureIdentifier(value); + emitAssignment(element.name, value); + write(".slice(" + i + ")"); + } + } + } + } + } + else { + emitAssignment(target.name, value); + } + } + } + function emitVariableDeclaration(node) { + emitLeadingComments(node); + if (ts.isBindingPattern(node.name)) { + if (compilerOptions.target < 2 /* ES6 */) { + emitDestructuring(node); + } + else { + emit(node.name); + emitOptional(" = ", node.initializer); + } + } + else { + emitModuleMemberName(node); + emitOptional(" = ", node.initializer); + } + emitTrailingComments(node); + } + function emitVariableStatement(node) { + emitLeadingComments(node); + if (!(node.flags & 1 /* Export */)) { + if (ts.isLet(node.declarationList)) { + write("let "); + } + else if (ts.isConst(node.declarationList)) { + write("const "); + } + else { + write("var "); + } + } + emitCommaList(node.declarationList.declarations); + write(";"); + emitTrailingComments(node); + } + function emitParameter(node) { + emitLeadingComments(node); + if (compilerOptions.target < 2 /* ES6 */) { + if (ts.isBindingPattern(node.name)) { + var name = createTempVariable(node); + if (!tempParameters) { + tempParameters = []; + } + tempParameters.push(name); + emit(name); + } + else { + emit(node.name); + } + } + else { + if (node.dotDotDotToken) { + write("..."); + } + emit(node.name); + emitOptional(" = ", node.initializer); + } + emitTrailingComments(node); + } + function emitDefaultValueAssignments(node) { + if (compilerOptions.target < 2 /* ES6 */) { + var tempIndex = 0; + ts.forEach(node.parameters, function (p) { + if (ts.isBindingPattern(p.name)) { + writeLine(); + write("var "); + emitDestructuring(p, tempParameters[tempIndex]); + write(";"); + tempIndex++; + } + else if (p.initializer) { + writeLine(); + emitStart(p); + write("if ("); + emitNode(p.name); + write(" === void 0)"); + emitEnd(p); + write(" { "); + emitStart(p); + emitNode(p.name); + write(" = "); + emitNode(p.initializer); + emitEnd(p); + write("; }"); + } + }); + } + } + function emitRestParameter(node) { + if (compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node)) { + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; + var tempName = createTempVariable(node, true).text; + writeLine(); + emitLeadingComments(restParam); + emitStart(restParam); + write("var "); + emitNode(restParam.name); + write(" = [];"); + emitEnd(restParam); + emitTrailingComments(restParam); + writeLine(); + write("for ("); + emitStart(restParam); + write("var " + tempName + " = " + restIndex + ";"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + " < arguments.length;"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + "++"); + emitEnd(restParam); + write(") {"); + increaseIndent(); + writeLine(); + emitStart(restParam); + emitNode(restParam.name); + write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); + emitEnd(restParam); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function emitAccessor(node) { + emitLeadingComments(node); + write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node); + emitTrailingComments(node); + } + function emitFunctionDeclaration(node) { + if (ts.nodeIsMissing(node.body)) { + return emitPinnedOrTripleSlashComments(node); + } + if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + emitLeadingComments(node); + } + write("function "); + if (node.kind === 190 /* FunctionDeclaration */ || (node.kind === 156 /* FunctionExpression */ && node.name)) { + emit(node.name); + } + emitSignatureAndBody(node); + if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + emitTrailingComments(node); + } + } + function emitCaptureThisForNodeIfNecessary(node) { + if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { + writeLine(); + emitStart(node); + write("var _this = this;"); + emitEnd(node); + } + } + function emitSignatureParameters(node) { + increaseIndent(); + write("("); + if (node) { + var parameters = node.parameters; + var omitCount = compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + emitList(parameters, 0, parameters.length - omitCount, false, false); + } + write(")"); + decreaseIndent(); + } + function emitSignatureAndBody(node) { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempCount = 0; + tempVariables = undefined; + tempParameters = undefined; + emitSignatureParameters(node); + write(" {"); + scopeEmitStart(node); + increaseIndent(); + emitDetachedComments(node.body.kind === 170 /* Block */ ? node.body.statements : node.body); + var startIndex = 0; + if (node.body.kind === 170 /* Block */) { + startIndex = emitDirectivePrologues(node.body.statements, true); + } + var outPos = writer.getTextPos(); + emitCaptureThisForNodeIfNecessary(node); + emitDefaultValueAssignments(node); + emitRestParameter(node); + if (node.body.kind !== 170 /* Block */ && outPos === writer.getTextPos()) { + decreaseIndent(); + write(" "); + emitStart(node.body); + write("return "); + emitNode(node.body); + emitEnd(node.body); + write(";"); + emitTempDeclarations(false); + write(" "); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + else { + if (node.body.kind === 170 /* Block */) { + emitLinesStartingAt(node.body.statements, startIndex); + } + else { + writeLine(); + emitLeadingComments(node.body); + write("return "); + emit(node.body); + write(";"); + emitTrailingComments(node.body); + } + emitTempDeclarations(true); + writeLine(); + if (node.body.kind === 170 /* Block */) { + emitLeadingCommentsOfPosition(node.body.statements.end); + decreaseIndent(); + emitToken(15 /* CloseBraceToken */, node.body.statements.end); + } + else { + decreaseIndent(); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + } + scopeEmitEnd(); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + tempCount = saveTempCount; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + function findInitialSuperCall(ctor) { + if (ctor.body) { + var statement = ctor.body.statements[0]; + if (statement && statement.kind === 173 /* ExpressionStatement */) { + var expr = statement.expression; + if (expr && expr.kind === 151 /* CallExpression */) { + var func = expr.expression; + if (func && func.kind === 90 /* SuperKeyword */) { + return statement; + } + } + } + } + } + function emitParameterPropertyAssignments(node) { + ts.forEach(node.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + writeLine(); + emitStart(param); + emitStart(param.name); + write("this."); + emitNode(param.name); + emitEnd(param.name); + write(" = "); + emit(param.name); + write(";"); + emitEnd(param); + } + }); + } + function emitMemberAccessForPropertyName(memberName) { + if (memberName.kind === 8 /* StringLiteral */ || memberName.kind === 7 /* NumericLiteral */) { + write("["); + emitNode(memberName); + write("]"); + } + else if (memberName.kind === 122 /* ComputedPropertyName */) { + emitComputedPropertyName(memberName); + } + else { + write("."); + emitNode(memberName); + } + } + function emitMemberAssignments(node, staticFlag) { + ts.forEach(node.members, function (member) { + if (member.kind === 126 /* PropertyDeclaration */ && (member.flags & 128 /* Static */) === staticFlag && member.initializer) { + writeLine(); + emitLeadingComments(member); + emitStart(member); + emitStart(member.name); + if (staticFlag) { + emitNode(node.name); + } + else { + write("this"); + } + emitMemberAccessForPropertyName(member.name); + emitEnd(member.name); + write(" = "); + emit(member.initializer); + write(";"); + emitEnd(member); + emitTrailingComments(member); + } + }); + } + function emitMemberFunctions(node) { + ts.forEach(node.members, function (member) { + if (member.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */) { + if (!member.body) { + return emitPinnedOrTripleSlashComments(member); + } + writeLine(); + emitLeadingComments(member); + emitStart(member); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 128 /* Static */)) { + write(".prototype"); + } + emitMemberAccessForPropertyName(member.name); + emitEnd(member.name); + write(" = "); + emitStart(member); + emitFunctionDeclaration(member); + emitEnd(member); + emitEnd(member); + write(";"); + emitTrailingComments(member); + } + else if (member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) { + var accessors = getAllAccessorDeclarations(node, member); + if (member === accessors.firstAccessor) { + writeLine(); + emitStart(member); + write("Object.defineProperty("); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 128 /* Static */)) { + write(".prototype"); + } + write(", "); + emitExpressionForPropertyName(member.name); + emitEnd(member.name); + write(", {"); + increaseIndent(); + if (accessors.getAccessor) { + writeLine(); + emitLeadingComments(accessors.getAccessor); + write("get: "); + emitStart(accessors.getAccessor); + write("function "); + emitSignatureAndBody(accessors.getAccessor); + emitEnd(accessors.getAccessor); + emitTrailingComments(accessors.getAccessor); + write(","); + } + if (accessors.setAccessor) { + writeLine(); + emitLeadingComments(accessors.setAccessor); + write("set: "); + emitStart(accessors.setAccessor); + write("function "); + emitSignatureAndBody(accessors.setAccessor); + emitEnd(accessors.setAccessor); + emitTrailingComments(accessors.setAccessor); + write(","); + } + writeLine(); + write("enumerable: true,"); + writeLine(); + write("configurable: true"); + decreaseIndent(); + writeLine(); + write("});"); + emitEnd(member); + } + } + }); + } + function emitClassDeclaration(node) { + emitLeadingComments(node); + write("var "); + emit(node.name); + write(" = (function ("); + var baseTypeNode = ts.getClassBaseTypeNode(node); + if (baseTypeNode) { + write("_super"); + } + write(") {"); + increaseIndent(); + scopeEmitStart(node); + if (baseTypeNode) { + writeLine(); + emitStart(baseTypeNode); + write("__extends("); + emit(node.name); + write(", _super);"); + emitEnd(baseTypeNode); + } + writeLine(); + emitConstructorOfClass(); + emitMemberFunctions(node); + emitMemberAssignments(node, 128 /* Static */); + writeLine(); + function emitClassReturnStatement() { + write("return "); + emitNode(node.name); + } + emitToken(15 /* CloseBraceToken */, node.members.end, emitClassReturnStatement); + write(";"); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + emitStart(node); + write(")("); + if (baseTypeNode) { + emit(baseTypeNode.typeName); + } + write(");"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + emitTrailingComments(node); + function emitConstructorOfClass() { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempCount = 0; + tempVariables = undefined; + tempParameters = undefined; + ts.forEach(node.members, function (member) { + if (member.kind === 129 /* Constructor */ && !member.body) { + emitPinnedOrTripleSlashComments(member); + } + }); + var ctor = getFirstConstructorWithBody(node); + if (ctor) { + emitLeadingComments(ctor); + } + emitStart(ctor || node); + write("function "); + emit(node.name); + emitSignatureParameters(ctor); + write(" {"); + scopeEmitStart(node, "constructor"); + increaseIndent(); + if (ctor) { + emitDetachedComments(ctor.body.statements); + } + emitCaptureThisForNodeIfNecessary(node); + if (ctor) { + emitDefaultValueAssignments(ctor); + emitRestParameter(ctor); + if (baseTypeNode) { + var superCall = findInitialSuperCall(ctor); + if (superCall) { + writeLine(); + emit(superCall); + } + } + emitParameterPropertyAssignments(ctor); + } + else { + if (baseTypeNode) { + writeLine(); + emitStart(baseTypeNode); + write("_super.apply(this, arguments);"); + emitEnd(baseTypeNode); + } + } + emitMemberAssignments(node, 0); + if (ctor) { + var statements = ctor.body.statements; + if (superCall) + statements = statements.slice(1); + emitLines(statements); + } + emitTempDeclarations(true); + writeLine(); + if (ctor) { + emitLeadingCommentsOfPosition(ctor.body.statements.end); + } + decreaseIndent(); + emitToken(15 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); + scopeEmitEnd(); + emitEnd(ctor || node); + if (ctor) { + emitTrailingComments(ctor); + } + tempCount = saveTempCount; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + } + function emitInterfaceDeclaration(node) { + emitPinnedOrTripleSlashComments(node); + } + function emitEnumDeclaration(node) { + var isConstEnum = ts.isConst(node); + if (isConstEnum && !compilerOptions.preserveConstEnums) { + return; + } + emitLeadingComments(node); + if (!(node.flags & 1 /* Export */)) { + emitStart(node); + write("var "); + emit(node.name); + emitEnd(node); + write(";"); + } + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") {"); + increaseIndent(); + scopeEmitStart(node); + emitEnumMemberDeclarations(isConstEnum); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + write(")("); + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + write("var "); + emit(node.name); + write(" = "); + emitModuleMemberName(node); + emitEnd(node); + write(";"); + } + emitTrailingComments(node); + function emitEnumMemberDeclarations(isConstEnum) { + ts.forEach(node.members, function (member) { + writeLine(); + emitLeadingComments(member); + emitStart(member); + write(resolver.getLocalNameOfContainer(node)); + write("["); + write(resolver.getLocalNameOfContainer(node)); + write("["); + emitExpressionForPropertyName(member.name); + write("] = "); + if (member.initializer && !isConstEnum) { + emit(member.initializer); + } + else { + write(resolver.getEnumMemberValue(member).toString()); + } + write("] = "); + emitExpressionForPropertyName(member.name); + emitEnd(member); + write(";"); + emitTrailingComments(member); + }); + } + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function emitModuleDeclaration(node) { + var shouldEmit = ts.getModuleInstanceState(node) === 1 /* Instantiated */ || (ts.getModuleInstanceState(node) === 2 /* ConstEnumOnly */ && compilerOptions.preserveConstEnums); + if (!shouldEmit) { + return emitPinnedOrTripleSlashComments(node); + } + emitLeadingComments(node); + emitStart(node); + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") "); + if (node.body.kind === 196 /* ModuleBlock */) { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + tempCount = 0; + tempVariables = undefined; + emit(node.body); + tempCount = saveTempCount; + tempVariables = saveTempVariables; + } + else { + write("{"); + increaseIndent(); + scopeEmitStart(node); + emitCaptureThisForNodeIfNecessary(node); + writeLine(); + emit(node.body); + decreaseIndent(); + writeLine(); + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + emitToken(15 /* CloseBraceToken */, moduleBlock.statements.end); + scopeEmitEnd(); + } + write(")("); + if (node.flags & 1 /* Export */) { + emit(node.name); + write(" = "); + } + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + emitTrailingComments(node); + } + function emitImportDeclaration(node) { + var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); + if (!emitImportDeclaration) { + emitImportDeclaration = !ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportWithEntityName(node); + } + if (emitImportDeclaration) { + if (ts.isExternalModuleImportDeclaration(node) && node.parent.kind === 207 /* SourceFile */ && compilerOptions.module === 2 /* AMD */) { + if (node.flags & 1 /* Export */) { + writeLine(); + emitLeadingComments(node); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + write(";"); + emitEnd(node); + emitTrailingComments(node); + } + } + else { + writeLine(); + emitLeadingComments(node); + emitStart(node); + if (!(node.flags & 1 /* Export */)) + write("var "); + emitModuleMemberName(node); + write(" = "); + if (ts.isInternalModuleImportDeclaration(node)) { + emit(node.moduleReference); + } + else { + var literal = ts.getExternalModuleImportDeclarationExpression(node); + write("require("); + emitStart(literal); + emitLiteral(literal); + emitEnd(literal); + emitToken(17 /* CloseParenToken */, literal.end); + } + write(";"); + emitEnd(node); + emitTrailingComments(node); + } + } + } + function getExternalImportDeclarations(node) { + var result = []; + ts.forEach(node.statements, function (statement) { + if (ts.isExternalModuleImportDeclaration(statement) && resolver.isReferencedImportDeclaration(statement)) { + result.push(statement); + } + }); + return result; + } + function getFirstExportAssignment(sourceFile) { + return ts.forEach(sourceFile.statements, function (node) { + if (node.kind === 198 /* ExportAssignment */) { + return node; + } + }); + } + function emitAMDModule(node, startIndex) { + var imports = getExternalImportDeclarations(node); + writeLine(); + write("define("); + if (node.amdModuleName) { + write("\"" + node.amdModuleName + "\", "); + } + write("[\"require\", \"exports\""); + ts.forEach(imports, function (imp) { + write(", "); + emitLiteral(ts.getExternalModuleImportDeclarationExpression(imp)); + }); + ts.forEach(node.amdDependencies, function (amdDependency) { + var text = "\"" + amdDependency + "\""; + write(", "); + write(text); + }); + write("], function (require, exports"); + ts.forEach(imports, function (imp) { + write(", "); + emit(imp.name); + }); + write(") {"); + increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignment = getFirstExportAssignment(node); + emitStart(exportAssignment); + write("return "); + emitStart(exportAssignment.exportName); + write(exportName); + emitEnd(exportAssignment.exportName); + write(";"); + emitEnd(exportAssignment); + } + decreaseIndent(); + writeLine(); + write("});"); + } + function emitCommonJSModule(node, startIndex) { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignment = getFirstExportAssignment(node); + emitStart(exportAssignment); + write("module.exports = "); + emitStart(exportAssignment.exportName); + write(exportName); + emitEnd(exportAssignment.exportName); + write(";"); + emitEnd(exportAssignment); + } + } + function emitDirectivePrologues(statements, startWithNewLine) { + for (var i = 0; i < statements.length; ++i) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitSourceFile(node) { + currentSourceFile = node; + writeLine(); + emitDetachedComments(node); + var startIndex = emitDirectivePrologues(node.statements, false); + if (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */) { + writeLine(); + write("var __extends = this.__extends || function (d, b) {"); + increaseIndent(); + writeLine(); + write("for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + writeLine(); + write("function __() { this.constructor = d; }"); + writeLine(); + write("__.prototype = b.prototype;"); + writeLine(); + write("d.prototype = new __();"); + decreaseIndent(); + writeLine(); + write("};"); + extendsEmitted = true; + } + if (ts.isExternalModule(node)) { + if (compilerOptions.module === 2 /* AMD */) { + emitAMDModule(node, startIndex); + } + else { + emitCommonJSModule(node, startIndex); + } + } + else { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + } + emitLeadingComments(node.endOfFileToken); + } + function emitNode(node) { + if (!node) { + return; + } + if (node.flags & 2 /* Ambient */) { + return emitPinnedOrTripleSlashComments(node); + } + switch (node.kind) { + case 64 /* Identifier */: + return emitIdentifier(node); + case 124 /* Parameter */: + return emitParameter(node); + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + return emitMethod(node); + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + return emitAccessor(node); + case 92 /* ThisKeyword */: + return emitThis(node); + case 90 /* SuperKeyword */: + return emitSuper(node); + case 88 /* NullKeyword */: + return write("null"); + case 94 /* TrueKeyword */: + return write("true"); + case 79 /* FalseKeyword */: + return write("false"); + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 9 /* RegularExpressionLiteral */: + case 10 /* NoSubstitutionTemplateLiteral */: + case 11 /* TemplateHead */: + case 12 /* TemplateMiddle */: + case 13 /* TemplateTail */: + return emitLiteral(node); + case 165 /* TemplateExpression */: + return emitTemplateExpression(node); + case 169 /* TemplateSpan */: + return emitTemplateSpan(node); + case 121 /* QualifiedName */: + return emitQualifiedName(node); + case 144 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 145 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 146 /* BindingElement */: + return emitBindingElement(node); + case 147 /* ArrayLiteralExpression */: + return emitArrayLiteral(node); + case 148 /* ObjectLiteralExpression */: + return emitObjectLiteral(node); + case 204 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 205 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 122 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + case 149 /* PropertyAccessExpression */: + return emitPropertyAccess(node); + case 150 /* ElementAccessExpression */: + return emitIndexedAccess(node); + case 151 /* CallExpression */: + return emitCallExpression(node); + case 152 /* NewExpression */: + return emitNewExpression(node); + case 153 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 154 /* TypeAssertionExpression */: + return emit(node.expression); + case 155 /* ParenthesizedExpression */: + return emitParenExpression(node); + case 190 /* FunctionDeclaration */: + case 156 /* FunctionExpression */: + case 157 /* ArrowFunction */: + return emitFunctionDeclaration(node); + case 158 /* DeleteExpression */: + return emitDeleteExpression(node); + case 159 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 160 /* VoidExpression */: + return emitVoidExpression(node); + case 161 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 162 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 163 /* BinaryExpression */: + return emitBinaryExpression(node); + case 164 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 167 /* SpreadElementExpression */: + return emitSpreadElementExpression(node); + case 168 /* OmittedExpression */: + return; + case 170 /* Block */: + case 196 /* ModuleBlock */: + return emitBlock(node); + case 171 /* VariableStatement */: + return emitVariableStatement(node); + case 172 /* EmptyStatement */: + return write(";"); + case 173 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 174 /* IfStatement */: + return emitIfStatement(node); + case 175 /* DoStatement */: + return emitDoStatement(node); + case 176 /* WhileStatement */: + return emitWhileStatement(node); + case 177 /* ForStatement */: + return emitForStatement(node); + case 178 /* ForInStatement */: + return emitForInStatement(node); + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: + return emitBreakOrContinueStatement(node); + case 181 /* ReturnStatement */: + return emitReturnStatement(node); + case 182 /* WithStatement */: + return emitWithStatement(node); + case 183 /* SwitchStatement */: + return emitSwitchStatement(node); + case 200 /* CaseClause */: + case 201 /* DefaultClause */: + return emitCaseOrDefaultClause(node); + case 184 /* LabeledStatement */: + return emitLabelledStatement(node); + case 185 /* ThrowStatement */: + return emitThrowStatement(node); + case 186 /* TryStatement */: + return emitTryStatement(node); + case 203 /* CatchClause */: + return emitCatchClause(node); + case 187 /* DebuggerStatement */: + return emitDebuggerStatement(node); + case 188 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 191 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 192 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 194 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 195 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 197 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 207 /* SourceFile */: + return emitSourceFile(node); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + } + function getLeadingCommentsWithoutDetachedComments() { + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + return leadingComments; + } + function getLeadingCommentsToEmit(node) { + if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { + var leadingComments; + if (hasDetachedComments(node.pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + } + return leadingComments; + } + } + function emitLeadingDeclarationComments(node) { + var leadingComments = getLeadingCommentsToEmit(node); + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + } + function emitTrailingDeclarationComments(node) { + if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { + var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + } + } + function emitLeadingCommentsOfLocalPosition(pos) { + var leadingComments; + if (hasDetachedComments(pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + } + emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + } + function emitDetachedCommentsAtPosition(node) { + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + if (leadingComments) { + var detachedComments = []; + var lastComment; + ts.forEach(leadingComments, function (comment) { + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + detachedComments.push(comment); + lastComment = comment; + }); + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var astLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (astLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + } + } + function emitPinnedOrTripleSlashCommentsOfNode(node) { + var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); + function isPinnedOrTripleSlashComment(comment) { + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + return currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */ && currentSourceFile.text.substring(comment.pos, comment.end).match(ts.fullTripleSlashReferencePathRegEx)) { + return true; + } + } + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, pinnedComments); + emitComments(currentSourceFile, writer, pinnedComments, true, newLine, writeComment); + } + if (compilerOptions.sourceMap) { + initializeEmitterWithSourceMaps(); + } + if (root) { + emit(root); + } + else { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + emit(sourceFile); + } + }); + } + writeLine(); + writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); + } + function writeDeclarationFile(jsFilePath, sourceFile) { + var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); + if (!emitDeclarationResult.reportedDeclarationError) { + var declarationOutput = emitDeclarationResult.referencePathsOutput; + var appliedSyncOutputPos = 0; + ts.forEach(emitDeclarationResult.aliasDeclarationEmitInfo, function (aliasEmitInfo) { + if (aliasEmitInfo.asynchronousOutput) { + declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); + declarationOutput += aliasEmitInfo.asynchronousOutput; + appliedSyncOutputPos = aliasEmitInfo.outputPos; + } + }); + declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos); + writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); + } + } + var hasSemanticErrors = false; + var isEmitBlocked = false; + if (targetSourceFile === undefined) { + hasSemanticErrors = resolver.hasSemanticErrors(); + isEmitBlocked = host.isEmitBlocked(); + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js"); + emitFile(jsFilePath, sourceFile); + } + }); + if (compilerOptions.out) { + emitFile(compilerOptions.out); + } + } + else { + if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { + hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); + isEmitBlocked = host.isEmitBlocked(targetSourceFile); + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitFile(jsFilePath, targetSourceFile); + } + else if (!ts.isDeclarationFile(targetSourceFile) && compilerOptions.out) { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { + hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); + isEmitBlocked = isEmitBlocked || host.isEmitBlocked(sourceFile); + } + }); + emitFile(compilerOptions.out); + } + } + function emitFile(jsFilePath, sourceFile) { + if (!isEmitBlocked) { + emitJavaScript(jsFilePath, sourceFile); + if (!hasSemanticErrors && compilerOptions.declaration) { + writeDeclarationFile(jsFilePath, sourceFile); + } + } + } + diagnostics.sort(ts.compareDiagnostics); + diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); + var hasEmitterError = ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === 1 /* Error */; }); + var emitResultStatus; + if (isEmitBlocked) { + emitResultStatus = 1 /* AllOutputGenerationSkipped */; + } + else if (hasEmitterError) { + emitResultStatus = 4 /* EmitErrorsEncountered */; + } + else if (hasSemanticErrors && compilerOptions.declaration) { + emitResultStatus = 3 /* DeclarationGenerationSkipped */; + } + else if (hasSemanticErrors && !compilerOptions.declaration) { + emitResultStatus = 2 /* JSGeneratedWithSemanticErrors */; + } + else { + emitResultStatus = 0 /* Succeeded */; + } + return { + emitResultStatus: emitResultStatus, + diagnostics: diagnostics, + sourceMaps: sourceMapDataList + }; + } + ts.emitFiles = emitFiles; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createCompilerHost(options) { + var currentDirectory; + var existingDirectories = {}; + function getCanonicalFileName(fileName) { + return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + var unsupportedFileEncodingErrorCode = -2147024809; + function getSourceFile(filename, languageVersion, onError) { + try { + var text = ts.sys.readFile(filename, options.charset); + } + catch (e) { + if (onError) { + onError(e.number === unsupportedFileEncodingErrorCode ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText : e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(filename, text, languageVersion) : undefined; + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + function directoryExists(directoryPath) { + if (ts.hasProperty(existingDirectories, directoryPath)) { + return true; + } + if (ts.sys.directoryExists(directoryPath)) { + existingDirectories[directoryPath] = true; + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + ts.sys.createDirectory(directoryPath); + } + } + try { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + ts.sys.writeFile(fileName, data, writeByteOrderMark); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + return { + getSourceFile: getSourceFile, + getDefaultLibFilename: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"); }, + writeFile: writeFile, + getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return ts.sys.newLine; } + }; + } + ts.createCompilerHost = createCompilerHost; + function createProgram(rootNames, options, host) { + var program; + var files = []; + var filesByName = {}; + var errors = []; + var seenNoDefaultLib = options.noLib; + var commonSourceDirectory; + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + if (!seenNoDefaultLib) { + processRootFile(host.getDefaultLibFilename(options), true); + } + verifyCompilerOptions(); + errors.sort(ts.compareDiagnostics); + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var emitHost; + program = { + getSourceFile: getSourceFile, + getSourceFiles: function () { return files; }, + getCompilerOptions: function () { return options; }, + getCompilerHost: function () { return host; }, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getCommonSourceDirectory: function () { return commonSourceDirectory; }, + emitFiles: invokeEmitter, + isEmitBlocked: isEmitBlocked, + getCurrentDirectory: host.getCurrentDirectory + }; + return program; + function getEmitHost() { + return emitHost || (emitHost = ts.createEmitHostFromProgram(program)); + } + function hasEarlyErrors(sourceFile) { + return ts.forEach(getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile), function (d) { return d.isEarly; }); + } + function isEmitBlocked(sourceFile) { + return getDiagnostics(sourceFile).length !== 0 || hasEarlyErrors(sourceFile) || (options.noEmitOnError && getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0); + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); + } + function getTypeChecker(produceDiagnostics) { + if (produceDiagnostics) { + return getDiagnosticsProducingTypeChecker(); + } + else { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, produceDiagnostics)); + } + } + function getDeclarationDiagnostics(targetSourceFile) { + var typeChecker = getDiagnosticsProducingTypeChecker(); + typeChecker.getDiagnostics(targetSourceFile); + var resolver = typeChecker.getEmitResolver(); + return ts.getDeclarationDiagnostics(getEmitHost(), resolver, targetSourceFile); + } + function invokeEmitter(targetSourceFile) { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(); + return ts.emitFiles(resolver, getEmitHost(), targetSourceFile); + } + function getSourceFile(filename) { + filename = host.getCanonicalFileName(filename); + return ts.hasProperty(filesByName, filename) ? filesByName[filename] : undefined; + } + function getDiagnostics(sourceFile) { + return sourceFile ? ts.filter(errors, function (e) { return e.file === sourceFile; }) : errors; + } + function getGlobalDiagnostics() { + return ts.filter(errors, function (e) { return !e.file; }); + } + function hasExtension(filename) { + return ts.getBaseFilename(filename).indexOf(".") >= 0; + } + function processRootFile(filename, isDefaultLib) { + processSourceFile(ts.normalizePath(filename), isDefaultLib); + } + function processSourceFile(filename, isDefaultLib, refFile, refPos, refEnd) { + if (refEnd !== undefined && refPos !== undefined) { + var start = refPos; + var length = refEnd - refPos; + } + var diagnostic; + if (hasExtension(filename)) { + if (!options.allowNonTsExtensions && !ts.fileExtensionIs(filename, ".ts")) { + diagnostic = ts.Diagnostics.File_0_must_have_extension_ts_or_d_ts; + } + else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { + diagnostic = ts.Diagnostics.File_0_not_found; + } + else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { + diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; + } + } + else { + if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { + diagnostic = ts.Diagnostics.File_0_not_found; + filename += ".ts"; + } + } + if (diagnostic) { + if (refFile) { + errors.push(ts.createFileDiagnostic(refFile, start, length, diagnostic, filename)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostic, filename)); + } + } + } + function findSourceFile(filename, isDefaultLib, refFile, refStart, refLength) { + var canonicalName = host.getCanonicalFileName(filename); + if (ts.hasProperty(filesByName, canonicalName)) { + return getSourceFileFromCache(filename, canonicalName, false); + } + else { + var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); + var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); + if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); + } + var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, function (hostErrorMessage) { + if (refFile) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + }); + if (file) { + seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + filesByName[canonicalAbsolutePath] = file; + if (!options.noResolve) { + var basePath = ts.getDirectoryPath(filename); + processReferencedFiles(file, basePath); + processImportedModules(file, basePath); + } + if (isDefaultLib) { + files.unshift(file); + } + else { + files.push(file); + } + ts.forEach(file.getSyntacticDiagnostics(), function (e) { + errors.push(e); + }); + } + } + return file; + function getSourceFileFromCache(filename, canonicalName, useAbsolutePath) { + var file = filesByName[canonicalName]; + if (file && host.useCaseSensitiveFileNames()) { + var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; + if (canonicalName !== sourceFileName) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); + } + } + return file; + } + } + function processReferencedFiles(file, basePath) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFilename = ts.isRootedDiskPath(ref.filename) ? ref.filename : ts.combinePaths(basePath, ref.filename); + processSourceFile(ts.normalizePath(referencedFilename), false, file, ref.pos, ref.end); + }); + } + function processImportedModules(file, basePath) { + ts.forEach(file.statements, function (node) { + if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { + var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + var searchPath = basePath; + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); + if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { + break; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + } + } + else if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + ts.forEachChild(node.body, function (node) { + if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { + var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + var searchName = ts.normalizePath(ts.combinePaths(basePath, moduleName)); + var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); + if (!tsFile) { + findModuleSourceFile(searchName + ".d.ts", nameLiteral); + } + } + } + }); + } + }); + function findModuleSourceFile(filename, nameLiteral) { + return findSourceFile(filename, false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); + } + } + function verifyCompilerOptions() { + if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { + if (options.mapRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + if (options.sourceRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + return; + } + var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + if (firstExternalModule && options.module === 0 /* None */) { + var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); + var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); + var errorLength = externalModuleErrorSpan.end - errorStart; + errors.push(ts.createFileDiagnostic(firstExternalModule, errorStart, errorLength, ts.Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); + } + if (options.outDir || options.sourceRoot || (options.mapRoot && (!options.out || firstExternalModule !== undefined))) { + var commonPathComponents; + ts.forEach(files, function (sourceFile) { + if (!(sourceFile.flags & 1024 /* DeclarationFile */) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); + sourcePathComponents.pop(); + if (commonPathComponents) { + for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { + if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (i === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + return; + } + commonPathComponents.length = i; + break; + } + } + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + } + else { + commonPathComponents = sourcePathComponents; + } + } + }); + commonSourceDirectory = ts.getNormalizedPathFromPathComponents(commonPathComponents); + if (commonSourceDirectory) { + commonSourceDirectory += ts.directorySeparator; + } + } + if (options.noEmit) { + if (options.out || options.outDir) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_out_or_outDir)); + } + if (options.declaration) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); + } + } + } + } + ts.createProgram = createProgram; +})(ts || (ts = {})); +var ts; (function (ts) { ts.optionDeclarations = [ { @@ -18380,6 +19255,11 @@ var ts; paramType: ts.Diagnostics.KIND, error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_or_amd }, + { + name: "noEmit", + type: "boolean", + description: ts.Diagnostics.Do_not_emit_outputs + }, { name: "noEmitOnError", type: "boolean", @@ -18774,12 +19654,15 @@ var ts; var checker = program.getTypeChecker(true); var checkStart = new Date().getTime(); errors = checker.getDiagnostics(); - if (checker.isEmitBlocked()) { + if (program.isEmitBlocked()) { exitStatus = 1 /* AllOutputGenerationSkipped */; } + else if (compilerOptions.noEmit) { + exitStatus = 0 /* Succeeded */; + } else { var emitStart = new Date().getTime(); - var emitOutput = checker.emitFiles(); + var emitOutput = program.emitFiles(); var emitErrors = emitOutput.diagnostics; exitStatus = emitOutput.emitResultStatus; var reportStart = new Date().getTime(); diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 0cb7ac8775..bd7764c3f4 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -189,29 +189,29 @@ declare module "typescript" { ConditionalExpression = 164, TemplateExpression = 165, YieldExpression = 166, - OmittedExpression = 167, - TemplateSpan = 168, - Block = 169, - VariableStatement = 170, - EmptyStatement = 171, - ExpressionStatement = 172, - IfStatement = 173, - DoStatement = 174, - WhileStatement = 175, - ForStatement = 176, - ForInStatement = 177, - ContinueStatement = 178, - BreakStatement = 179, - ReturnStatement = 180, - WithStatement = 181, - SwitchStatement = 182, - LabeledStatement = 183, - ThrowStatement = 184, - TryStatement = 185, - TryBlock = 186, - FinallyBlock = 187, - DebuggerStatement = 188, - VariableDeclaration = 189, + SpreadElementExpression = 167, + OmittedExpression = 168, + TemplateSpan = 169, + Block = 170, + VariableStatement = 171, + EmptyStatement = 172, + ExpressionStatement = 173, + IfStatement = 174, + DoStatement = 175, + WhileStatement = 176, + ForStatement = 177, + ForInStatement = 178, + ContinueStatement = 179, + BreakStatement = 180, + ReturnStatement = 181, + WithStatement = 182, + SwitchStatement = 183, + LabeledStatement = 184, + ThrowStatement = 185, + TryStatement = 186, + DebuggerStatement = 187, + VariableDeclaration = 188, + VariableDeclarationList = 189, FunctionDeclaration = 190, ClassDeclaration = 191, InterfaceDeclaration = 192, @@ -230,9 +230,8 @@ declare module "typescript" { ShorthandPropertyAssignment = 205, EnumMember = 206, SourceFile = 207, - Program = 208, - SyntaxList = 209, - Count = 210, + SyntaxList = 208, + Count = 209, FirstAssignment = 52, LastAssignment = 63, FirstReservedWord = 65, @@ -253,8 +252,6 @@ declare module "typescript" { LastLiteralToken = 10, FirstTemplateToken = 10, LastTemplateToken = 13, - FirstOperator = 22, - LastOperator = 63, FirstBinaryOperator = 24, LastBinaryOperator = 63, FirstNode = 121, @@ -331,10 +328,14 @@ declare module "typescript" { type?: TypeNode; } interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; name: Identifier | BindingPattern; type?: TypeNode; initializer?: Expression; } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; name: Identifier | BindingPattern; @@ -514,6 +515,9 @@ declare module "typescript" { interface ArrayLiteralExpression extends PrimaryExpression { elements: NodeArray; } + interface SpreadElementExpression extends Expression { + expression: Expression; + } interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } @@ -548,7 +552,7 @@ declare module "typescript" { statements: NodeArray; } interface VariableStatement extends Statement { - declarations: NodeArray; + declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { expression: Expression; @@ -568,14 +572,12 @@ declare module "typescript" { expression: Expression; } interface ForStatement extends IterationStatement { - declarations?: NodeArray; - initializer?: Expression; + initializer?: VariableDeclarationList | Expression; condition?: Expression; iterator?: Expression; } interface ForInStatement extends IterationStatement { - declarations?: NodeArray; - variable?: Expression; + initializer: VariableDeclarationList | Expression; expression: Expression; } interface BreakOrContinueStatement extends Statement { @@ -682,12 +684,12 @@ declare module "typescript" { getLineAndCharacterFromPosition(position: number): LineAndCharacter; getPositionFromLineAndCharacter(line: number, character: number): number; getLineStarts(): number[]; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; amdDependencies: string[]; amdModuleName: string; referencedFiles: FileReference[]; referenceDiagnostics: Diagnostic[]; parseDiagnostics: Diagnostic[]; - grammarDiagnostics: Diagnostic[]; getSyntacticDiagnostics(): Diagnostic[]; semanticDiagnostics: Diagnostic[]; hasNoDefaultLib: boolean; @@ -698,15 +700,21 @@ declare module "typescript" { languageVersion: ScriptTarget; identifiers: Map; } - interface Program { - getSourceFile(filename: string): SourceFile; - getSourceFiles(): SourceFile[]; + interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; + getSourceFile(filename: string): SourceFile; + getCurrentDirectory(): string; + } + interface Program extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; getCompilerHost(): CompilerHost; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; - getTypeChecker(fullTypeCheckMode: boolean): TypeChecker; + getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; + getTypeChecker(produceDiagnostics: boolean): TypeChecker; getCommonSourceDirectory(): string; + emitFiles(targetSourceFile?: SourceFile): EmitResult; + isEmitBlocked(sourceFile?: SourceFile): boolean; } interface SourceMapSpan { emittedLine: number; @@ -740,16 +748,20 @@ declare module "typescript" { diagnostics: Diagnostic[]; sourceMaps: SourceMapData[]; } + interface TypeCheckerHost { + getCompilerOptions(): CompilerOptions; + getCompilerHost(): CompilerHost; + getSourceFiles(): SourceFile[]; + getSourceFile(filename: string): SourceFile; + } interface TypeChecker { - getProgram(): Program; + getEmitResolver(): EmitResolver; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; - getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; - emitFiles(targetSourceFile?: SourceFile): EmitResult; getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; @@ -773,7 +785,6 @@ declare module "typescript" { isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; - isEmitBlocked(sourceFile?: SourceFile): boolean; getEnumMemberValue(node: EnumMember): number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; @@ -833,7 +844,6 @@ declare module "typescript" { errorModuleName?: string; } interface EmitResolver { - getProgram(): Program; getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string; getExpressionNamePrefix(node: Identifier): string; getExportAssignmentName(node: SourceFile): string; @@ -849,7 +859,6 @@ declare module "typescript" { isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult; isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - isEmitBlocked(sourceFile?: SourceFile): boolean; isUnknownIdentifier(location: Node, name: string): boolean; } const enum SymbolFlags { @@ -1119,6 +1128,7 @@ declare module "typescript" { locale?: string; mapRoot?: string; module?: ModuleKind; + noEmit?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; noImplicitAny?: boolean; @@ -1303,13 +1313,18 @@ declare module "typescript" { useCaseSensitiveFileNames(): boolean; getNewLine(): string; } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } } declare module "typescript" { interface ErrorCallback { - (message: DiagnosticMessage): void; - } - interface CommentCallback { - (pos: number, end: number): void; + (message: DiagnosticMessage, length: number): void; } interface Scanner { getStartPos(): number; @@ -1356,16 +1371,18 @@ declare module "typescript" { function getNodeConstructor(kind: SyntaxKind): new () => Node; function createNode(kind: SyntaxKind): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T; - function createCompilerHost(options: CompilerOptions): CompilerHost; function modifierToFlag(token: SyntaxKind): NodeFlags; function isEvalOrArgumentsIdentifier(node: Node): boolean; function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; function isLeftHandSideExpression(expr: Expression): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; - function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program; } declare module "typescript" { - function createTypeChecker(program: Program, fullTypeCheck: boolean): TypeChecker; + function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; +} +declare module "typescript" { + function createCompilerHost(options: CompilerOptions): CompilerHost; + function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program; } declare module "typescript" { var servicesVersion: string; @@ -1412,9 +1429,8 @@ declare module "typescript" { interface SourceFile { isOpen: boolean; version: string; - getScriptSnapshot(): IScriptSnapshot; + scriptSnapshot: IScriptSnapshot; getNamedDeclarations(): Declaration[]; - update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile; } /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the @@ -1496,96 +1512,6 @@ declare module "typescript" { getSourceFile(filename: string): SourceFile; dispose(): void; } - class TextSpan { - private _start; - private _length; - /** - * Creates a TextSpan instance beginning with the position Start and having the Length - * specified with length. - */ - constructor(start: number, length: number); - toJSON(key: any): any; - start(): number; - length(): number; - end(): number; - isEmpty(): boolean; - /** - * Determines whether the position lies within the span. Returns true if the position is greater than or equal to Start and strictly less - * than End, otherwise false. - * @param position The position to check. - */ - containsPosition(position: number): boolean; - /** - * Determines whether span falls completely within this span. Returns true if the specified span falls completely within this span, otherwise false. - * @param span The span to check. - */ - containsTextSpan(span: TextSpan): boolean; - /** - * Determines whether the given span overlaps this span. Two spans are considered to overlap - * if they have positions in common and neither is empty. Empty spans do not overlap with any - * other span. Returns true if the spans overlap, false otherwise. - * @param span The span to check. - */ - overlapsWith(span: TextSpan): boolean; - /** - * Returns the overlap with the given span, or undefined if there is no overlap. - * @param span The span to check. - */ - overlap(span: TextSpan): TextSpan; - /** - * Determines whether span intersects this span. Two spans are considered to - * intersect if they have positions in common or the end of one span - * coincides with the start of the other span. Returns true if the spans intersect, false otherwise. - * @param The span to check. - */ - intersectsWithTextSpan(span: TextSpan): boolean; - intersectsWith(start: number, length: number): boolean; - /** - * Determines whether the given position intersects this span. - * A position is considered to intersect if it is between the start and - * end positions (inclusive) of this span. Returns true if the position intersects, false otherwise. - * @param position The position to check. - */ - intersectsWithPosition(position: number): boolean; - /** - * Returns the intersection with the given span, or undefined if there is no intersection. - * @param span The span to check. - */ - intersection(span: TextSpan): TextSpan; - /** - * Creates a new TextSpan from the given start and end positions - * as opposed to a position and length. - */ - static fromBounds(start: number, end: number): TextSpan; - } - class TextChangeRange { - static unchanged: TextChangeRange; - private _span; - private _newLength; - /** - * Initializes a new instance of TextChangeRange. - */ - constructor(span: TextSpan, newLength: number); - /** - * The span of text before the edit which is being changed - */ - span(): TextSpan; - /** - * Width of the span after the edit. A 0 here would represent a delete - */ - newLength(): number; - newSpan(): TextSpan; - isUnchanged(): boolean; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - } interface ClassifiedSpan { textSpan: TextSpan; classificationType: string; @@ -1877,6 +1803,8 @@ declare module "typescript" { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(filename: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, isOpen: boolean, setNodeParents: boolean): SourceFile; + var disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry): LanguageService; diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index 24ea4aebd3..c980d9c2d6 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -189,29 +189,29 @@ declare module ts { ConditionalExpression = 164, TemplateExpression = 165, YieldExpression = 166, - OmittedExpression = 167, - TemplateSpan = 168, - Block = 169, - VariableStatement = 170, - EmptyStatement = 171, - ExpressionStatement = 172, - IfStatement = 173, - DoStatement = 174, - WhileStatement = 175, - ForStatement = 176, - ForInStatement = 177, - ContinueStatement = 178, - BreakStatement = 179, - ReturnStatement = 180, - WithStatement = 181, - SwitchStatement = 182, - LabeledStatement = 183, - ThrowStatement = 184, - TryStatement = 185, - TryBlock = 186, - FinallyBlock = 187, - DebuggerStatement = 188, - VariableDeclaration = 189, + SpreadElementExpression = 167, + OmittedExpression = 168, + TemplateSpan = 169, + Block = 170, + VariableStatement = 171, + EmptyStatement = 172, + ExpressionStatement = 173, + IfStatement = 174, + DoStatement = 175, + WhileStatement = 176, + ForStatement = 177, + ForInStatement = 178, + ContinueStatement = 179, + BreakStatement = 180, + ReturnStatement = 181, + WithStatement = 182, + SwitchStatement = 183, + LabeledStatement = 184, + ThrowStatement = 185, + TryStatement = 186, + DebuggerStatement = 187, + VariableDeclaration = 188, + VariableDeclarationList = 189, FunctionDeclaration = 190, ClassDeclaration = 191, InterfaceDeclaration = 192, @@ -230,9 +230,8 @@ declare module ts { ShorthandPropertyAssignment = 205, EnumMember = 206, SourceFile = 207, - Program = 208, - SyntaxList = 209, - Count = 210, + SyntaxList = 208, + Count = 209, FirstAssignment = 52, LastAssignment = 63, FirstReservedWord = 65, @@ -253,8 +252,6 @@ declare module ts { LastLiteralToken = 10, FirstTemplateToken = 10, LastTemplateToken = 13, - FirstOperator = 22, - LastOperator = 63, FirstBinaryOperator = 24, LastBinaryOperator = 63, FirstNode = 121, @@ -331,10 +328,14 @@ declare module ts { type?: TypeNode; } interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; name: Identifier | BindingPattern; type?: TypeNode; initializer?: Expression; } + interface VariableDeclarationList extends Node { + declarations: NodeArray; + } interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; name: Identifier | BindingPattern; @@ -514,6 +515,9 @@ declare module ts { interface ArrayLiteralExpression extends PrimaryExpression { elements: NodeArray; } + interface SpreadElementExpression extends Expression { + expression: Expression; + } interface ObjectLiteralExpression extends PrimaryExpression, Declaration { properties: NodeArray; } @@ -548,7 +552,7 @@ declare module ts { statements: NodeArray; } interface VariableStatement extends Statement { - declarations: NodeArray; + declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { expression: Expression; @@ -568,14 +572,12 @@ declare module ts { expression: Expression; } interface ForStatement extends IterationStatement { - declarations?: NodeArray; - initializer?: Expression; + initializer?: VariableDeclarationList | Expression; condition?: Expression; iterator?: Expression; } interface ForInStatement extends IterationStatement { - declarations?: NodeArray; - variable?: Expression; + initializer: VariableDeclarationList | Expression; expression: Expression; } interface BreakOrContinueStatement extends Statement { @@ -682,12 +684,12 @@ declare module ts { getLineAndCharacterFromPosition(position: number): LineAndCharacter; getPositionFromLineAndCharacter(line: number, character: number): number; getLineStarts(): number[]; + update(newText: string, textChangeRange: TextChangeRange): SourceFile; amdDependencies: string[]; amdModuleName: string; referencedFiles: FileReference[]; referenceDiagnostics: Diagnostic[]; parseDiagnostics: Diagnostic[]; - grammarDiagnostics: Diagnostic[]; getSyntacticDiagnostics(): Diagnostic[]; semanticDiagnostics: Diagnostic[]; hasNoDefaultLib: boolean; @@ -698,15 +700,21 @@ declare module ts { languageVersion: ScriptTarget; identifiers: Map; } - interface Program { - getSourceFile(filename: string): SourceFile; - getSourceFiles(): SourceFile[]; + interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; + getSourceFile(filename: string): SourceFile; + getCurrentDirectory(): string; + } + interface Program extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; getCompilerHost(): CompilerHost; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; - getTypeChecker(fullTypeCheckMode: boolean): TypeChecker; + getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; + getTypeChecker(produceDiagnostics: boolean): TypeChecker; getCommonSourceDirectory(): string; + emitFiles(targetSourceFile?: SourceFile): EmitResult; + isEmitBlocked(sourceFile?: SourceFile): boolean; } interface SourceMapSpan { emittedLine: number; @@ -740,16 +748,20 @@ declare module ts { diagnostics: Diagnostic[]; sourceMaps: SourceMapData[]; } + interface TypeCheckerHost { + getCompilerOptions(): CompilerOptions; + getCompilerHost(): CompilerHost; + getSourceFiles(): SourceFile[]; + getSourceFile(filename: string): SourceFile; + } interface TypeChecker { - getProgram(): Program; + getEmitResolver(): EmitResolver; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; - getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; - emitFiles(targetSourceFile?: SourceFile): EmitResult; getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; @@ -773,7 +785,6 @@ declare module ts { isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; - isEmitBlocked(sourceFile?: SourceFile): boolean; getEnumMemberValue(node: EnumMember): number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; getAliasedSymbol(symbol: Symbol): Symbol; @@ -833,7 +844,6 @@ declare module ts { errorModuleName?: string; } interface EmitResolver { - getProgram(): Program; getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string; getExpressionNamePrefix(node: Identifier): string; getExportAssignmentName(node: SourceFile): string; @@ -849,7 +859,6 @@ declare module ts { isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult; isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - isEmitBlocked(sourceFile?: SourceFile): boolean; isUnknownIdentifier(location: Node, name: string): boolean; } const enum SymbolFlags { @@ -1119,6 +1128,7 @@ declare module ts { locale?: string; mapRoot?: string; module?: ModuleKind; + noEmit?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; noImplicitAny?: boolean; @@ -1303,13 +1313,18 @@ declare module ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; } + interface TextSpan { + start: number; + length: number; + } + interface TextChangeRange { + span: TextSpan; + newLength: number; + } } declare module ts { interface ErrorCallback { - (message: DiagnosticMessage): void; - } - interface CommentCallback { - (pos: number, end: number): void; + (message: DiagnosticMessage, length: number): void; } interface Scanner { getStartPos(): number; @@ -1356,16 +1371,18 @@ declare module ts { function getNodeConstructor(kind: SyntaxKind): new () => Node; function createNode(kind: SyntaxKind): Node; function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T; - function createCompilerHost(options: CompilerOptions): CompilerHost; function modifierToFlag(token: SyntaxKind): NodeFlags; function isEvalOrArgumentsIdentifier(node: Node): boolean; function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile; function isLeftHandSideExpression(expr: Expression): boolean; function isAssignmentOperator(token: SyntaxKind): boolean; - function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program; } declare module ts { - function createTypeChecker(program: Program, fullTypeCheck: boolean): TypeChecker; + function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker; +} +declare module ts { + function createCompilerHost(options: CompilerOptions): CompilerHost; + function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program; } declare module ts { var servicesVersion: string; @@ -1412,9 +1429,8 @@ declare module ts { interface SourceFile { isOpen: boolean; version: string; - getScriptSnapshot(): IScriptSnapshot; + scriptSnapshot: IScriptSnapshot; getNamedDeclarations(): Declaration[]; - update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile; } /** * Represents an immutable snapshot of a script at a specified time.Once acquired, the @@ -1496,96 +1512,6 @@ declare module ts { getSourceFile(filename: string): SourceFile; dispose(): void; } - class TextSpan { - private _start; - private _length; - /** - * Creates a TextSpan instance beginning with the position Start and having the Length - * specified with length. - */ - constructor(start: number, length: number); - toJSON(key: any): any; - start(): number; - length(): number; - end(): number; - isEmpty(): boolean; - /** - * Determines whether the position lies within the span. Returns true if the position is greater than or equal to Start and strictly less - * than End, otherwise false. - * @param position The position to check. - */ - containsPosition(position: number): boolean; - /** - * Determines whether span falls completely within this span. Returns true if the specified span falls completely within this span, otherwise false. - * @param span The span to check. - */ - containsTextSpan(span: TextSpan): boolean; - /** - * Determines whether the given span overlaps this span. Two spans are considered to overlap - * if they have positions in common and neither is empty. Empty spans do not overlap with any - * other span. Returns true if the spans overlap, false otherwise. - * @param span The span to check. - */ - overlapsWith(span: TextSpan): boolean; - /** - * Returns the overlap with the given span, or undefined if there is no overlap. - * @param span The span to check. - */ - overlap(span: TextSpan): TextSpan; - /** - * Determines whether span intersects this span. Two spans are considered to - * intersect if they have positions in common or the end of one span - * coincides with the start of the other span. Returns true if the spans intersect, false otherwise. - * @param The span to check. - */ - intersectsWithTextSpan(span: TextSpan): boolean; - intersectsWith(start: number, length: number): boolean; - /** - * Determines whether the given position intersects this span. - * A position is considered to intersect if it is between the start and - * end positions (inclusive) of this span. Returns true if the position intersects, false otherwise. - * @param position The position to check. - */ - intersectsWithPosition(position: number): boolean; - /** - * Returns the intersection with the given span, or undefined if there is no intersection. - * @param span The span to check. - */ - intersection(span: TextSpan): TextSpan; - /** - * Creates a new TextSpan from the given start and end positions - * as opposed to a position and length. - */ - static fromBounds(start: number, end: number): TextSpan; - } - class TextChangeRange { - static unchanged: TextChangeRange; - private _span; - private _newLength; - /** - * Initializes a new instance of TextChangeRange. - */ - constructor(span: TextSpan, newLength: number); - /** - * The span of text before the edit which is being changed - */ - span(): TextSpan; - /** - * Width of the span after the edit. A 0 here would represent a delete - */ - newLength(): number; - newSpan(): TextSpan; - isUnchanged(): boolean; - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; - } interface ClassifiedSpan { textSpan: TextSpan; classificationType: string; @@ -1877,6 +1803,8 @@ declare module ts { throwIfCancellationRequested(): void; } function createLanguageServiceSourceFile(filename: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, isOpen: boolean, setNodeParents: boolean): SourceFile; + var disableIncrementalParsing: boolean; + function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile; function createDocumentRegistry(): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry): LanguageService; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 11bce67850..9506ab39dc 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -15,6 +15,271 @@ and limitations under the License. var ts; (function (ts) { + (function (SyntaxKind) { + SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown"; + SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken"; + SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia"; + SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia"; + SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia"; + SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia"; + SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 6] = "ConflictMarkerTrivia"; + SyntaxKind[SyntaxKind["NumericLiteral"] = 7] = "NumericLiteral"; + SyntaxKind[SyntaxKind["StringLiteral"] = 8] = "StringLiteral"; + SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 9] = "RegularExpressionLiteral"; + SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 10] = "NoSubstitutionTemplateLiteral"; + SyntaxKind[SyntaxKind["TemplateHead"] = 11] = "TemplateHead"; + SyntaxKind[SyntaxKind["TemplateMiddle"] = 12] = "TemplateMiddle"; + SyntaxKind[SyntaxKind["TemplateTail"] = 13] = "TemplateTail"; + SyntaxKind[SyntaxKind["OpenBraceToken"] = 14] = "OpenBraceToken"; + SyntaxKind[SyntaxKind["CloseBraceToken"] = 15] = "CloseBraceToken"; + SyntaxKind[SyntaxKind["OpenParenToken"] = 16] = "OpenParenToken"; + SyntaxKind[SyntaxKind["CloseParenToken"] = 17] = "CloseParenToken"; + SyntaxKind[SyntaxKind["OpenBracketToken"] = 18] = "OpenBracketToken"; + SyntaxKind[SyntaxKind["CloseBracketToken"] = 19] = "CloseBracketToken"; + SyntaxKind[SyntaxKind["DotToken"] = 20] = "DotToken"; + SyntaxKind[SyntaxKind["DotDotDotToken"] = 21] = "DotDotDotToken"; + SyntaxKind[SyntaxKind["SemicolonToken"] = 22] = "SemicolonToken"; + SyntaxKind[SyntaxKind["CommaToken"] = 23] = "CommaToken"; + SyntaxKind[SyntaxKind["LessThanToken"] = 24] = "LessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanToken"] = 25] = "GreaterThanToken"; + SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 26] = "LessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 27] = "GreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 28] = "EqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 29] = "ExclamationEqualsToken"; + SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 30] = "EqualsEqualsEqualsToken"; + SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 31] = "ExclamationEqualsEqualsToken"; + SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 32] = "EqualsGreaterThanToken"; + SyntaxKind[SyntaxKind["PlusToken"] = 33] = "PlusToken"; + SyntaxKind[SyntaxKind["MinusToken"] = 34] = "MinusToken"; + SyntaxKind[SyntaxKind["AsteriskToken"] = 35] = "AsteriskToken"; + SyntaxKind[SyntaxKind["SlashToken"] = 36] = "SlashToken"; + SyntaxKind[SyntaxKind["PercentToken"] = 37] = "PercentToken"; + SyntaxKind[SyntaxKind["PlusPlusToken"] = 38] = "PlusPlusToken"; + SyntaxKind[SyntaxKind["MinusMinusToken"] = 39] = "MinusMinusToken"; + SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 40] = "LessThanLessThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 41] = "GreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 42] = "GreaterThanGreaterThanGreaterThanToken"; + SyntaxKind[SyntaxKind["AmpersandToken"] = 43] = "AmpersandToken"; + SyntaxKind[SyntaxKind["BarToken"] = 44] = "BarToken"; + SyntaxKind[SyntaxKind["CaretToken"] = 45] = "CaretToken"; + SyntaxKind[SyntaxKind["ExclamationToken"] = 46] = "ExclamationToken"; + SyntaxKind[SyntaxKind["TildeToken"] = 47] = "TildeToken"; + SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 48] = "AmpersandAmpersandToken"; + SyntaxKind[SyntaxKind["BarBarToken"] = 49] = "BarBarToken"; + SyntaxKind[SyntaxKind["QuestionToken"] = 50] = "QuestionToken"; + SyntaxKind[SyntaxKind["ColonToken"] = 51] = "ColonToken"; + SyntaxKind[SyntaxKind["EqualsToken"] = 52] = "EqualsToken"; + SyntaxKind[SyntaxKind["PlusEqualsToken"] = 53] = "PlusEqualsToken"; + SyntaxKind[SyntaxKind["MinusEqualsToken"] = 54] = "MinusEqualsToken"; + SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 55] = "AsteriskEqualsToken"; + SyntaxKind[SyntaxKind["SlashEqualsToken"] = 56] = "SlashEqualsToken"; + SyntaxKind[SyntaxKind["PercentEqualsToken"] = 57] = "PercentEqualsToken"; + SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 58] = "LessThanLessThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 59] = "GreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 60] = "GreaterThanGreaterThanGreaterThanEqualsToken"; + SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 61] = "AmpersandEqualsToken"; + SyntaxKind[SyntaxKind["BarEqualsToken"] = 62] = "BarEqualsToken"; + SyntaxKind[SyntaxKind["CaretEqualsToken"] = 63] = "CaretEqualsToken"; + SyntaxKind[SyntaxKind["Identifier"] = 64] = "Identifier"; + SyntaxKind[SyntaxKind["BreakKeyword"] = 65] = "BreakKeyword"; + SyntaxKind[SyntaxKind["CaseKeyword"] = 66] = "CaseKeyword"; + SyntaxKind[SyntaxKind["CatchKeyword"] = 67] = "CatchKeyword"; + SyntaxKind[SyntaxKind["ClassKeyword"] = 68] = "ClassKeyword"; + SyntaxKind[SyntaxKind["ConstKeyword"] = 69] = "ConstKeyword"; + SyntaxKind[SyntaxKind["ContinueKeyword"] = 70] = "ContinueKeyword"; + SyntaxKind[SyntaxKind["DebuggerKeyword"] = 71] = "DebuggerKeyword"; + SyntaxKind[SyntaxKind["DefaultKeyword"] = 72] = "DefaultKeyword"; + SyntaxKind[SyntaxKind["DeleteKeyword"] = 73] = "DeleteKeyword"; + SyntaxKind[SyntaxKind["DoKeyword"] = 74] = "DoKeyword"; + SyntaxKind[SyntaxKind["ElseKeyword"] = 75] = "ElseKeyword"; + SyntaxKind[SyntaxKind["EnumKeyword"] = 76] = "EnumKeyword"; + SyntaxKind[SyntaxKind["ExportKeyword"] = 77] = "ExportKeyword"; + SyntaxKind[SyntaxKind["ExtendsKeyword"] = 78] = "ExtendsKeyword"; + SyntaxKind[SyntaxKind["FalseKeyword"] = 79] = "FalseKeyword"; + SyntaxKind[SyntaxKind["FinallyKeyword"] = 80] = "FinallyKeyword"; + SyntaxKind[SyntaxKind["ForKeyword"] = 81] = "ForKeyword"; + SyntaxKind[SyntaxKind["FunctionKeyword"] = 82] = "FunctionKeyword"; + SyntaxKind[SyntaxKind["IfKeyword"] = 83] = "IfKeyword"; + SyntaxKind[SyntaxKind["ImportKeyword"] = 84] = "ImportKeyword"; + SyntaxKind[SyntaxKind["InKeyword"] = 85] = "InKeyword"; + SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 86] = "InstanceOfKeyword"; + SyntaxKind[SyntaxKind["NewKeyword"] = 87] = "NewKeyword"; + SyntaxKind[SyntaxKind["NullKeyword"] = 88] = "NullKeyword"; + SyntaxKind[SyntaxKind["ReturnKeyword"] = 89] = "ReturnKeyword"; + SyntaxKind[SyntaxKind["SuperKeyword"] = 90] = "SuperKeyword"; + SyntaxKind[SyntaxKind["SwitchKeyword"] = 91] = "SwitchKeyword"; + SyntaxKind[SyntaxKind["ThisKeyword"] = 92] = "ThisKeyword"; + SyntaxKind[SyntaxKind["ThrowKeyword"] = 93] = "ThrowKeyword"; + SyntaxKind[SyntaxKind["TrueKeyword"] = 94] = "TrueKeyword"; + SyntaxKind[SyntaxKind["TryKeyword"] = 95] = "TryKeyword"; + SyntaxKind[SyntaxKind["TypeOfKeyword"] = 96] = "TypeOfKeyword"; + SyntaxKind[SyntaxKind["VarKeyword"] = 97] = "VarKeyword"; + SyntaxKind[SyntaxKind["VoidKeyword"] = 98] = "VoidKeyword"; + SyntaxKind[SyntaxKind["WhileKeyword"] = 99] = "WhileKeyword"; + SyntaxKind[SyntaxKind["WithKeyword"] = 100] = "WithKeyword"; + SyntaxKind[SyntaxKind["ImplementsKeyword"] = 101] = "ImplementsKeyword"; + SyntaxKind[SyntaxKind["InterfaceKeyword"] = 102] = "InterfaceKeyword"; + SyntaxKind[SyntaxKind["LetKeyword"] = 103] = "LetKeyword"; + SyntaxKind[SyntaxKind["PackageKeyword"] = 104] = "PackageKeyword"; + SyntaxKind[SyntaxKind["PrivateKeyword"] = 105] = "PrivateKeyword"; + SyntaxKind[SyntaxKind["ProtectedKeyword"] = 106] = "ProtectedKeyword"; + SyntaxKind[SyntaxKind["PublicKeyword"] = 107] = "PublicKeyword"; + SyntaxKind[SyntaxKind["StaticKeyword"] = 108] = "StaticKeyword"; + SyntaxKind[SyntaxKind["YieldKeyword"] = 109] = "YieldKeyword"; + SyntaxKind[SyntaxKind["AnyKeyword"] = 110] = "AnyKeyword"; + SyntaxKind[SyntaxKind["BooleanKeyword"] = 111] = "BooleanKeyword"; + SyntaxKind[SyntaxKind["ConstructorKeyword"] = 112] = "ConstructorKeyword"; + SyntaxKind[SyntaxKind["DeclareKeyword"] = 113] = "DeclareKeyword"; + SyntaxKind[SyntaxKind["GetKeyword"] = 114] = "GetKeyword"; + SyntaxKind[SyntaxKind["ModuleKeyword"] = 115] = "ModuleKeyword"; + SyntaxKind[SyntaxKind["RequireKeyword"] = 116] = "RequireKeyword"; + SyntaxKind[SyntaxKind["NumberKeyword"] = 117] = "NumberKeyword"; + SyntaxKind[SyntaxKind["SetKeyword"] = 118] = "SetKeyword"; + SyntaxKind[SyntaxKind["StringKeyword"] = 119] = "StringKeyword"; + SyntaxKind[SyntaxKind["TypeKeyword"] = 120] = "TypeKeyword"; + SyntaxKind[SyntaxKind["QualifiedName"] = 121] = "QualifiedName"; + SyntaxKind[SyntaxKind["ComputedPropertyName"] = 122] = "ComputedPropertyName"; + SyntaxKind[SyntaxKind["TypeParameter"] = 123] = "TypeParameter"; + SyntaxKind[SyntaxKind["Parameter"] = 124] = "Parameter"; + SyntaxKind[SyntaxKind["PropertySignature"] = 125] = "PropertySignature"; + SyntaxKind[SyntaxKind["PropertyDeclaration"] = 126] = "PropertyDeclaration"; + SyntaxKind[SyntaxKind["MethodSignature"] = 127] = "MethodSignature"; + SyntaxKind[SyntaxKind["MethodDeclaration"] = 128] = "MethodDeclaration"; + SyntaxKind[SyntaxKind["Constructor"] = 129] = "Constructor"; + SyntaxKind[SyntaxKind["GetAccessor"] = 130] = "GetAccessor"; + SyntaxKind[SyntaxKind["SetAccessor"] = 131] = "SetAccessor"; + SyntaxKind[SyntaxKind["CallSignature"] = 132] = "CallSignature"; + SyntaxKind[SyntaxKind["ConstructSignature"] = 133] = "ConstructSignature"; + SyntaxKind[SyntaxKind["IndexSignature"] = 134] = "IndexSignature"; + SyntaxKind[SyntaxKind["TypeReference"] = 135] = "TypeReference"; + SyntaxKind[SyntaxKind["FunctionType"] = 136] = "FunctionType"; + SyntaxKind[SyntaxKind["ConstructorType"] = 137] = "ConstructorType"; + SyntaxKind[SyntaxKind["TypeQuery"] = 138] = "TypeQuery"; + SyntaxKind[SyntaxKind["TypeLiteral"] = 139] = "TypeLiteral"; + SyntaxKind[SyntaxKind["ArrayType"] = 140] = "ArrayType"; + SyntaxKind[SyntaxKind["TupleType"] = 141] = "TupleType"; + SyntaxKind[SyntaxKind["UnionType"] = 142] = "UnionType"; + SyntaxKind[SyntaxKind["ParenthesizedType"] = 143] = "ParenthesizedType"; + SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 144] = "ObjectBindingPattern"; + SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 145] = "ArrayBindingPattern"; + SyntaxKind[SyntaxKind["BindingElement"] = 146] = "BindingElement"; + SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 147] = "ArrayLiteralExpression"; + SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 148] = "ObjectLiteralExpression"; + SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 149] = "PropertyAccessExpression"; + SyntaxKind[SyntaxKind["ElementAccessExpression"] = 150] = "ElementAccessExpression"; + SyntaxKind[SyntaxKind["CallExpression"] = 151] = "CallExpression"; + SyntaxKind[SyntaxKind["NewExpression"] = 152] = "NewExpression"; + SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 153] = "TaggedTemplateExpression"; + SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 154] = "TypeAssertionExpression"; + SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 155] = "ParenthesizedExpression"; + SyntaxKind[SyntaxKind["FunctionExpression"] = 156] = "FunctionExpression"; + SyntaxKind[SyntaxKind["ArrowFunction"] = 157] = "ArrowFunction"; + SyntaxKind[SyntaxKind["DeleteExpression"] = 158] = "DeleteExpression"; + SyntaxKind[SyntaxKind["TypeOfExpression"] = 159] = "TypeOfExpression"; + SyntaxKind[SyntaxKind["VoidExpression"] = 160] = "VoidExpression"; + SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 161] = "PrefixUnaryExpression"; + SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 162] = "PostfixUnaryExpression"; + SyntaxKind[SyntaxKind["BinaryExpression"] = 163] = "BinaryExpression"; + SyntaxKind[SyntaxKind["ConditionalExpression"] = 164] = "ConditionalExpression"; + SyntaxKind[SyntaxKind["TemplateExpression"] = 165] = "TemplateExpression"; + SyntaxKind[SyntaxKind["YieldExpression"] = 166] = "YieldExpression"; + SyntaxKind[SyntaxKind["SpreadElementExpression"] = 167] = "SpreadElementExpression"; + SyntaxKind[SyntaxKind["OmittedExpression"] = 168] = "OmittedExpression"; + SyntaxKind[SyntaxKind["TemplateSpan"] = 169] = "TemplateSpan"; + SyntaxKind[SyntaxKind["Block"] = 170] = "Block"; + SyntaxKind[SyntaxKind["VariableStatement"] = 171] = "VariableStatement"; + SyntaxKind[SyntaxKind["EmptyStatement"] = 172] = "EmptyStatement"; + SyntaxKind[SyntaxKind["ExpressionStatement"] = 173] = "ExpressionStatement"; + SyntaxKind[SyntaxKind["IfStatement"] = 174] = "IfStatement"; + SyntaxKind[SyntaxKind["DoStatement"] = 175] = "DoStatement"; + SyntaxKind[SyntaxKind["WhileStatement"] = 176] = "WhileStatement"; + SyntaxKind[SyntaxKind["ForStatement"] = 177] = "ForStatement"; + SyntaxKind[SyntaxKind["ForInStatement"] = 178] = "ForInStatement"; + SyntaxKind[SyntaxKind["ContinueStatement"] = 179] = "ContinueStatement"; + SyntaxKind[SyntaxKind["BreakStatement"] = 180] = "BreakStatement"; + SyntaxKind[SyntaxKind["ReturnStatement"] = 181] = "ReturnStatement"; + SyntaxKind[SyntaxKind["WithStatement"] = 182] = "WithStatement"; + SyntaxKind[SyntaxKind["SwitchStatement"] = 183] = "SwitchStatement"; + SyntaxKind[SyntaxKind["LabeledStatement"] = 184] = "LabeledStatement"; + SyntaxKind[SyntaxKind["ThrowStatement"] = 185] = "ThrowStatement"; + SyntaxKind[SyntaxKind["TryStatement"] = 186] = "TryStatement"; + SyntaxKind[SyntaxKind["DebuggerStatement"] = 187] = "DebuggerStatement"; + SyntaxKind[SyntaxKind["VariableDeclaration"] = 188] = "VariableDeclaration"; + SyntaxKind[SyntaxKind["VariableDeclarationList"] = 189] = "VariableDeclarationList"; + SyntaxKind[SyntaxKind["FunctionDeclaration"] = 190] = "FunctionDeclaration"; + SyntaxKind[SyntaxKind["ClassDeclaration"] = 191] = "ClassDeclaration"; + SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 192] = "InterfaceDeclaration"; + SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 193] = "TypeAliasDeclaration"; + SyntaxKind[SyntaxKind["EnumDeclaration"] = 194] = "EnumDeclaration"; + SyntaxKind[SyntaxKind["ModuleDeclaration"] = 195] = "ModuleDeclaration"; + SyntaxKind[SyntaxKind["ModuleBlock"] = 196] = "ModuleBlock"; + SyntaxKind[SyntaxKind["ImportDeclaration"] = 197] = "ImportDeclaration"; + SyntaxKind[SyntaxKind["ExportAssignment"] = 198] = "ExportAssignment"; + SyntaxKind[SyntaxKind["ExternalModuleReference"] = 199] = "ExternalModuleReference"; + SyntaxKind[SyntaxKind["CaseClause"] = 200] = "CaseClause"; + SyntaxKind[SyntaxKind["DefaultClause"] = 201] = "DefaultClause"; + SyntaxKind[SyntaxKind["HeritageClause"] = 202] = "HeritageClause"; + SyntaxKind[SyntaxKind["CatchClause"] = 203] = "CatchClause"; + SyntaxKind[SyntaxKind["PropertyAssignment"] = 204] = "PropertyAssignment"; + SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 205] = "ShorthandPropertyAssignment"; + SyntaxKind[SyntaxKind["EnumMember"] = 206] = "EnumMember"; + SyntaxKind[SyntaxKind["SourceFile"] = 207] = "SourceFile"; + SyntaxKind[SyntaxKind["SyntaxList"] = 208] = "SyntaxList"; + SyntaxKind[SyntaxKind["Count"] = 209] = "Count"; + SyntaxKind[SyntaxKind["FirstAssignment"] = 52] = "FirstAssignment"; + SyntaxKind[SyntaxKind["LastAssignment"] = 63] = "LastAssignment"; + SyntaxKind[SyntaxKind["FirstReservedWord"] = 65] = "FirstReservedWord"; + SyntaxKind[SyntaxKind["LastReservedWord"] = 100] = "LastReservedWord"; + SyntaxKind[SyntaxKind["FirstKeyword"] = 65] = "FirstKeyword"; + SyntaxKind[SyntaxKind["LastKeyword"] = 120] = "LastKeyword"; + SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 101] = "FirstFutureReservedWord"; + SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 109] = "LastFutureReservedWord"; + SyntaxKind[SyntaxKind["FirstTypeNode"] = 135] = "FirstTypeNode"; + SyntaxKind[SyntaxKind["LastTypeNode"] = 143] = "LastTypeNode"; + SyntaxKind[SyntaxKind["FirstPunctuation"] = 14] = "FirstPunctuation"; + SyntaxKind[SyntaxKind["LastPunctuation"] = 63] = "LastPunctuation"; + SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken"; + SyntaxKind[SyntaxKind["LastToken"] = 120] = "LastToken"; + SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken"; + SyntaxKind[SyntaxKind["LastTriviaToken"] = 6] = "LastTriviaToken"; + SyntaxKind[SyntaxKind["FirstLiteralToken"] = 7] = "FirstLiteralToken"; + SyntaxKind[SyntaxKind["LastLiteralToken"] = 10] = "LastLiteralToken"; + SyntaxKind[SyntaxKind["FirstTemplateToken"] = 10] = "FirstTemplateToken"; + SyntaxKind[SyntaxKind["LastTemplateToken"] = 13] = "LastTemplateToken"; + SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 24] = "FirstBinaryOperator"; + SyntaxKind[SyntaxKind["LastBinaryOperator"] = 63] = "LastBinaryOperator"; + SyntaxKind[SyntaxKind["FirstNode"] = 121] = "FirstNode"; + })(ts.SyntaxKind || (ts.SyntaxKind = {})); + var SyntaxKind = ts.SyntaxKind; + (function (NodeFlags) { + NodeFlags[NodeFlags["Export"] = 1] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 16] = "Public"; + NodeFlags[NodeFlags["Private"] = 32] = "Private"; + NodeFlags[NodeFlags["Protected"] = 64] = "Protected"; + NodeFlags[NodeFlags["Static"] = 128] = "Static"; + NodeFlags[NodeFlags["MultiLine"] = 256] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 512] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 1024] = "DeclarationFile"; + NodeFlags[NodeFlags["Let"] = 2048] = "Let"; + NodeFlags[NodeFlags["Const"] = 4096] = "Const"; + NodeFlags[NodeFlags["OctalLiteral"] = 8192] = "OctalLiteral"; + NodeFlags[NodeFlags["Modifier"] = 243] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 112] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 6144] = "BlockScoped"; + })(ts.NodeFlags || (ts.NodeFlags = {})); + var NodeFlags = ts.NodeFlags; + (function (ParserContextFlags) { + ParserContextFlags[ParserContextFlags["StrictMode"] = 1] = "StrictMode"; + ParserContextFlags[ParserContextFlags["DisallowIn"] = 2] = "DisallowIn"; + ParserContextFlags[ParserContextFlags["Yield"] = 4] = "Yield"; + ParserContextFlags[ParserContextFlags["GeneratorParameter"] = 8] = "GeneratorParameter"; + ParserContextFlags[ParserContextFlags["ThisNodeHasError"] = 16] = "ThisNodeHasError"; + ParserContextFlags[ParserContextFlags["ParserGeneratedFlags"] = 31] = "ParserGeneratedFlags"; + ParserContextFlags[ParserContextFlags["ThisNodeOrAnySubNodesHasError"] = 32] = "ThisNodeOrAnySubNodesHasError"; + ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 64] = "HasAggregatedChildData"; + })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); + var ParserContextFlags = ts.ParserContextFlags; (function (EmitReturnStatus) { EmitReturnStatus[EmitReturnStatus["Succeeded"] = 0] = "Succeeded"; EmitReturnStatus[EmitReturnStatus["AllOutputGenerationSkipped"] = 1] = "AllOutputGenerationSkipped"; @@ -24,19 +289,305 @@ var ts; EmitReturnStatus[EmitReturnStatus["CompilerOptionsErrors"] = 5] = "CompilerOptionsErrors"; })(ts.EmitReturnStatus || (ts.EmitReturnStatus = {})); var EmitReturnStatus = ts.EmitReturnStatus; + (function (TypeFormatFlags) { + TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 2] = "UseTypeOfFunction"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 4] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 8] = "WriteArrowStyleSignature"; + TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 16] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 64] = "InElementType"; + })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); + var TypeFormatFlags = ts.TypeFormatFlags; + (function (SymbolFormatFlags) { + SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; + SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; + SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + })(ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); + var SymbolFormatFlags = ts.SymbolFormatFlags; + (function (SymbolAccessibility) { + SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible"; + SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible"; + SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed"; + })(ts.SymbolAccessibility || (ts.SymbolAccessibility = {})); + var SymbolAccessibility = ts.SymbolAccessibility; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable"; + SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable"; + SymbolFlags[SymbolFlags["Property"] = 4] = "Property"; + SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember"; + SymbolFlags[SymbolFlags["Function"] = 16] = "Function"; + SymbolFlags[SymbolFlags["Class"] = 32] = "Class"; + SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface"; + SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum"; + SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum"; + SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule"; + SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule"; + SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral"; + SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral"; + SymbolFlags[SymbolFlags["Method"] = 8192] = "Method"; + SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor"; + SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor"; + SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature"; + SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter"; + SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias"; + SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue"; + SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; + SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; + SymbolFlags[SymbolFlags["Import"] = 8388608] = "Import"; + SymbolFlags[SymbolFlags["Instantiated"] = 16777216] = "Instantiated"; + SymbolFlags[SymbolFlags["Merged"] = 33554432] = "Merged"; + SymbolFlags[SymbolFlags["Transient"] = 67108864] = "Transient"; + SymbolFlags[SymbolFlags["Prototype"] = 134217728] = "Prototype"; + SymbolFlags[SymbolFlags["UnionProperty"] = 268435456] = "UnionProperty"; + SymbolFlags[SymbolFlags["Optional"] = 536870912] = "Optional"; + SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; + SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; + SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; + SymbolFlags[SymbolFlags["Type"] = 793056] = "Type"; + SymbolFlags[SymbolFlags["Namespace"] = 1536] = "Namespace"; + SymbolFlags[SymbolFlags["Module"] = 1536] = "Module"; + SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor"; + SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 107454] = "FunctionScopedVariableExcludes"; + SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 107455] = "BlockScopedVariableExcludes"; + SymbolFlags[SymbolFlags["ParameterExcludes"] = 107455] = "ParameterExcludes"; + SymbolFlags[SymbolFlags["PropertyExcludes"] = 107455] = "PropertyExcludes"; + SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 107455] = "EnumMemberExcludes"; + SymbolFlags[SymbolFlags["FunctionExcludes"] = 106927] = "FunctionExcludes"; + SymbolFlags[SymbolFlags["ClassExcludes"] = 899583] = "ClassExcludes"; + SymbolFlags[SymbolFlags["InterfaceExcludes"] = 792992] = "InterfaceExcludes"; + SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes"; + SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes"; + SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 106639] = "ValueModuleExcludes"; + SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes"; + SymbolFlags[SymbolFlags["MethodExcludes"] = 99263] = "MethodExcludes"; + SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 41919] = "GetAccessorExcludes"; + SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 74687] = "SetAccessorExcludes"; + SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 530912] = "TypeParameterExcludes"; + SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 793056] = "TypeAliasExcludes"; + SymbolFlags[SymbolFlags["ImportExcludes"] = 8388608] = "ImportExcludes"; + SymbolFlags[SymbolFlags["ModuleMember"] = 8914931] = "ModuleMember"; + SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal"; + SymbolFlags[SymbolFlags["HasLocals"] = 255504] = "HasLocals"; + SymbolFlags[SymbolFlags["HasExports"] = 1952] = "HasExports"; + SymbolFlags[SymbolFlags["HasMembers"] = 6240] = "HasMembers"; + SymbolFlags[SymbolFlags["IsContainer"] = 262128] = "IsContainer"; + SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor"; + SymbolFlags[SymbolFlags["Export"] = 7340032] = "Export"; + })(ts.SymbolFlags || (ts.SymbolFlags = {})); + var SymbolFlags = ts.SymbolFlags; + (function (NodeCheckFlags) { + NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; + NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis"; + NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis"; + NodeCheckFlags[NodeCheckFlags["EmitExtends"] = 8] = "EmitExtends"; + NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 16] = "SuperInstance"; + NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 32] = "SuperStatic"; + NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 64] = "ContextChecked"; + NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 128] = "EnumValuesComputed"; + })(ts.NodeCheckFlags || (ts.NodeCheckFlags = {})); + var NodeCheckFlags = ts.NodeCheckFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["Any"] = 1] = "Any"; + TypeFlags[TypeFlags["String"] = 2] = "String"; + TypeFlags[TypeFlags["Number"] = 4] = "Number"; + TypeFlags[TypeFlags["Boolean"] = 8] = "Boolean"; + TypeFlags[TypeFlags["Void"] = 16] = "Void"; + TypeFlags[TypeFlags["Undefined"] = 32] = "Undefined"; + TypeFlags[TypeFlags["Null"] = 64] = "Null"; + TypeFlags[TypeFlags["Enum"] = 128] = "Enum"; + TypeFlags[TypeFlags["StringLiteral"] = 256] = "StringLiteral"; + TypeFlags[TypeFlags["TypeParameter"] = 512] = "TypeParameter"; + TypeFlags[TypeFlags["Class"] = 1024] = "Class"; + TypeFlags[TypeFlags["Interface"] = 2048] = "Interface"; + TypeFlags[TypeFlags["Reference"] = 4096] = "Reference"; + TypeFlags[TypeFlags["Tuple"] = 8192] = "Tuple"; + TypeFlags[TypeFlags["Union"] = 16384] = "Union"; + TypeFlags[TypeFlags["Anonymous"] = 32768] = "Anonymous"; + TypeFlags[TypeFlags["FromSignature"] = 65536] = "FromSignature"; + TypeFlags[TypeFlags["Unwidened"] = 131072] = "Unwidened"; + TypeFlags[TypeFlags["Intrinsic"] = 127] = "Intrinsic"; + TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; + TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; + TypeFlags[TypeFlags["ObjectType"] = 48128] = "ObjectType"; + })(ts.TypeFlags || (ts.TypeFlags = {})); + var TypeFlags = ts.TypeFlags; + (function (SignatureKind) { + SignatureKind[SignatureKind["Call"] = 0] = "Call"; + SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; + })(ts.SignatureKind || (ts.SignatureKind = {})); + var SignatureKind = ts.SignatureKind; + (function (IndexKind) { + IndexKind[IndexKind["String"] = 0] = "String"; + IndexKind[IndexKind["Number"] = 1] = "Number"; + })(ts.IndexKind || (ts.IndexKind = {})); + var IndexKind = ts.IndexKind; (function (DiagnosticCategory) { DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning"; DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error"; DiagnosticCategory[DiagnosticCategory["Message"] = 2] = "Message"; })(ts.DiagnosticCategory || (ts.DiagnosticCategory = {})); var DiagnosticCategory = ts.DiagnosticCategory; + (function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + })(ts.ModuleKind || (ts.ModuleKind = {})); + var ModuleKind = ts.ModuleKind; + (function (ScriptTarget) { + ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; + ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; + ScriptTarget[ScriptTarget["ES6"] = 2] = "ES6"; + ScriptTarget[ScriptTarget["Latest"] = 2] = "Latest"; + })(ts.ScriptTarget || (ts.ScriptTarget = {})); + var ScriptTarget = ts.ScriptTarget; + (function (CharacterCodes) { + CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; + CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; + CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; + CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; + CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator"; + CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator"; + CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine"; + CharacterCodes[CharacterCodes["space"] = 32] = "space"; + CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace"; + CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad"; + CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad"; + CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace"; + CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace"; + CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace"; + CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace"; + CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace"; + CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace"; + CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace"; + CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace"; + CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace"; + CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace"; + CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace"; + CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace"; + CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace"; + CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham"; + CharacterCodes[CharacterCodes["_"] = 95] = "_"; + CharacterCodes[CharacterCodes["$"] = 36] = "$"; + CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; + CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; + CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; + CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; + CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; + CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; + CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; + CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; + CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; + CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; + CharacterCodes[CharacterCodes["a"] = 97] = "a"; + CharacterCodes[CharacterCodes["b"] = 98] = "b"; + CharacterCodes[CharacterCodes["c"] = 99] = "c"; + CharacterCodes[CharacterCodes["d"] = 100] = "d"; + CharacterCodes[CharacterCodes["e"] = 101] = "e"; + CharacterCodes[CharacterCodes["f"] = 102] = "f"; + CharacterCodes[CharacterCodes["g"] = 103] = "g"; + CharacterCodes[CharacterCodes["h"] = 104] = "h"; + CharacterCodes[CharacterCodes["i"] = 105] = "i"; + CharacterCodes[CharacterCodes["j"] = 106] = "j"; + CharacterCodes[CharacterCodes["k"] = 107] = "k"; + CharacterCodes[CharacterCodes["l"] = 108] = "l"; + CharacterCodes[CharacterCodes["m"] = 109] = "m"; + CharacterCodes[CharacterCodes["n"] = 110] = "n"; + CharacterCodes[CharacterCodes["o"] = 111] = "o"; + CharacterCodes[CharacterCodes["p"] = 112] = "p"; + CharacterCodes[CharacterCodes["q"] = 113] = "q"; + CharacterCodes[CharacterCodes["r"] = 114] = "r"; + CharacterCodes[CharacterCodes["s"] = 115] = "s"; + CharacterCodes[CharacterCodes["t"] = 116] = "t"; + CharacterCodes[CharacterCodes["u"] = 117] = "u"; + CharacterCodes[CharacterCodes["v"] = 118] = "v"; + CharacterCodes[CharacterCodes["w"] = 119] = "w"; + CharacterCodes[CharacterCodes["x"] = 120] = "x"; + CharacterCodes[CharacterCodes["y"] = 121] = "y"; + CharacterCodes[CharacterCodes["z"] = 122] = "z"; + CharacterCodes[CharacterCodes["A"] = 65] = "A"; + CharacterCodes[CharacterCodes["B"] = 66] = "B"; + CharacterCodes[CharacterCodes["C"] = 67] = "C"; + CharacterCodes[CharacterCodes["D"] = 68] = "D"; + CharacterCodes[CharacterCodes["E"] = 69] = "E"; + CharacterCodes[CharacterCodes["F"] = 70] = "F"; + CharacterCodes[CharacterCodes["G"] = 71] = "G"; + CharacterCodes[CharacterCodes["H"] = 72] = "H"; + CharacterCodes[CharacterCodes["I"] = 73] = "I"; + CharacterCodes[CharacterCodes["J"] = 74] = "J"; + CharacterCodes[CharacterCodes["K"] = 75] = "K"; + CharacterCodes[CharacterCodes["L"] = 76] = "L"; + CharacterCodes[CharacterCodes["M"] = 77] = "M"; + CharacterCodes[CharacterCodes["N"] = 78] = "N"; + CharacterCodes[CharacterCodes["O"] = 79] = "O"; + CharacterCodes[CharacterCodes["P"] = 80] = "P"; + CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; + CharacterCodes[CharacterCodes["R"] = 82] = "R"; + CharacterCodes[CharacterCodes["S"] = 83] = "S"; + CharacterCodes[CharacterCodes["T"] = 84] = "T"; + CharacterCodes[CharacterCodes["U"] = 85] = "U"; + CharacterCodes[CharacterCodes["V"] = 86] = "V"; + CharacterCodes[CharacterCodes["W"] = 87] = "W"; + CharacterCodes[CharacterCodes["X"] = 88] = "X"; + CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; + CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; + CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand"; + CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; + CharacterCodes[CharacterCodes["at"] = 64] = "at"; + CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; + CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick"; + CharacterCodes[CharacterCodes["bar"] = 124] = "bar"; + CharacterCodes[CharacterCodes["caret"] = 94] = "caret"; + CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; + CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; + CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen"; + CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; + CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; + CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; + CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; + CharacterCodes[CharacterCodes["equals"] = 61] = "equals"; + CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation"; + CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan"; + CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan"; + CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; + CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; + CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; + CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen"; + CharacterCodes[CharacterCodes["percent"] = 37] = "percent"; + CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; + CharacterCodes[CharacterCodes["question"] = 63] = "question"; + CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon"; + CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote"; + CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; + CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde"; + CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace"; + CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; + CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark"; + CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; + CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab"; + })(ts.CharacterCodes || (ts.CharacterCodes = {})); + var CharacterCodes = ts.CharacterCodes; })(ts || (ts = {})); var ts; (function (ts) { + (function (Ternary) { + Ternary[Ternary["False"] = 0] = "False"; + Ternary[Ternary["Maybe"] = 1] = "Maybe"; + Ternary[Ternary["True"] = -1] = "True"; + })(ts.Ternary || (ts.Ternary = {})); + var Ternary = ts.Ternary; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(ts.Comparison || (ts.Comparison = {})); + var Comparison = ts.Comparison; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i]); + var result = callback(array[i], i); if (result) { return result; } @@ -578,6 +1129,13 @@ var ts; getTypeConstructor: function () { return Type; }, getSignatureConstructor: function () { return Signature; } }; + (function (AssertionLevel) { + AssertionLevel[AssertionLevel["None"] = 0] = "None"; + AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal"; + AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive"; + AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive"; + })(ts.AssertionLevel || (ts.AssertionLevel = {})); + var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { var currentAssertionLevel = 0 /* None */; @@ -943,7 +1501,9 @@ var ts; A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: 1 /* Error */, key: "A destructuring declaration must have an initializer.", isEarly: true }, Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: 1 /* Error */, key: "Destructuring declarations are not allowed in ambient contexts.", isEarly: true }, An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: 1 /* Error */, key: "An implementation cannot be declared in ambient contexts.", isEarly: true }, - Merge_conflict_marker_encountered: { code: 1184, category: 1 /* Error */, key: "Merge conflict marker encountered." }, + Modifiers_cannot_appear_here: { code: 1184, category: 1 /* Error */, key: "Modifiers cannot appear here." }, + Merge_conflict_marker_encountered: { code: 1185, category: 1 /* Error */, key: "Merge conflict marker encountered." }, + A_rest_element_cannot_have_an_initializer: { code: 1186, category: 1 /* Error */, key: "A rest element cannot have an initializer." }, Duplicate_identifier_0: { code: 2300, category: 1 /* Error */, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: 1 /* Error */, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: 1 /* Error */, key: "Static members cannot reference class type parameters." }, @@ -1094,6 +1654,7 @@ var ts; Type_0_has_no_property_1_and_no_string_index_signature: { code: 2459, category: 1 /* Error */, key: "Type '{0}' has no property '{1}' and no string index signature." }, Type_0_has_no_property_1: { code: 2460, category: 1 /* Error */, key: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: 1 /* Error */, key: "Type '{0}' is not an array type." }, + A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: 1 /* Error */, key: "A rest element must be last in an array destructuring pattern" }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: 1 /* Error */, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1177,6 +1738,8 @@ var ts; Could_not_write_file_0_Colon_1: { code: 5033, category: 1 /* Error */, key: "Could not write file '{0}': {1}" }, Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, + Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option noEmit cannot be specified with option out or outDir." }, + Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option noEmit cannot be specified with option declaration." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: 2 /* Message */, key: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: 2 /* Message */, key: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: 2 /* Message */, key: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1186,6 +1749,7 @@ var ts; Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: 2 /* Message */, key: "Do not erase const enum declarations in generated code." }, Do_not_emit_outputs_if_any_type_checking_errors_were_reported: { code: 6008, category: 2 /* Message */, key: "Do not emit outputs if any type checking errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: 2 /* Message */, key: "Do not emit comments to output." }, + Do_not_emit_outputs: { code: 6010, category: 2 /* Message */, key: "Do not emit outputs." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: 2 /* Message */, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" }, Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: 2 /* Message */, key: "Specify module code generation: 'commonjs' or 'amd'" }, Print_this_message: { code: 6017, category: 2 /* Message */, key: "Print this message." }, @@ -1521,25 +2085,42 @@ var ts; } } ts.skipTrivia = skipTrivia; + var mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text, pos) { - if (pos > 0 && isLineBreak(text.charCodeAt(pos - 1))) { + ts.Debug.assert(pos >= 0); + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { var ch = text.charCodeAt(pos); - var markerLength = "<<<<<<<".length; - if ((pos + markerLength) < text.length) { - for (var i = 0, n = markerLength; i < n; i++) { + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) { if (text.charCodeAt(pos + i) !== ch) { return false; } } - return ch === 61 /* equals */ || text.charCodeAt(pos + markerLength) === 32 /* space */; + return ch === 61 /* equals */ || text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */; } } return false; } - function scanConflictMarkerTrivia(text, pos) { + function scanConflictMarkerTrivia(text, pos, error) { + if (error) { + error(ts.Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + } + var ch = text.charCodeAt(pos); var len = text.length; - while (pos < len && !isLineBreak(text.charCodeAt(pos))) { - pos++; + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + ts.Debug.assert(ch === 61 /* equals */); + while (pos < len) { + var ch = text.charCodeAt(pos); + if (ch === 62 /* greaterThan */ && isConflictMarkerTrivia(text, pos)) { + break; + } + pos++; + } } return pos; } @@ -1638,9 +2219,9 @@ var ts; var tokenValue; var precedingLineBreak; var tokenIsUnterminated; - function error(message) { + function error(message, length) { if (onError) { - onError(message); + onError(message, length || 0); } } function isIdentifierStart(ch) { @@ -2103,8 +2684,7 @@ var ts; return pos++, token = 22 /* SemicolonToken */; case 60 /* lessThan */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2124,8 +2704,7 @@ var ts; return pos++, token = 24 /* LessThanToken */; case 61 /* equals */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2145,8 +2724,7 @@ var ts; return pos++, token = 52 /* EqualsToken */; case 62 /* greaterThan */: if (isConflictMarkerTrivia(text, pos)) { - error(ts.Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -2392,17 +2970,14 @@ var ts; return node.end - node.pos; } ts.getFullWidth = getFullWidth; - function hasFlag(val, flag) { - return (val & flag) !== 0; - } function containsParseError(node) { aggregateChildData(node); - return hasFlag(node.parserContextFlags, 32 /* ThisNodeOrAnySubNodesHasError */); + return (node.parserContextFlags & 32 /* ThisNodeOrAnySubNodesHasError */) !== 0; } ts.containsParseError = containsParseError; function aggregateChildData(node) { - if (!hasFlag(node.parserContextFlags, 64 /* HasAggregatedChildData */)) { - var thisNodeOrAnySubNodesHasError = hasFlag(node.parserContextFlags, 16 /* ThisNodeHasError */) || ts.forEachChild(node, containsParseError); + if (!(node.parserContextFlags & 64 /* HasAggregatedChildData */)) { + var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & 16 /* ThisNodeHasError */) !== 0) || ts.forEachChild(node, containsParseError); if (thisNodeOrAnySubNodesHasError) { node.parserContextFlags |= 32 /* ThisNodeOrAnySubNodesHasError */; } @@ -2426,19 +3001,26 @@ var ts; return node.pos; } ts.getStartPosOfNode = getStartPosOfNode; - function isMissingNode(node) { + function nodeIsMissing(node) { + if (!node) { + return true; + } return node.pos === node.end && node.kind !== 1 /* EndOfFileToken */; } - ts.isMissingNode = isMissingNode; + ts.nodeIsMissing = nodeIsMissing; + function nodeIsPresent(node) { + return !nodeIsMissing(node); + } + ts.nodeIsPresent = nodeIsPresent; function getTokenPosOfNode(node, sourceFile) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return node.pos; } return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos); } ts.getTokenPosOfNode = getTokenPosOfNode; function getSourceTextOfNodeFromSourceFile(sourceFile, node) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } var text = sourceFile.text; @@ -2446,7 +3028,7 @@ var ts; } ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile; function getTextOfNodeFromSourceText(sourceText, node) { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } return sourceText.substring(ts.skipTrivia(sourceText, node.pos), node.end); @@ -2487,7 +3069,7 @@ var ts; function getErrorSpanForNode(node) { var errorSpan; switch (node.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 191 /* ClassDeclaration */: case 192 /* InterfaceDeclaration */: @@ -2512,16 +3094,38 @@ var ts; return node.kind === 194 /* EnumDeclaration */ && isConst(node); } ts.isConstEnumDeclaration = isConstEnumDeclaration; + function walkUpBindingElementsAndPatterns(node) { + while (node && (node.kind === 146 /* BindingElement */ || isBindingPattern(node))) { + node = node.parent; + } + return node; + } + function getCombinedNodeFlags(node) { + node = walkUpBindingElementsAndPatterns(node); + var flags = node.flags; + if (node.kind === 188 /* VariableDeclaration */) { + node = node.parent; + } + if (node && node.kind === 189 /* VariableDeclarationList */) { + flags |= node.flags; + node = node.parent; + } + if (node && node.kind === 171 /* VariableStatement */) { + flags |= node.flags; + } + return flags; + } + ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(node.flags & 4096 /* Const */); + return !!(getCombinedNodeFlags(node) & 4096 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(node.flags & 2048 /* Let */); + return !!(getCombinedNodeFlags(node) & 2048 /* Let */); } ts.isLet = isLet; function isPrologueDirective(node) { - return node.kind === 172 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; + return node.kind === 173 /* ExpressionStatement */ && node.expression.kind === 8 /* StringLiteral */; } ts.isPrologueDirective = isPrologueDirective; function getLeadingCommentRangesOfNode(node, sourceFileOfNode) { @@ -2546,23 +3150,21 @@ var ts; return traverse(body); function traverse(node) { switch (node.kind) { - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return visitor(node); - case 169 /* Block */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return ts.forEachChild(node, traverse); } } @@ -2594,7 +3196,7 @@ var ts; } ts.isAnyFunction = isAnyFunction; function isFunctionBlock(node) { - return node && node.kind === 169 /* Block */ && isAnyFunction(node.parent); + return node && node.kind === 170 /* Block */ && isAnyFunction(node.parent); } ts.isFunctionBlock = isFunctionBlock; function isObjectLiteralMethod(node) { @@ -2690,9 +3292,10 @@ var ts; case 162 /* PostfixUnaryExpression */: case 163 /* BinaryExpression */: case 164 /* ConditionalExpression */: + case 167 /* SpreadElementExpression */: case 165 /* TemplateExpression */: case 10 /* NoSubstitutionTemplateLiteral */: - case 167 /* OmittedExpression */: + case 168 /* OmittedExpression */: return true; case 121 /* QualifiedName */: while (node.parent.kind === 121 /* QualifiedName */) { @@ -2707,7 +3310,7 @@ var ts; case 8 /* StringLiteral */: var parent = node.parent; switch (parent.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 124 /* Parameter */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: @@ -2715,24 +3318,26 @@ var ts; case 204 /* PropertyAssignment */: case 146 /* BindingElement */: return parent.initializer === node; - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 180 /* ReturnStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 181 /* ReturnStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: - case 184 /* ThrowStatement */: - case 182 /* SwitchStatement */: + case 185 /* ThrowStatement */: + case 183 /* SwitchStatement */: return parent.expression === node; - case 176 /* ForStatement */: - return parent.initializer === node || parent.condition === node || parent.iterator === node; - case 177 /* ForInStatement */: - return parent.variable === node || parent.expression === node; + case 177 /* ForStatement */: + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== 189 /* VariableDeclarationList */) || forStatement.condition === node || forStatement.iterator === node; + case 178 /* ForInStatement */: + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== 189 /* VariableDeclarationList */) || forInStatement.expression === node; case 154 /* TypeAssertionExpression */: return node === parent.expression; - case 168 /* TemplateSpan */: + case 169 /* TemplateSpan */: return node === parent.expression; default: if (isExpression(parent)) { @@ -2800,8 +3405,9 @@ var ts; ts.isBindingPattern = isBindingPattern; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 /* Ambient */ | 1024 /* DeclarationFile */)) + if (node.flags & (2 /* Ambient */ | 1024 /* DeclarationFile */)) { return true; + } node = node.parent; } return false; @@ -2811,7 +3417,7 @@ var ts; switch (node.kind) { case 123 /* TypeParameter */: case 124 /* Parameter */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: @@ -2837,23 +3443,23 @@ var ts; ts.isDeclaration = isDeclaration; function isStatement(n) { switch (n.kind) { - case 179 /* BreakStatement */: - case 178 /* ContinueStatement */: - case 188 /* DebuggerStatement */: - case 174 /* DoStatement */: - case 172 /* ExpressionStatement */: - case 171 /* EmptyStatement */: - case 177 /* ForInStatement */: - case 176 /* ForStatement */: - case 173 /* IfStatement */: - case 183 /* LabeledStatement */: - case 180 /* ReturnStatement */: - case 182 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 187 /* DebuggerStatement */: + case 175 /* DoStatement */: + case 173 /* ExpressionStatement */: + case 172 /* EmptyStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 174 /* IfStatement */: + case 184 /* LabeledStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: case 93 /* ThrowKeyword */: - case 185 /* TryStatement */: - case 170 /* VariableStatement */: - case 175 /* WhileStatement */: - case 181 /* WithStatement */: + case 186 /* TryStatement */: + case 171 /* VariableStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: case 198 /* ExportAssignment */: return true; default: @@ -2901,11 +3507,11 @@ var ts; return undefined; } ts.getHeritageClause = getHeritageClause; - function tryResolveScriptReference(program, sourceFile, reference) { - if (!program.getCompilerOptions().noResolve) { + function tryResolveScriptReference(host, sourceFile, reference) { + if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.filename) ? reference.filename : ts.combinePaths(ts.getDirectoryPath(sourceFile.filename), reference.filename); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, program.getCompilerHost().getCurrentDirectory()); - return program.getSourceFile(referenceFileName); + referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); + return host.getSourceFile(referenceFileName); } } ts.tryResolveScriptReference = tryResolveScriptReference; @@ -2996,10 +3602,134 @@ var ts; return false; } ts.isModifier = isModifier; + function createEmitHostFromProgram(program) { + var compilerHost = program.getCompilerHost(); + return { + getCanonicalFileName: compilerHost.getCanonicalFileName, + getCommonSourceDirectory: program.getCommonSourceDirectory, + getCompilerOptions: program.getCompilerOptions, + getCurrentDirectory: compilerHost.getCurrentDirectory, + getNewLine: compilerHost.getNewLine, + getSourceFile: program.getSourceFile, + getSourceFiles: program.getSourceFiles, + isEmitBlocked: program.isEmitBlocked, + writeFile: compilerHost.writeFile + }; + } + ts.createEmitHostFromProgram = createEmitHostFromProgram; + function textSpanEnd(span) { + return span.start + span.length; + } + ts.textSpanEnd = textSpanEnd; + function textSpanIsEmpty(span) { + return span.length === 0; + } + ts.textSpanIsEmpty = textSpanIsEmpty; + function textSpanContainsPosition(span, position) { + return position >= span.start && position < textSpanEnd(span); + } + ts.textSpanContainsPosition = textSpanContainsPosition; + function textSpanContainsTextSpan(span, other) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + ts.textSpanContainsTextSpan = textSpanContainsTextSpan; + function textSpanOverlapsWith(span, other) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + ts.textSpanOverlapsWith = textSpanOverlapsWith; + function textSpanOverlap(span1, span2) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + ts.textSpanOverlap = textSpanOverlap; + function textSpanIntersectsWithTextSpan(span, other) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start; + } + ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan; + function textSpanIntersectsWith(span, start, length) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + ts.textSpanIntersectsWith = textSpanIntersectsWith; + function textSpanIntersectsWithPosition(span, position) { + return position <= textSpanEnd(span) && position >= span.start; + } + ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition; + function textSpanIntersection(span1, span2) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + ts.textSpanIntersection = textSpanIntersection; + function createTextSpan(start, length) { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + return { start: start, length: length }; + } + ts.createTextSpan = createTextSpan; + function createTextSpanFromBounds(start, end) { + return createTextSpan(start, end - start); + } + ts.createTextSpanFromBounds = createTextSpanFromBounds; + function textChangeRangeNewSpan(range) { + return createTextSpan(range.span.start, range.newLength); + } + ts.textChangeRangeNewSpan = textChangeRangeNewSpan; + function textChangeRangeIsUnchanged(range) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged; + function createTextChangeRange(span, newLength) { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + return { span: span, newLength: newLength }; + } + ts.createTextChangeRange = createTextChangeRange; + ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + function collapseTextChangeRangesAcrossMultipleVersions(changes) { + if (changes.length === 0) { + return ts.unchangedTextChangeRange; + } + if (changes.length === 1) { + return changes[0]; + } + var change0 = changes[0]; + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), newEndN - oldStartN); + } + ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions; })(ts || (ts = {})); var ts; (function (ts) { - var nodeConstructors = new Array(210 /* Count */); + var nodeConstructors = new Array(209 /* Count */); function getNodeConstructor(kind) { return nodeConstructors[kind] || (nodeConstructors[kind] = ts.objectAllocator.getNodeConstructor(kind)); } @@ -3041,7 +3771,7 @@ var ts; case 125 /* PropertySignature */: case 204 /* PropertyAssignment */: case 205 /* ShorthandPropertyAssignment */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: return children(node.modifiers) || child(node.propertyName) || child(node.dotDotDotToken) || child(node.name) || child(node.questionToken) || child(node.type) || child(node.initializer); case 136 /* FunctionType */: @@ -3109,45 +3839,47 @@ var ts; return child(node.left) || child(node.right); case 164 /* ConditionalExpression */: return child(node.condition) || child(node.whenTrue) || child(node.whenFalse); - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: + case 167 /* SpreadElementExpression */: + return child(node.expression); + case 170 /* Block */: case 196 /* ModuleBlock */: return children(node.statements); case 207 /* SourceFile */: return children(node.statements) || child(node.endOfFileToken); - case 170 /* VariableStatement */: - return children(node.modifiers) || children(node.declarations); - case 172 /* ExpressionStatement */: + case 171 /* VariableStatement */: + return children(node.modifiers) || child(node.declarationList); + case 189 /* VariableDeclarationList */: + return children(node.declarations); + case 173 /* ExpressionStatement */: return child(node.expression); - case 173 /* IfStatement */: + case 174 /* IfStatement */: return child(node.expression) || child(node.thenStatement) || child(node.elseStatement); - case 174 /* DoStatement */: + case 175 /* DoStatement */: return child(node.statement) || child(node.expression); - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return child(node.expression) || child(node.statement); - case 176 /* ForStatement */: - return children(node.declarations) || child(node.initializer) || child(node.condition) || child(node.iterator) || child(node.statement); - case 177 /* ForInStatement */: - return children(node.declarations) || child(node.variable) || child(node.expression) || child(node.statement); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: + case 177 /* ForStatement */: + return child(node.initializer) || child(node.condition) || child(node.iterator) || child(node.statement); + case 178 /* ForInStatement */: + return child(node.initializer) || child(node.expression) || child(node.statement); + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: return child(node.label); - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return child(node.expression); - case 181 /* WithStatement */: + case 182 /* WithStatement */: return child(node.expression) || child(node.statement); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return child(node.expression) || children(node.clauses); case 200 /* CaseClause */: return child(node.expression) || children(node.statements); case 201 /* DefaultClause */: return children(node.statements); - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return child(node.label) || child(node.statement); - case 184 /* ThrowStatement */: + case 185 /* ThrowStatement */: return child(node.expression); - case 185 /* TryStatement */: + case 186 /* TryStatement */: return child(node.tryBlock) || child(node.catchClause) || child(node.finallyBlock); case 203 /* CatchClause */: return child(node.name) || child(node.type) || child(node.block); @@ -3169,7 +3901,7 @@ var ts; return children(node.modifiers) || child(node.exportName); case 165 /* TemplateExpression */: return child(node.head) || children(node.templateSpans); - case 168 /* TemplateSpan */: + case 169 /* TemplateSpan */: return child(node.expression) || child(node.literal); case 122 /* ComputedPropertyName */: return child(node.expression); @@ -3180,64 +3912,36 @@ var ts; } } ts.forEachChild = forEachChild; - function createCompilerHost(options) { - var currentDirectory; - var existingDirectories = {}; - function getCanonicalFileName(fileName) { - return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } - var unsupportedFileEncodingErrorCode = -2147024809; - function getSourceFile(filename, languageVersion, onError) { - try { - var text = ts.sys.readFile(filename, options.charset); - } - catch (e) { - if (onError) { - onError(e.number === unsupportedFileEncodingErrorCode ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText : e.message); - } - text = ""; - } - return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; - } - function writeFile(fileName, data, writeByteOrderMark, onError) { - function directoryExists(directoryPath) { - if (ts.hasProperty(existingDirectories, directoryPath)) { - return true; - } - if (ts.sys.directoryExists(directoryPath)) { - existingDirectories[directoryPath] = true; - return true; - } - return false; - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - ts.sys.createDirectory(directoryPath); - } - } - try { - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - ts.sys.writeFile(fileName, data, writeByteOrderMark); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } - return { - getSourceFile: getSourceFile, - getDefaultLibFilename: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"); }, - writeFile: writeFile, - getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } - }; - } - ts.createCompilerHost = createCompilerHost; + var ParsingContext; + (function (ParsingContext) { + ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements"; + ParsingContext[ParsingContext["ModuleElements"] = 1] = "ModuleElements"; + ParsingContext[ParsingContext["BlockStatements"] = 2] = "BlockStatements"; + ParsingContext[ParsingContext["SwitchClauses"] = 3] = "SwitchClauses"; + ParsingContext[ParsingContext["SwitchClauseStatements"] = 4] = "SwitchClauseStatements"; + ParsingContext[ParsingContext["TypeMembers"] = 5] = "TypeMembers"; + ParsingContext[ParsingContext["ClassMembers"] = 6] = "ClassMembers"; + ParsingContext[ParsingContext["EnumMembers"] = 7] = "EnumMembers"; + ParsingContext[ParsingContext["TypeReferences"] = 8] = "TypeReferences"; + ParsingContext[ParsingContext["VariableDeclarations"] = 9] = "VariableDeclarations"; + ParsingContext[ParsingContext["ObjectBindingElements"] = 10] = "ObjectBindingElements"; + ParsingContext[ParsingContext["ArrayBindingElements"] = 11] = "ArrayBindingElements"; + ParsingContext[ParsingContext["ArgumentExpressions"] = 12] = "ArgumentExpressions"; + ParsingContext[ParsingContext["ObjectLiteralMembers"] = 13] = "ObjectLiteralMembers"; + ParsingContext[ParsingContext["ArrayLiteralMembers"] = 14] = "ArrayLiteralMembers"; + ParsingContext[ParsingContext["Parameters"] = 15] = "Parameters"; + ParsingContext[ParsingContext["TypeParameters"] = 16] = "TypeParameters"; + ParsingContext[ParsingContext["TypeArguments"] = 17] = "TypeArguments"; + ParsingContext[ParsingContext["TupleElementTypes"] = 18] = "TupleElementTypes"; + ParsingContext[ParsingContext["HeritageClauses"] = 19] = "HeritageClauses"; + ParsingContext[ParsingContext["Count"] = 20] = "Count"; + })(ParsingContext || (ParsingContext = {})); + var Tristate; + (function (Tristate) { + Tristate[Tristate["False"] = 0] = "False"; + Tristate[Tristate["True"] = 1] = "True"; + Tristate[Tristate["Unknown"] = 2] = "Unknown"; + })(Tristate || (Tristate = {})); function parsingContextErrors(context) { switch (context) { case 0 /* SourceElements */: return ts.Diagnostics.Declaration_or_statement_expected; @@ -3298,45 +4002,269 @@ var ts; var nodeText = ts.getSourceTextOfNodeFromSourceFile(sourceFile, node.expression); return nodeText === '"use strict"' || nodeText === "'use strict'"; } + var InvalidPosition; + (function (InvalidPosition) { + InvalidPosition[InvalidPosition["Value"] = -1] = "Value"; + })(InvalidPosition || (InvalidPosition = {})); + function createSyntaxCursor(sourceFile) { + var currentArray = sourceFile.statements; + var currentArrayIndex = 0; + ts.Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = -1 /* Value */; + return { + currentNode: function (position) { + if (position !== lastQueriedPosition) { + if (current && current.end === position && currentArrayIndex < currentArray.length) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + lastQueriedPosition = position; + ts.Debug.assert(!current || current.pos === position); + return current; + } + }; + function findHighestListElementThatStartsAtPosition(position) { + currentArray = undefined; + currentArrayIndex = -1 /* Value */; + current = undefined; + forEachChild(sourceFile, visitNode, visitArray); + function visitNode(node) { + if (position >= node.pos && position < node.end) { + forEachChild(node, visitNode, visitArray); + return true; + } + return false; + } + function visitArray(array) { + if (position >= array.pos && position < array.end) { + for (var i = 0, n = array.length; i < n; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + return false; + } + } + } function createSourceFile(filename, sourceText, languageVersion, setParentNodes) { if (setParentNodes === void 0) { setParentNodes = false; } var parsingContext; - var identifiers = {}; + var identifiers; var identifierCount = 0; var nodeCount = 0; var lineStarts; - var contextFlags = 0; - var parseErrorBeforeNextFinishedNode = false; - var sourceFile = createNode(207 /* SourceFile */, 0); - if (ts.fileExtensionIs(filename, ".d.ts")) { - sourceFile.flags = 1024 /* DeclarationFile */; + var syntacticDiagnostics; + var scanner; + var token; + var syntaxCursor; + var contextFlags; + var parseErrorBeforeNextFinishedNode; + var sourceFile; + return parseSourceFile(sourceText, setParentNodes); + function parseSourceFile(text, setParentNodes) { + sourceText = text; + parsingContext = 0; + identifiers = {}; + lineStarts = undefined; + syntacticDiagnostics = undefined; + contextFlags = 0; + parseErrorBeforeNextFinishedNode = false; + sourceFile = createNode(207 /* SourceFile */, 0); + sourceFile.referenceDiagnostics = []; + sourceFile.parseDiagnostics = []; + sourceFile.semanticDiagnostics = []; + scanner = ts.createScanner(languageVersion, true, sourceText, scanError); + token = nextToken(); + sourceFile.flags = ts.fileExtensionIs(filename, ".d.ts") ? 1024 /* DeclarationFile */ : 0; + sourceFile.end = sourceText.length; + sourceFile.filename = ts.normalizePath(filename); + sourceFile.text = sourceText; + sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; + sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; + sourceFile.getLineStarts = getLineStarts; + sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; + sourceFile.update = update; + processReferenceComments(sourceFile); + sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); + ts.Debug.assert(token === 1 /* EndOfFileToken */); + sourceFile.endOfFileToken = parseTokenNode(); + setExternalModuleIndicator(sourceFile); + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.languageVersion = languageVersion; + sourceFile.identifiers = identifiers; + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + return sourceFile; } - sourceFile.end = sourceText.length; - sourceFile.filename = ts.normalizePath(filename); - sourceFile.text = sourceText; - sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; - sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; - sourceFile.getLineStarts = getLineStarts; - sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; - sourceFile.referenceDiagnostics = []; - sourceFile.parseDiagnostics = []; - sourceFile.grammarDiagnostics = []; - sourceFile.semanticDiagnostics = []; - processReferenceComments(); - var scanner = ts.createScanner(languageVersion, true, sourceText, scanError); - var token = nextToken(); - sourceFile.statements = parseList(0 /* SourceElements */, true, parseSourceElement); - ts.Debug.assert(token === 1 /* EndOfFileToken */); - sourceFile.endOfFileToken = parseTokenNode(); - sourceFile.externalModuleIndicator = getExternalModuleIndicator(); - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.languageVersion = languageVersion; - sourceFile.identifiers = identifiers; - if (setParentNodes) { - fixupParentReferences(sourceFile); + function update(newText, textChangeRange) { + if (ts.textChangeRangeIsUnchanged(textChangeRange)) { + return sourceFile; + } + if (sourceFile.statements.length === 0) { + return parseSourceFile(newText, true); + } + syntaxCursor = createSyntaxCursor(sourceFile); + var changeRange = extendToAffectedRange(textChangeRange); + var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + updateTokenPositionsAndMarkElements(sourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta); + var result = parseSourceFile(newText, true); + syntaxCursor = undefined; + return result; + } + function updateTokenPositionsAndMarkElements(node, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + visitNode(node); + function visitNode(child) { + if (child.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(child, delta); + return; + } + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + return; + } + } + function visitArray(array) { + if (array.pos > changeRangeOldEnd) { + moveElementEntirelyPastChangeRange(array, delta); + } + else { + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + } + } + } + function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) { + ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + element.pos = Math.min(element.pos, changeRangeNewEnd); + if (element.end >= changeRangeOldEnd) { + element.end += delta; + } + else { + element.end = Math.min(element.end, changeRangeNewEnd); + } + ts.Debug.assert(element.pos <= element.end); + if (element.parent) { + ts.Debug.assert(element.pos >= element.parent.pos); + ts.Debug.assert(element.end <= element.parent.end); + } + } + function moveElementEntirelyPastChangeRange(element, delta) { + if (element.length) { + visitArray(element); + } + else { + visitNode(element); + } + function visitNode(node) { + node._children = undefined; + node.pos += delta; + node.end += delta; + forEachChild(node, visitNode, visitArray); + } + function visitArray(array) { + array.pos += delta; + array.end += delta; + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + } + function extendToAffectedRange(changeRange) { + var maxLookahead = 1; + var start = changeRange.span.start; + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(start); + var position = nearestNode.pos; + start = Math.max(0, position - 1); + } + var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + return ts.createTextChangeRange(finalSpan, finalLength); + } + function findNearestNodeStartingBeforeOrAtPosition(position) { + var bestResult = sourceFile; + var lastNodeEntirelyBeforePosition; + forEachChild(sourceFile, visit); + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + return bestResult; + function getLastChild(node) { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + function getLastChildWorker(node) { + var last = undefined; + forEachChild(node, function (child) { + if (ts.nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + function visit(child) { + if (ts.nodeIsMissing(child)) { + return; + } + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + bestResult = child; + } + if (position < child.end) { + forEachChild(child, visit); + return true; + } + else { + ts.Debug.assert(child.end <= position); + lastNodeEntirelyBeforePosition = child; + } + } + else { + ts.Debug.assert(child.pos > position); + return true; + } + } } - return sourceFile; function setContextFlag(val, flag) { if (val) { contextFlags |= flag; @@ -3426,9 +4354,9 @@ var ts; } parseErrorBeforeNextFinishedNode = true; } - function scanError(message) { + function scanError(message, length) { var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, 0, message); + parseErrorAtPosition(pos, length || 0, message); } function getNodePos() { return scanner.getStartPos(); @@ -3480,13 +4408,13 @@ var ts; } return inStrictModeContext() ? token > 109 /* LastFutureReservedWord */ : token > 100 /* LastReservedWord */; } - function parseExpected(kind, diagnosticMessage, arg0) { + function parseExpected(kind, diagnosticMessage) { if (token === kind) { nextToken(); return true; } if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage, arg0); + parseErrorAtCurrentToken(diagnosticMessage); } else { parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind)); @@ -3514,7 +4442,7 @@ var ts; } return token === 15 /* CloseBraceToken */ || token === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak(); } - function parseSemicolon(diagnosticMessage) { + function parseSemicolon() { if (canParseSemicolon()) { if (token === 22 /* SemicolonToken */) { nextToken(); @@ -3522,7 +4450,7 @@ var ts; return true; } else { - return parseExpected(22 /* SemicolonToken */, diagnosticMessage); + return parseExpected(22 /* SemicolonToken */); } } function createNode(kind, pos) { @@ -3623,14 +4551,18 @@ var ts; function canFollowModifier() { return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); } - function isListElement(kind, inErrorRecovery) { - switch (kind) { + function isListElement(parsingContext, inErrorRecovery) { + var node = currentNode(parsingContext); + if (node) { + return true; + } + switch (parsingContext) { case 0 /* SourceElements */: case 1 /* ModuleElements */: return isSourceElement(inErrorRecovery); case 2 /* BlockStatements */: case 4 /* SwitchClauseStatements */: - return isStatement(inErrorRecovery); + return isStartOfStatement(inErrorRecovery); case 3 /* SwitchClauses */: return token === 66 /* CaseKeyword */ || token === 72 /* DefaultKeyword */; case 5 /* TypeMembers */: @@ -3648,13 +4580,13 @@ var ts; case 9 /* VariableDeclarations */: return isIdentifierOrPattern(); case 11 /* ArrayBindingElements */: - return token === 23 /* CommaToken */ || isIdentifierOrPattern(); + return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isIdentifierOrPattern(); case 16 /* TypeParameters */: return isIdentifier(); case 12 /* ArgumentExpressions */: return token === 23 /* CommaToken */ || isStartOfExpression(); case 14 /* ArrayLiteralMembers */: - return token === 23 /* CommaToken */ || isStartOfExpression(); + return token === 23 /* CommaToken */ || token === 21 /* DotDotDotToken */ || isStartOfExpression(); case 15 /* Parameters */: return isStartOfParameter(); case 17 /* TypeArguments */: @@ -3741,7 +4673,7 @@ var ts; var savedStrictModeContext = inStrictModeContext(); while (!isListTerminator(kind)) { if (isListElement(kind, false)) { - var element = parseElement(); + var element = parseListElement(kind, parseElement); result.push(element); if (checkForStrictMode && !inStrictModeContext()) { if (ts.isPrologueDirective(element)) { @@ -3765,6 +4697,183 @@ var ts; parsingContext = saveParsingContext; return result; } + function parseListElement(kind, parseElement) { + var node = currentNode(kind); + if (node) { + return consumeNode(node); + } + return parseElement(); + } + function currentNode(parsingContext) { + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + if (!syntaxCursor) { + return undefined; + } + var node = syntaxCursor.currentNode(scanner.getStartPos()); + if (ts.nodeIsMissing(node)) { + return undefined; + } + if (node.intersectsChange) { + return undefined; + } + if (ts.containsParseError(node)) { + return undefined; + } + var nodeContextFlags = node.parserContextFlags & 31 /* ParserGeneratedFlags */; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + return node; + } + function consumeNode(node) { + scanner.setTextPos(node.end); + nextToken(); + return node; + } + function canReuseNode(node, parsingContext) { + switch (parsingContext) { + case 1 /* ModuleElements */: + return isReusableModuleElement(node); + case 6 /* ClassMembers */: + return isReusableClassMember(node); + case 3 /* SwitchClauses */: + return isReusableSwitchClause(node); + case 2 /* BlockStatements */: + case 4 /* SwitchClauseStatements */: + return isReusableStatement(node); + case 7 /* EnumMembers */: + return isReusableEnumMember(node); + case 5 /* TypeMembers */: + return isReusableTypeMember(node); + case 9 /* VariableDeclarations */: + return isReusableVariableDeclaration(node); + case 15 /* Parameters */: + return isReusableParameter(node); + case 19 /* HeritageClauses */: + case 8 /* TypeReferences */: + case 16 /* TypeParameters */: + case 18 /* TupleElementTypes */: + case 17 /* TypeArguments */: + case 12 /* ArgumentExpressions */: + case 13 /* ObjectLiteralMembers */: + } + return false; + } + function isReusableModuleElement(node) { + if (node) { + switch (node.kind) { + case 197 /* ImportDeclaration */: + case 198 /* ExportAssignment */: + case 191 /* ClassDeclaration */: + case 192 /* InterfaceDeclaration */: + case 195 /* ModuleDeclaration */: + case 194 /* EnumDeclaration */: + case 190 /* FunctionDeclaration */: + case 171 /* VariableStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 173 /* ExpressionStatement */: + case 185 /* ThrowStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 172 /* EmptyStatement */: + case 186 /* TryStatement */: + case 184 /* LabeledStatement */: + case 175 /* DoStatement */: + case 187 /* DebuggerStatement */: + return true; + } + } + return false; + } + function isReusableClassMember(node) { + if (node) { + switch (node.kind) { + case 129 /* Constructor */: + case 134 /* IndexSignature */: + case 128 /* MethodDeclaration */: + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + case 126 /* PropertyDeclaration */: + return true; + } + } + return false; + } + function isReusableSwitchClause(node) { + if (node) { + switch (node.kind) { + case 200 /* CaseClause */: + case 201 /* DefaultClause */: + return true; + } + } + return false; + } + function isReusableStatement(node) { + if (node) { + switch (node.kind) { + case 190 /* FunctionDeclaration */: + case 171 /* VariableStatement */: + case 170 /* Block */: + case 174 /* IfStatement */: + case 173 /* ExpressionStatement */: + case 185 /* ThrowStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 172 /* EmptyStatement */: + case 186 /* TryStatement */: + case 184 /* LabeledStatement */: + case 175 /* DoStatement */: + case 187 /* DebuggerStatement */: + return true; + } + } + return false; + } + function isReusableEnumMember(node) { + return node.kind === 206 /* EnumMember */; + } + function isReusableTypeMember(node) { + if (node) { + switch (node.kind) { + case 133 /* ConstructSignature */: + case 127 /* MethodSignature */: + case 134 /* IndexSignature */: + case 125 /* PropertySignature */: + case 132 /* CallSignature */: + return true; + } + } + return false; + } + function isReusableVariableDeclaration(node) { + if (node.kind !== 188 /* VariableDeclaration */) { + return false; + } + var variableDeclarator = node; + return variableDeclarator.initializer === undefined; + } + function isReusableParameter(node) { + return node.kind === 124 /* Parameter */; + } function abortParsingListOrMoveToNextToken(kind) { parseErrorAtCurrentToken(parsingContextErrors(kind)); if (isInSomeParsingContext()) { @@ -3781,7 +4890,7 @@ var ts; var commaStart = -1; while (true) { if (isListElement(kind, false)) { - result.push(parseElement()); + result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(23 /* CommaToken */)) { continue; @@ -3860,7 +4969,7 @@ var ts; return finishNode(template); } function parseTemplateSpan() { - var span = createNode(168 /* TemplateSpan */); + var span = createNode(169 /* TemplateSpan */); span.expression = allowInAnd(parseExpression); var literal; if (token === 15 /* CloseBraceToken */) { @@ -4026,7 +5135,8 @@ var ts; nextToken(); return token === 51 /* ColonToken */ || token === 23 /* CommaToken */ || token === 19 /* CloseBracketToken */; } - function parseIndexSignatureDeclaration(fullStart, modifiers) { + function parseIndexSignatureDeclaration(modifiers) { + var fullStart = modifiers ? modifiers.pos : scanner.getStartPos(); var node = createNode(134 /* IndexSignature */, fullStart); setModifiers(node, modifiers); node.parameters = parseBracketedList(15 /* Parameters */, parseParameter, 18 /* OpenBracketToken */, 19 /* CloseBracketToken */); @@ -4062,9 +5172,21 @@ var ts; case 18 /* OpenBracketToken */: return true; default: + if (ts.isModifier(token)) { + var result = lookAhead(isStartOfIndexSignatureDeclaration); + if (result) { + return result; + } + } return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); } } + function isStartOfIndexSignatureDeclaration() { + while (ts.isModifier(token)) { + nextToken(); + } + return isIndexSignature(); + } function isTypeMemberWithLiteralPropertyName() { nextToken(); return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */ || token === 50 /* QuestionToken */ || token === 51 /* ColonToken */ || canParseSemicolon(); @@ -4075,7 +5197,7 @@ var ts; case 24 /* LessThanToken */: return parseSignatureMember(132 /* CallSignature */); case 18 /* OpenBracketToken */: - return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), undefined) : parsePropertyOrMethodSignature(); + return isIndexSignature() ? parseIndexSignatureDeclaration(undefined) : parsePropertyOrMethodSignature(); case 87 /* NewKeyword */: if (lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(133 /* ConstructSignature */); @@ -4084,11 +5206,21 @@ var ts; case 7 /* NumericLiteral */: return parsePropertyOrMethodSignature(); default: + if (ts.isModifier(token)) { + var result = tryParse(parseIndexSignatureWithModifiers); + if (result) { + return result; + } + } if (isIdentifierOrKeyword()) { return parsePropertyOrMethodSignature(); } } } + function parseIndexSignatureWithModifiers() { + var modifiers = parseModifiers(); + return isIndexSignature() ? parseIndexSignatureDeclaration(modifiers) : undefined; + } function isStartOfConstructSignature() { nextToken(); return token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */; @@ -4445,7 +5577,7 @@ var ts; if (token === 14 /* OpenBraceToken */) { return parseFunctionBlock(false, false); } - if (isStatement(true) && !isStartOfExpressionStatement() && token !== 82 /* FunctionKeyword */) { + if (isStartOfStatement(true) && !isStartOfExpressionStatement() && token !== 82 /* FunctionKeyword */) { return parseFunctionBlock(false, true); } return parseAssignmentExpressionOrHigher(); @@ -4720,16 +5852,16 @@ var ts; } function parsePrimaryExpression() { switch (token) { + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* NoSubstitutionTemplateLiteral */: + return parseLiteralNode(); case 92 /* ThisKeyword */: case 90 /* SuperKeyword */: case 88 /* NullKeyword */: case 94 /* TrueKeyword */: case 79 /* FalseKeyword */: return parseTokenNode(); - case 7 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 10 /* NoSubstitutionTemplateLiteral */: - return parseLiteralNode(); case 16 /* OpenParenToken */: return parseParenthesizedExpression(); case 18 /* OpenBracketToken */: @@ -4759,10 +5891,16 @@ var ts; return finishNode(node); } function parseAssignmentExpressionOrOmittedExpression() { - return token === 23 /* CommaToken */ ? createNode(167 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); + return token === 23 /* CommaToken */ ? createNode(168 /* OmittedExpression */) : parseAssignmentExpressionOrHigher(); + } + function parseSpreadElement() { + var node = createNode(167 /* SpreadElementExpression */); + parseExpected(21 /* DotDotDotToken */); + node.expression = parseAssignmentExpressionOrHigher(); + return finishNode(node); } function parseArrayLiteralElement() { - return parseAssignmentExpressionOrOmittedExpression(); + return token === 21 /* DotDotDotToken */ ? parseSpreadElement() : parseAssignmentExpressionOrOmittedExpression(); } function parseArgumentExpression() { return allowInAnd(parseAssignmentExpressionOrOmittedExpression); @@ -4776,21 +5914,30 @@ var ts; parseExpected(19 /* CloseBracketToken */); return finishNode(node); } + function tryParseAccessorDeclaration(fullStart, modifiers) { + if (parseContextualModifier(114 /* GetKeyword */)) { + return parseAccessorDeclaration(130 /* GetAccessor */, fullStart, modifiers); + } + else if (parseContextualModifier(118 /* SetKeyword */)) { + return parseAccessorDeclaration(131 /* SetAccessor */, fullStart, modifiers); + } + return undefined; + } function parseObjectLiteralElement() { var fullStart = scanner.getStartPos(); - var initialToken = token; - if (parseContextualModifier(114 /* GetKeyword */) || parseContextualModifier(118 /* SetKeyword */)) { - var kind = initialToken === 114 /* GetKeyword */ ? 130 /* GetAccessor */ : 131 /* SetAccessor */; - return parseAccessorDeclaration(kind, fullStart, undefined); + var modifiers = parseModifiers(); + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } var asteriskToken = parseOptionalToken(35 /* AsteriskToken */); var tokenIsIdentifier = isIdentifier(); var nameToken = token; var propertyName = parsePropertyName(); - if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, undefined, asteriskToken, propertyName, undefined, true); - } var questionToken = parseOptionalToken(50 /* QuestionToken */); + if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, propertyName, questionToken); + } if ((token === 23 /* CommaToken */ || token === 15 /* CloseBraceToken */) && tokenIsIdentifier) { var shorthandDeclaration = createNode(205 /* ShorthandPropertyAssignment */, fullStart); shorthandDeclaration.name = propertyName; @@ -4838,9 +5985,9 @@ var ts; } return finishNode(node); } - function parseBlock(kind, ignoreMissingOpenBrace, checkForStrictMode) { - var node = createNode(kind); - if (parseExpected(14 /* OpenBraceToken */) || ignoreMissingOpenBrace) { + function parseBlock(ignoreMissingOpenBrace, checkForStrictMode, diagnosticMessage) { + var node = createNode(170 /* Block */); + if (parseExpected(14 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(2 /* BlockStatements */, checkForStrictMode, parseStatement); parseExpected(15 /* CloseBraceToken */); } @@ -4849,20 +5996,20 @@ var ts; } return finishNode(node); } - function parseFunctionBlock(allowYield, ignoreMissingOpenBrace) { + function parseFunctionBlock(allowYield, ignoreMissingOpenBrace, diagnosticMessage) { var savedYieldContext = inYieldContext(); setYieldContext(allowYield); - var block = parseBlock(169 /* Block */, ignoreMissingOpenBrace, true); + var block = parseBlock(ignoreMissingOpenBrace, true, diagnosticMessage); setYieldContext(savedYieldContext); return block; } function parseEmptyStatement() { - var node = createNode(171 /* EmptyStatement */); + var node = createNode(172 /* EmptyStatement */); parseExpected(22 /* SemicolonToken */); return finishNode(node); } function parseIfStatement() { - var node = createNode(173 /* IfStatement */); + var node = createNode(174 /* IfStatement */); parseExpected(83 /* IfKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4872,7 +6019,7 @@ var ts; return finishNode(node); } function parseDoStatement() { - var node = createNode(174 /* DoStatement */); + var node = createNode(175 /* DoStatement */); parseExpected(74 /* DoKeyword */); node.statement = parseStatement(); parseExpected(99 /* WhileKeyword */); @@ -4883,7 +6030,7 @@ var ts; return finishNode(node); } function parseWhileStatement() { - var node = createNode(175 /* WhileStatement */); + var node = createNode(176 /* WhileStatement */); parseExpected(99 /* WhileKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4895,41 +6042,26 @@ var ts; var pos = getNodePos(); parseExpected(81 /* ForKeyword */); parseExpected(16 /* OpenParenToken */); + var initializer = undefined; if (token !== 22 /* SemicolonToken */) { - if (parseOptional(97 /* VarKeyword */)) { - var declarations = disallowInAnd(parseVariableDeclarationList); - } - else if (parseOptional(103 /* LetKeyword */)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), 2048 /* Let */); - } - else if (parseOptional(69 /* ConstKeyword */)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), 4096 /* Const */); + if (token === 97 /* VarKeyword */ || token === 103 /* LetKeyword */ || token === 69 /* ConstKeyword */) { + initializer = parseVariableDeclarationList(true); } else { - var varOrInit = disallowInAnd(parseExpression); + initializer = disallowInAnd(parseExpression); } } var forOrForInStatement; if (parseOptional(85 /* InKeyword */)) { - var forInStatement = createNode(177 /* ForInStatement */, pos); - if (declarations) { - forInStatement.declarations = declarations; - } - else { - forInStatement.variable = varOrInit; - } + var forInStatement = createNode(178 /* ForInStatement */, pos); + forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(17 /* CloseParenToken */); forOrForInStatement = forInStatement; } else { - var forStatement = createNode(176 /* ForStatement */, pos); - if (declarations) { - forStatement.declarations = declarations; - } - if (varOrInit) { - forStatement.initializer = varOrInit; - } + var forStatement = createNode(177 /* ForStatement */, pos); + forStatement.initializer = initializer; parseExpected(22 /* SemicolonToken */); if (token !== 22 /* SemicolonToken */ && token !== 17 /* CloseParenToken */) { forStatement.condition = allowInAnd(parseExpression); @@ -4946,7 +6078,7 @@ var ts; } function parseBreakOrContinueStatement(kind) { var node = createNode(kind); - parseExpected(kind === 179 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */); + parseExpected(kind === 180 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */); if (!canParseSemicolon()) { node.label = parseIdentifier(); } @@ -4954,7 +6086,7 @@ var ts; return finishNode(node); } function parseReturnStatement() { - var node = createNode(180 /* ReturnStatement */); + var node = createNode(181 /* ReturnStatement */); parseExpected(89 /* ReturnKeyword */); if (!canParseSemicolon()) { node.expression = allowInAnd(parseExpression); @@ -4963,7 +6095,7 @@ var ts; return finishNode(node); } function parseWithStatement() { - var node = createNode(181 /* WithStatement */); + var node = createNode(182 /* WithStatement */); parseExpected(100 /* WithKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -4990,7 +6122,7 @@ var ts; return token === 66 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause(); } function parseSwitchStatement() { - var node = createNode(182 /* SwitchStatement */); + var node = createNode(183 /* SwitchStatement */); parseExpected(91 /* SwitchKeyword */); parseExpected(16 /* OpenParenToken */); node.expression = allowInAnd(parseExpression); @@ -5001,26 +6133,23 @@ var ts; return finishNode(node); } function parseThrowStatement() { - var node = createNode(184 /* ThrowStatement */); + var node = createNode(185 /* ThrowStatement */); parseExpected(93 /* ThrowKeyword */); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); return finishNode(node); } function parseTryStatement() { - var node = createNode(185 /* TryStatement */); - node.tryBlock = parseTokenAndBlock(95 /* TryKeyword */); + var node = createNode(186 /* TryStatement */); + parseExpected(95 /* TryKeyword */); + node.tryBlock = parseBlock(false, false); node.catchClause = token === 67 /* CatchKeyword */ ? parseCatchClause() : undefined; - node.finallyBlock = !node.catchClause || token === 80 /* FinallyKeyword */ ? parseTokenAndBlock(80 /* FinallyKeyword */) : undefined; + if (!node.catchClause || token === 80 /* FinallyKeyword */) { + parseExpected(80 /* FinallyKeyword */); + node.finallyBlock = parseBlock(false, false); + } return finishNode(node); } - function parseTokenAndBlock(token) { - var pos = getNodePos(); - parseExpected(token); - var result = parseBlock(token === 95 /* TryKeyword */ ? 186 /* TryBlock */ : 187 /* FinallyBlock */, false, false); - result.pos = pos; - return result; - } function parseCatchClause() { var result = createNode(203 /* CatchClause */); parseExpected(67 /* CatchKeyword */); @@ -5028,11 +6157,11 @@ var ts; result.name = parseIdentifier(); result.type = parseTypeAnnotation(); parseExpected(17 /* CloseParenToken */); - result.block = parseBlock(169 /* Block */, false, false); + result.block = parseBlock(false, false); return finishNode(result); } function parseDebuggerStatement() { - var node = createNode(188 /* DebuggerStatement */); + var node = createNode(187 /* DebuggerStatement */); parseExpected(71 /* DebuggerKeyword */); parseSemicolon(); return finishNode(node); @@ -5041,19 +6170,25 @@ var ts; var fullStart = scanner.getStartPos(); var expression = allowInAnd(parseExpression); if (expression.kind === 64 /* Identifier */ && parseOptional(51 /* ColonToken */)) { - var labeledStatement = createNode(183 /* LabeledStatement */, fullStart); + var labeledStatement = createNode(184 /* LabeledStatement */, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - var expressionStatement = createNode(172 /* ExpressionStatement */, fullStart); + var expressionStatement = createNode(173 /* ExpressionStatement */, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); } } - function isStatement(inErrorRecovery) { + function isStartOfStatement(inErrorRecovery) { + if (ts.isModifier(token)) { + var result = lookAhead(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return true; + } + } switch (token) { case 22 /* SemicolonToken */: return !inErrorRecovery; @@ -5109,7 +6244,7 @@ var ts; function parseStatement() { switch (token) { case 14 /* OpenBraceToken */: - return parseBlock(169 /* Block */, false, false); + return parseBlock(false, false); case 97 /* VarKeyword */: case 69 /* ConstKeyword */: return parseVariableStatement(scanner.getStartPos(), undefined); @@ -5126,9 +6261,9 @@ var ts; case 81 /* ForKeyword */: return parseForOrForInStatement(); case 70 /* ContinueKeyword */: - return parseBreakOrContinueStatement(178 /* ContinueStatement */); + return parseBreakOrContinueStatement(179 /* ContinueStatement */); case 65 /* BreakKeyword */: - return parseBreakOrContinueStatement(179 /* BreakStatement */); + return parseBreakOrContinueStatement(180 /* BreakStatement */); case 89 /* ReturnKeyword */: return parseReturnStatement(); case 100 /* WithKeyword */: @@ -5148,21 +6283,50 @@ var ts; return parseVariableStatement(scanner.getStartPos(), undefined); } default: + if (ts.isModifier(token)) { + var result = tryParse(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return result; + } + } return parseExpressionOrLabeledStatement(); } } - function parseFunctionBlockOrSemicolon(isGenerator) { - if (token === 14 /* OpenBraceToken */) { - return parseFunctionBlock(isGenerator, false); + function parseVariableStatementOrFunctionDeclarationWithModifiers() { + var start = scanner.getStartPos(); + var modifiers = parseModifiers(); + switch (token) { + case 69 /* ConstKeyword */: + var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword); + if (nextTokenIsEnum) { + return undefined; + } + return parseVariableStatement(start, modifiers); + case 103 /* LetKeyword */: + if (!isLetDeclaration()) { + return undefined; + } + return parseVariableStatement(start, modifiers); + case 97 /* VarKeyword */: + return parseVariableStatement(start, modifiers); + case 82 /* FunctionKeyword */: + return parseFunctionDeclaration(start, modifiers); } - parseSemicolon(ts.Diagnostics.or_expected); return undefined; } + function parseFunctionBlockOrSemicolon(isGenerator, diagnosticMessage) { + if (token !== 14 /* OpenBraceToken */ && canParseSemicolon()) { + parseSemicolon(); + return; + } + return parseFunctionBlock(isGenerator, false, diagnosticMessage); + } function parseArrayBindingElement() { if (token === 23 /* CommaToken */) { - return createNode(167 /* OmittedExpression */); + return createNode(168 /* OmittedExpression */); } var node = createNode(146 /* BindingElement */); + node.dotDotDotToken = parseOptionalToken(21 /* DotDotDotToken */); node.name = parseIdentifierOrPattern(); node.initializer = parseInitializer(false); return finishNode(node); @@ -5208,40 +6372,37 @@ var ts; return parseIdentifier(); } function parseVariableDeclaration() { - var node = createNode(189 /* VariableDeclaration */); + var node = createNode(188 /* VariableDeclaration */); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); node.initializer = parseInitializer(false); return finishNode(node); } - function setFlag(nodes, flag) { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - node.flags |= flag; - if (node.name && ts.isBindingPattern(node.name)) { - setFlag(node.name.elements, flag); - } - } - return nodes; - } - function parseVariableDeclarationList() { - return parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); - } - function parseVariableStatement(fullStart, modifiers) { - var node = createNode(170 /* VariableStatement */, fullStart); - setModifiers(node, modifiers); - if (token === 103 /* LetKeyword */) { - node.flags |= 2048 /* Let */; - } - else if (token === 69 /* ConstKeyword */) { - node.flags |= 4096 /* Const */; - } - else { - ts.Debug.assert(token === 97 /* VarKeyword */); + function parseVariableDeclarationList(disallowIn) { + var node = createNode(189 /* VariableDeclarationList */); + switch (token) { + case 97 /* VarKeyword */: + break; + case 103 /* LetKeyword */: + node.flags |= 2048 /* Let */; + break; + case 69 /* ConstKeyword */: + node.flags |= 4096 /* Const */; + break; + default: + ts.Debug.fail(); } nextToken(); - node.declarations = allowInAnd(parseVariableDeclarationList); - setFlag(node.declarations, node.flags); + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(disallowIn); + node.declarations = parseDelimitedList(9 /* VariableDeclarations */, parseVariableDeclaration); + setDisallowInContext(savedDisallowIn); + return finishNode(node); + } + function parseVariableStatement(fullStart, modifiers) { + var node = createNode(171 /* VariableStatement */, fullStart); + setModifiers(node, modifiers); + node.declarationList = parseVariableDeclarationList(false); parseSemicolon(); return finishNode(node); } @@ -5252,7 +6413,7 @@ var ts; node.asteriskToken = parseOptionalToken(35 /* AsteriskToken */); node.name = parseIdentifier(); fillSignature(51 /* ColonToken */, !!node.asteriskToken, false, node); - node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken); + node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken, ts.Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(pos, modifiers) { @@ -5260,17 +6421,17 @@ var ts; setModifiers(node, modifiers); parseExpected(112 /* ConstructorKeyword */); fillSignature(51 /* ColonToken */, false, false, node); - node.body = parseFunctionBlockOrSemicolon(false); + node.body = parseFunctionBlockOrSemicolon(false, ts.Diagnostics.or_expected); return finishNode(node); } - function parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, requireBlock) { + function parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, diagnosticMessage) { var method = createNode(128 /* MethodDeclaration */, fullStart); setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; fillSignature(51 /* ColonToken */, !!asteriskToken, false, method); - method.body = requireBlock ? parseFunctionBlock(!!asteriskToken, false) : parseFunctionBlockOrSemicolon(!!asteriskToken); + method.body = parseFunctionBlockOrSemicolon(!!asteriskToken, diagnosticMessage); return finishNode(method); } function parsePropertyOrMethodDeclaration(fullStart, modifiers) { @@ -5278,7 +6439,7 @@ var ts; var name = parsePropertyName(); var questionToken = parseOptionalToken(50 /* QuestionToken */); if (asteriskToken || token === 16 /* OpenParenToken */ || token === 24 /* LessThanToken */) { - return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, false); + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, ts.Diagnostics.or_expected); } else { var property = createNode(126 /* PropertyDeclaration */, fullStart); @@ -5360,17 +6521,15 @@ var ts; function parseClassElement() { var fullStart = getNodePos(); var modifiers = parseModifiers(); - if (parseContextualModifier(114 /* GetKeyword */)) { - return parseAccessorDeclaration(130 /* GetAccessor */, fullStart, modifiers); - } - if (parseContextualModifier(118 /* SetKeyword */)) { - return parseAccessorDeclaration(131 /* SetAccessor */, fullStart, modifiers); + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } if (token === 112 /* ConstructorKeyword */) { return parseConstructorDeclaration(fullStart, modifiers); } if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, modifiers); + return parseIndexSignatureDeclaration(modifiers); } if (isIdentifierOrKeyword() || token === 8 /* StringLiteral */ || token === 7 /* NumericLiteral */ || token === 35 /* AsteriskToken */ || token === 18 /* OpenBracketToken */) { return parsePropertyOrMethodDeclaration(fullStart, modifiers); @@ -5606,7 +6765,7 @@ var ts; } } function isSourceElement(inErrorRecovery) { - return isDeclarationStart() || isStatement(inErrorRecovery); + return isDeclarationStart() || isStartOfStatement(inErrorRecovery); } function parseSourceElement() { return parseSourceElementOrModuleElement(); @@ -5617,7 +6776,7 @@ var ts; function parseSourceElementOrModuleElement() { return isDeclarationStart() ? parseDeclaration() : parseStatement(); } - function processReferenceComments() { + function processReferenceComments(sourceFile) { var triviaScanner = ts.createScanner(languageVersion, false, sourceText); var referencedFiles = []; var amdDependencies = []; @@ -5664,10 +6823,9 @@ var ts; sourceFile.amdDependencies = amdDependencies; sourceFile.amdModuleName = amdModuleName; } - function getExternalModuleIndicator() { - return ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ || node.kind === 197 /* ImportDeclaration */ && node.moduleReference.kind === 199 /* ExternalModuleReference */ || node.kind === 198 /* ExportAssignment */ ? node : undefined; }); + function setExternalModuleIndicator(sourceFile) { + sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { return node.flags & 1 /* Export */ || node.kind === 197 /* ImportDeclaration */ && node.moduleReference.kind === 199 /* ExternalModuleReference */ || node.kind === 198 /* ExportAssignment */ ? node : undefined; }); } - var syntacticDiagnostics; function getSyntacticDiagnostics() { if (syntacticDiagnostics === undefined) { syntacticDiagnostics = sourceFile.referenceDiagnostics.concat(sourceFile.parseDiagnostics); @@ -5710,228 +6868,15 @@ var ts; return token >= 52 /* FirstAssignment */ && token <= 63 /* LastAssignment */; } ts.isAssignmentOperator = isAssignmentOperator; - function createProgram(rootNames, options, host) { - var program; - var files = []; - var filesByName = {}; - var errors = []; - var seenNoDefaultLib = options.noLib; - var commonSourceDirectory; - ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - if (!seenNoDefaultLib) { - processRootFile(host.getDefaultLibFilename(options), true); - } - verifyCompilerOptions(); - errors.sort(ts.compareDiagnostics); - program = { - getSourceFile: getSourceFile, - getSourceFiles: function () { return files; }, - getCompilerOptions: function () { return options; }, - getCompilerHost: function () { return host; }, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeChecker: function (fullTypeCheckMode) { return ts.createTypeChecker(program, fullTypeCheckMode); }, - getCommonSourceDirectory: function () { return commonSourceDirectory; } - }; - return program; - function getSourceFile(filename) { - filename = host.getCanonicalFileName(filename); - return ts.hasProperty(filesByName, filename) ? filesByName[filename] : undefined; - } - function getDiagnostics(sourceFile) { - return sourceFile ? ts.filter(errors, function (e) { return e.file === sourceFile; }) : errors; - } - function getGlobalDiagnostics() { - return ts.filter(errors, function (e) { return !e.file; }); - } - function hasExtension(filename) { - return ts.getBaseFilename(filename).indexOf(".") >= 0; - } - function processRootFile(filename, isDefaultLib) { - processSourceFile(ts.normalizePath(filename), isDefaultLib); - } - function processSourceFile(filename, isDefaultLib, refFile, refPos, refEnd) { - if (refEnd !== undefined && refPos !== undefined) { - var start = refPos; - var length = refEnd - refPos; - } - var diagnostic; - if (hasExtension(filename)) { - if (!options.allowNonTsExtensions && !ts.fileExtensionIs(filename, ".ts")) { - diagnostic = ts.Diagnostics.File_0_must_have_extension_ts_or_d_ts; - } - else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = ts.Diagnostics.File_0_not_found; - } - else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { - diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; - } - } - else { - if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = ts.Diagnostics.File_0_not_found; - filename += ".ts"; - } - } - if (diagnostic) { - if (refFile) { - errors.push(ts.createFileDiagnostic(refFile, start, length, diagnostic, filename)); - } - else { - errors.push(ts.createCompilerDiagnostic(diagnostic, filename)); - } - } - } - function findSourceFile(filename, isDefaultLib, refFile, refStart, refLength) { - var canonicalName = host.getCanonicalFileName(filename); - if (ts.hasProperty(filesByName, canonicalName)) { - return getSourceFileFromCache(filename, canonicalName, false); - } - else { - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); - var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { - return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); - } - var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, function (hostErrorMessage) { - if (refFile) { - errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - }); - if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - filesByName[canonicalAbsolutePath] = file; - if (!options.noResolve) { - var basePath = ts.getDirectoryPath(filename); - processReferencedFiles(file, basePath); - processImportedModules(file, basePath); - } - if (isDefaultLib) { - files.unshift(file); - } - else { - files.push(file); - } - ts.forEach(file.getSyntacticDiagnostics(), function (e) { - errors.push(e); - }); - } - } - return file; - function getSourceFileFromCache(filename, canonicalName, useAbsolutePath) { - var file = filesByName[canonicalName]; - if (file && host.useCaseSensitiveFileNames()) { - var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; - if (canonicalName !== sourceFileName) { - errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); - } - } - return file; - } - } - function processReferencedFiles(file, basePath) { - ts.forEach(file.referencedFiles, function (ref) { - var referencedFilename = ts.isRootedDiskPath(ref.filename) ? ref.filename : ts.combinePaths(basePath, ref.filename); - processSourceFile(ts.normalizePath(referencedFilename), false, file, ref.pos, ref.end); - }); - } - function processImportedModules(file, basePath) { - ts.forEach(file.statements, function (node) { - if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { - var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - var searchPath = basePath; - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { - break; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - } - } - else if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { - forEachChild(node.body, function (node) { - if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { - var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - var searchName = ts.normalizePath(ts.combinePaths(basePath, moduleName)); - var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); - if (!tsFile) { - findModuleSourceFile(searchName + ".d.ts", nameLiteral); - } - } - } - }); - } - }); - function findModuleSourceFile(filename, nameLiteral) { - return findSourceFile(filename, false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); - } - } - function verifyCompilerOptions() { - if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { - if (options.mapRoot) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - if (options.sourceRoot) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - return; - } - var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (firstExternalModule && options.module === 0 /* None */) { - var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); - var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); - var errorLength = externalModuleErrorSpan.end - errorStart; - errors.push(ts.createFileDiagnostic(firstExternalModule, errorStart, errorLength, ts.Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); - } - if (options.outDir || options.sourceRoot || (options.mapRoot && (!options.out || firstExternalModule !== undefined))) { - var commonPathComponents; - ts.forEach(files, function (sourceFile) { - if (!(sourceFile.flags & 1024 /* DeclarationFile */) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { - var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); - sourcePathComponents.pop(); - if (commonPathComponents) { - for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { - if (i === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; - } - commonPathComponents.length = i; - break; - } - } - if (sourcePathComponents.length < commonPathComponents.length) { - commonPathComponents.length = sourcePathComponents.length; - } - } - else { - commonPathComponents = sourcePathComponents; - } - } - }); - commonSourceDirectory = ts.getNormalizedPathFromPathComponents(commonPathComponents); - if (commonSourceDirectory) { - commonSourceDirectory += ts.directorySeparator; - } - } - } - } - ts.createProgram = createProgram; })(ts || (ts = {})); var ts; (function (ts) { + (function (ModuleInstanceState) { + ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated"; + ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated"; + ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; + })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); + var ModuleInstanceState = ts.ModuleInstanceState; function getModuleInstanceState(node) { if (node.kind === 192 /* InterfaceDeclaration */) { return 0 /* NonInstantiated */; @@ -6080,7 +7025,7 @@ var ts; if (symbolKind & 1536 /* Namespace */) { exportKind |= 4194304 /* ExportNamespace */; } - if (node.flags & 1 /* Export */ || (node.kind !== 197 /* ImportDeclaration */ && isAmbientContext(container))) { + if (ts.getCombinedNodeFlags(node) & 1 /* Export */ || (node.kind !== 197 /* ImportDeclaration */ && isAmbientContext(container))) { if (exportKind) { var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); @@ -6104,9 +7049,7 @@ var ts; parent = node; if (symbolKind & 262128 /* IsContainer */) { container = node; - ts.Debug.assert(container.nextContainer === undefined); if (lastContainer) { - ts.Debug.assert(lastContainer.nextContainer === undefined); lastContainer.nextContainer = container; } lastContainer = container; @@ -6234,12 +7177,12 @@ var ts; case 124 /* Parameter */: bindParameter(node); break; - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: if (ts.isBindingPattern(node.name)) { bindChildren(node, 0, false); } - else if (node.flags & 6144 /* BlockScoped */) { + else if (ts.getCombinedNodeFlags(node) & 6144 /* BlockScoped */) { bindBlockScopedVariableDeclaration(node); } else { @@ -6323,13 +7266,11 @@ var ts; bindAnonymousDeclaration(node, 512 /* ValueModule */, '"' + ts.removeFileExtension(node.filename) + '"', true); break; } - case 169 /* Block */: - case 186 /* TryBlock */: + case 170 /* Block */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 182 /* SwitchStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 183 /* SwitchStatement */: bindChildren(node, 0, true); break; default: @@ -6355,3434 +7296,27 @@ var ts; ts.bindSourceFile = bindSourceFile; })(ts || (ts = {})); var ts; -(function (ts) { - var indentStrings = ["", " "]; - function getIndentString(level) { - if (indentStrings[level] === undefined) { - indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; - } - return indentStrings[level]; - } - ts.getIndentString = getIndentString; - function getIndentSize() { - return indentStrings[1].length; - } - function shouldEmitToOwnFile(sourceFile, compilerOptions) { - if (!ts.isDeclarationFile(sourceFile)) { - if ((ts.isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { - return true; - } - return false; - } - return false; - } - ts.shouldEmitToOwnFile = shouldEmitToOwnFile; - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; - function createTextWriter(newLine) { - var output = ""; - var indent = 0; - var lineStart = true; - var lineCount = 0; - var linePos = 0; - function write(s) { - if (s && s.length) { - if (lineStart) { - output += getIndentString(indent); - lineStart = false; - } - output += s; - } - } - function rawWrite(s) { - if (s !== undefined) { - if (lineStart) { - lineStart = false; - } - output += s; - } - } - function writeLiteral(s) { - if (s && s.length) { - write(s); - var lineStartsOfS = ts.computeLineStarts(s); - if (lineStartsOfS.length > 1) { - lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; - } - } - } - function writeLine() { - if (!lineStart) { - output += newLine; - lineCount++; - linePos = output.length; - lineStart = true; - } - } - function writeTextOfNode(sourceFile, node) { - write(ts.getSourceTextOfNodeFromSourceFile(sourceFile, node)); - } - return { - write: write, - rawWrite: rawWrite, - writeTextOfNode: writeTextOfNode, - writeLiteral: writeLiteral, - writeLine: writeLine, - increaseIndent: function () { return indent++; }, - decreaseIndent: function () { return indent--; }, - getIndent: function () { return indent; }, - getTextPos: function () { return output.length; }, - getLine: function () { return lineCount + 1; }, - getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, - getText: function () { return output; } - }; - } - function getLineOfLocalPosition(currentSourceFile, pos) { - return currentSourceFile.getLineAndCharacterFromPosition(pos).line; - } - function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { - if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { - writer.writeLine(); - } - } - function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { - var emitLeadingSpace = !trailingSeparator; - ts.forEach(comments, function (comment) { - if (emitLeadingSpace) { - writer.write(" "); - emitLeadingSpace = false; - } - writeComment(currentSourceFile, writer, comment, newLine); - if (comment.hasTrailingNewLine) { - writer.writeLine(); - } - else if (trailingSeparator) { - writer.write(" "); - } - else { - emitLeadingSpace = true; - } - }); - } - function writeCommentRange(currentSourceFile, writer, comment, newLine) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); - var firstCommentLineIndent; - for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); - if (pos !== comment.pos) { - if (firstCommentLineIndent === undefined) { - firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); - } - var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); - var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); - if (spacesToEmit > 0) { - var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); - writer.rawWrite(indentSizeSpaceString); - while (numberOfSingleSpacesToEmit) { - writer.rawWrite(" "); - numberOfSingleSpacesToEmit--; - } - } - else { - writer.rawWrite(""); - } - } - writeTrimmedCurrentLine(pos, nextLineStart); - pos = nextLineStart; - } - } - else { - writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); - } - function writeTrimmedCurrentLine(pos, nextLineStart) { - var end = Math.min(comment.end, nextLineStart - 1); - var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); - if (currentLineText) { - writer.write(currentLineText); - if (end !== comment.end) { - writer.writeLine(); - } - } - else { - writer.writeLiteral(newLine); - } - } - function calculateIndent(pos, end) { - var currentLineIndent = 0; - for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { - if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { - currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); - } - else { - currentLineIndent++; - } - } - return currentLineIndent; - } - } - function getFirstConstructorWithBody(node) { - return ts.forEach(node.members, function (member) { - if (member.kind === 129 /* Constructor */ && member.body) { - return member; - } - }); - } - function getAllAccessorDeclarations(node, accessor) { - var firstAccessor; - var getAccessor; - var setAccessor; - if (accessor.name.kind === 122 /* ComputedPropertyName */) { - firstAccessor = accessor; - if (accessor.kind === 130 /* GetAccessor */) { - getAccessor = accessor; - } - else if (accessor.kind === 131 /* SetAccessor */) { - setAccessor = accessor; - } - else { - ts.Debug.fail("Accessor has wrong kind"); - } - } - else { - ts.forEach(node.members, function (member) { - if ((member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) && member.name.text === accessor.name.text && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { - if (!firstAccessor) { - firstAccessor = member; - } - if (member.kind === 130 /* GetAccessor */ && !getAccessor) { - getAccessor = member; - } - if (member.kind === 131 /* SetAccessor */ && !setAccessor) { - setAccessor = member; - } - } - }); - } - return { - firstAccessor: firstAccessor, - getAccessor: getAccessor, - setAccessor: setAccessor - }; - } - function getSourceFilePathInNewDir(sourceFile, program, newDirPath) { - var compilerHost = program.getCompilerHost(); - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, compilerHost.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), ""); - return ts.combinePaths(newDirPath, sourceFilePath); - } - function getOwnEmitOutputFilePath(sourceFile, program, extension) { - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outDir) { - var emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, program, compilerOptions.outDir)); - } - else { - var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.filename); - } - return emitOutputFilePathWithoutExtension + extension; - } - function writeFile(compilerHost, diagnostics, filename, data, writeByteOrderMark) { - compilerHost.writeFile(filename, data, writeByteOrderMark, function (hostErrorMessage) { - diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); - }); - } - function emitDeclarations(program, resolver, diagnostics, jsFilePath, root) { - var newLine = program.getCompilerHost().getNewLine(); - var compilerOptions = program.getCompilerOptions(); - var compilerHost = program.getCompilerHost(); - var write; - var writeLine; - var increaseIndent; - var decreaseIndent; - var writeTextOfNode; - var writer = createAndSetNewTextWriterWithSymbolWriter(); - var enclosingDeclaration; - var currentSourceFile; - var reportedDeclarationError = false; - var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { - } : writeJsDocComments; - var aliasDeclarationEmitInfo = []; - function createAndSetNewTextWriterWithSymbolWriter() { - var writer = createTextWriter(newLine); - writer.trackSymbol = trackSymbol; - writer.writeKeyword = writer.write; - writer.writeOperator = writer.write; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - return writer; - } - function setWriter(newWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - function writeAsychronousImportDeclarations(importDeclarations) { - var oldWriter = writer; - ts.forEach(importDeclarations, function (aliasToWrite) { - var aliasEmitInfo = ts.forEach(aliasDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined; }); - if (aliasEmitInfo) { - createAndSetNewTextWriterWithSymbolWriter(); - for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - writeImportDeclaration(aliasToWrite); - aliasEmitInfo.asynchronousOutput = writer.getText(); - } - }); - setWriter(oldWriter); - } - function handleSymbolAccessibilityError(symbolAccesibilityResult) { - if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { - if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { - writeAsychronousImportDeclarations(symbolAccesibilityResult.aliasesToMakeVisible); - } - } - else { - reportedDeclarationError = true; - var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); - } - else { - diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); - } - } - } - } - function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); - } - function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (type) { - emitType(type); - } - else { - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); - } - } - function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - emitType(signature.type); - } - else { - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); - } - } - function emitLines(nodes) { - for (var i = 0, n = nodes.length; i < n; i++) { - emitNode(nodes[i]); - } - } - function emitSeparatedList(nodes, separator, eachNodeEmitFn) { - var currentWriterPos = writer.getTextPos(); - for (var i = 0, n = nodes.length; i < n; i++) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(nodes[i]); - } - } - function emitCommaList(nodes, eachNodeEmitFn) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn); - } - function writeJsDocComments(declaration) { - if (declaration) { - var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); - emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); - emitComments(currentSourceFile, writer, jsDocComments, true, newLine, writeCommentRange); - } - } - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - function emitType(type) { - switch (type.kind) { - case 110 /* AnyKeyword */: - case 119 /* StringKeyword */: - case 117 /* NumberKeyword */: - case 111 /* BooleanKeyword */: - case 98 /* VoidKeyword */: - case 8 /* StringLiteral */: - return writeTextOfNode(currentSourceFile, type); - case 135 /* TypeReference */: - return emitTypeReference(type); - case 138 /* TypeQuery */: - return emitTypeQuery(type); - case 140 /* ArrayType */: - return emitArrayType(type); - case 141 /* TupleType */: - return emitTupleType(type); - case 142 /* UnionType */: - return emitUnionType(type); - case 143 /* ParenthesizedType */: - return emitParenType(type); - case 136 /* FunctionType */: - case 137 /* ConstructorType */: - return emitSignatureDeclarationWithJsDocComments(type); - case 139 /* TypeLiteral */: - return emitTypeLiteral(type); - case 64 /* Identifier */: - return emitEntityName(type); - case 121 /* QualifiedName */: - return emitEntityName(type); - default: - ts.Debug.fail("Unknown type annotation: " + type.kind); - } - function emitEntityName(entityName) { - var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 197 /* ImportDeclaration */ ? entityName.parent : enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - writeEntityName(entityName); - function writeEntityName(entityName) { - if (entityName.kind === 64 /* Identifier */) { - writeTextOfNode(currentSourceFile, entityName); - } - else { - var qualifiedName = entityName; - writeEntityName(qualifiedName.left); - write("."); - writeTextOfNode(currentSourceFile, qualifiedName.right); - } - } - } - function emitTypeReference(type) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - function emitTypeQuery(type) { - write("typeof "); - emitEntityName(type.exprName); - } - function emitArrayType(type) { - emitType(type.elementType); - write("[]"); - } - function emitTupleType(type) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - function emitUnionType(type) { - emitSeparatedList(type.types, " | ", emitType); - } - function emitParenType(type) { - write("("); - emitType(type.type); - write(")"); - } - function emitTypeLiteral(type) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - function emitSourceFile(node) { - currentSourceFile = node; - enclosingDeclaration = node; - emitLines(node.statements); - } - function emitExportAssignment(node) { - write("export = "); - writeTextOfNode(currentSourceFile, node.exportName); - write(";"); - writeLine(); - } - function emitModuleElementDeclarationFlags(node) { - if (node.parent === currentSourceFile) { - if (node.flags & 1 /* Export */) { - write("export "); - } - if (node.kind !== 192 /* InterfaceDeclaration */) { - write("declare "); - } - } - } - function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32 /* Private */) { - write("private "); - } - else if (node.flags & 64 /* Protected */) { - write("protected "); - } - if (node.flags & 128 /* Static */) { - write("static "); - } - } - function emitImportDeclaration(node) { - var nodeEmitInfo = { - declaration: node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - hasWritten: resolver.isDeclarationVisible(node) - }; - aliasDeclarationEmitInfo.push(nodeEmitInfo); - if (nodeEmitInfo.hasWritten) { - writeImportDeclaration(node); - } - } - function writeImportDeclaration(node) { - emitJsDocComments(node); - if (node.flags & 1 /* Export */) { - write("export "); - } - write("import "); - writeTextOfNode(currentSourceFile, node.name); - write(" = "); - if (ts.isInternalModuleImportDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - writeTextOfNode(currentSourceFile, ts.getExternalModuleImportDeclarationExpression(node)); - write(");"); - } - writer.writeLine(); - function getImportEntityNameVisibilityError(symbolAccesibilityResult) { - return { - diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - function emitModuleDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("module "); - writeTextOfNode(currentSourceFile, node.name); - while (node.body.kind !== 196 /* ModuleBlock */) { - node = node.body; - write("."); - writeTextOfNode(currentSourceFile, node.name); - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.body.statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitTypeAliasDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentSourceFile, node.name); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - } - function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { - return { - diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - function emitEnumDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentSourceFile, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - } - function emitEnumMemberDeclaration(node) { - emitJsDocComments(node); - writeTextOfNode(currentSourceFile, node.name); - var enumMemberValue = resolver.getEnumMemberValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(enumMemberValue.toString()); - } - write(","); - writeLine(); - } - function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 128 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); - } - function emitTypeParameters(typeParameters) { - function emitTypeParameter(node) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentSourceFile, node.name); - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || (node.parent.parent && node.parent.parent.kind === 139 /* TypeLiteral */)) { - ts.Debug.assert(node.parent.kind === 128 /* MethodDeclaration */ || node.parent.kind === 127 /* MethodSignature */ || node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.kind === 132 /* CallSignature */ || node.parent.kind === 133 /* ConstructSignature */); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.parent.kind) { - case 191 /* ClassDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - case 192 /* InterfaceDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - case 133 /* ConstructSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 132 /* CallSignature */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - function emitHeritageClause(typeReferences, isImplementsList) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - function emitTypeOfTypeReference(node) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - function getHeritageClauseVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.parent.parent.name - }; - } - } - } - function emitClassDeclaration(node) { - function emitParameterProperties(constructorDeclaration) { - if (constructorDeclaration) { - ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { - emitPropertyDeclaration(param); - } - }); - } - } - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("class "); - writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - var baseTypeNode = ts.getClassBaseTypeNode(node); - if (baseTypeNode) { - emitHeritageClause([baseTypeNode], false); - } - emitHeritageClause(ts.getClassImplementedTypeNodes(node), true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitInterfaceDeclaration(node) { - if (resolver.isDeclarationVisible(node)) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentSourceFile, node.name); - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - } - function emitPropertyDeclaration(node) { - emitJsDocComments(node); - emitClassMemberDeclarationFlags(node); - emitVariableDeclaration(node); - write(";"); - writeLine(); - } - function emitVariableDeclaration(node) { - if (node.kind !== 189 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { - writeTextOfNode(currentSourceFile, node.name); - if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && ts.hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && node.parent.kind === 139 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!(node.flags & 32 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (node.kind === 189 /* VariableDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } - else if (node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) { - if (node.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - return diagnosticMessage !== undefined ? { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - } - function emitTypeOfVariableDeclarationFromTypeLiteral(node) { - if (node.type) { - write(": "); - emitType(node.type); - } - } - function emitVariableStatement(node) { - var hasDeclarationWithEmit = ts.forEach(node.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); - if (hasDeclarationWithEmit) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (ts.isLet(node)) { - write("let "); - } - else if (ts.isConst(node)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarations, emitVariableDeclaration); - write(";"); - writeLine(); - } - } - function emitAccessorDeclaration(node) { - var accessors = getAllAccessorDeclarations(node.parent, node); - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(node); - writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32 /* Private */)) { - var accessorWithTypeAnnotation = node; - var type = getTypeAnnotationFromAccessor(node); - if (!type) { - var anotherAccessor = node.kind === 130 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - function getTypeAnnotationFromAccessor(accessor) { - if (accessor) { - return accessor.kind === 130 /* GetAccessor */ ? accessor.type : accessor.parameters[0].type; - } - } - function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - if (accessorWithTypeAnnotation.kind === 131 /* SetAccessor */) { - if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.parameters[0], - typeName: accessorWithTypeAnnotation.name - }; - } - else { - if (accessorWithTypeAnnotation.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: undefined - }; - } - } - } - function emitFunctionDeclaration(node) { - if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === 190 /* FunctionDeclaration */) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === 128 /* MethodDeclaration */) { - emitClassMemberDeclarationFlags(node); - } - if (node.kind === 190 /* FunctionDeclaration */) { - write("function "); - writeTextOfNode(currentSourceFile, node.name); - } - else if (node.kind === 129 /* Constructor */) { - write("constructor"); - } - else { - writeTextOfNode(currentSourceFile, node.name); - if (ts.hasQuestionToken(node)) { - write("?"); - } - } - emitSignatureDeclaration(node); - } - } - function emitSignatureDeclarationWithJsDocComments(node) { - emitJsDocComments(node); - emitSignatureDeclaration(node); - } - function emitSignatureDeclaration(node) { - if (node.kind === 133 /* ConstructSignature */ || node.kind === 137 /* ConstructorType */) { - write("new "); - } - emitTypeParameters(node.typeParameters); - if (node.kind === 134 /* IndexSignature */) { - write("["); - } - else { - write("("); - } - var prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitCommaList(node.parameters, emitParameterDeclaration); - if (node.kind === 134 /* IndexSignature */) { - write("]"); - } - else { - write(")"); - } - var isFunctionTypeOrConstructorType = node.kind === 136 /* FunctionType */ || node.kind === 137 /* ConstructorType */; - if (isFunctionTypeOrConstructorType || node.parent.kind === 139 /* TypeLiteral */) { - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== 129 /* Constructor */ && !(node.flags & 32 /* Private */)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - enclosingDeclaration = prevEnclosingDeclaration; - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - function getReturnTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.kind) { - case 133 /* ConstructSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 132 /* CallSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 134 /* IndexSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - } - else if (node.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; - break; - default: - ts.Debug.fail("This is unknown kind for signature: " + node.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node.name || node - }; - } - } - function emitParameterDeclaration(node) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - write("_" + ts.indexOf(node.parent.parameters, node)); - } - else { - writeTextOfNode(currentSourceFile, node.name); - } - if (node.initializer || ts.hasQuestionToken(node)) { - write("?"); - } - decreaseIndent(); - if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.parent.kind === 139 /* TypeLiteral */) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!(node.parent.flags & 32 /* Private */)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { - var diagnosticMessage; - switch (node.parent.kind) { - case 129 /* Constructor */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - break; - case 133 /* ConstructSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 132 /* CallSignature */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - case 190 /* FunctionDeclaration */: - diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - default: - ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - return { - diagnosticMessage: diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - function emitNode(node) { - switch (node.kind) { - case 129 /* Constructor */: - case 190 /* FunctionDeclaration */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - return emitFunctionDeclaration(node); - case 133 /* ConstructSignature */: - case 132 /* CallSignature */: - case 134 /* IndexSignature */: - return emitSignatureDeclarationWithJsDocComments(node); - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return emitAccessorDeclaration(node); - case 170 /* VariableStatement */: - return emitVariableStatement(node); - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - return emitPropertyDeclaration(node); - case 192 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 191 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 193 /* TypeAliasDeclaration */: - return emitTypeAliasDeclaration(node); - case 206 /* EnumMember */: - return emitEnumMemberDeclaration(node); - case 194 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 195 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 197 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 198 /* ExportAssignment */: - return emitExportAssignment(node); - case 207 /* SourceFile */: - return emitSourceFile(node); - } - } - var referencePathsOutput = ""; - function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 1024 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile, compilerOptions) ? getOwnEmitOutputFilePath(referencedFile, program, ".d.ts") : ts.removeFileExtension(compilerOptions.out) + ".d.ts"; - declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, false); - referencePathsOutput += "/// " + newLine; - } - if (root) { - if (!compilerOptions.noResolve) { - var addedGlobalFileReference = false; - ts.forEach(root.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(program, root, fileReference); - if (referencedFile && ((referencedFile.flags & 1024 /* DeclarationFile */) || shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { - writeReferencePath(referencedFile); - if (!isExternalModuleOrDeclarationFile(referencedFile)) { - addedGlobalFileReference = true; - } - } - }); - } - emitNode(root); - } - else { - var emittedReferencedFiles = []; - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - if (!compilerOptions.noResolve) { - ts.forEach(sourceFile.referencedFiles, function (fileReference) { - var referencedFile = ts.tryResolveScriptReference(program, sourceFile, fileReference); - if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && !ts.contains(emittedReferencedFiles, referencedFile))) { - writeReferencePath(referencedFile); - emittedReferencedFiles.push(referencedFile); - } - }); - } - emitNode(sourceFile); - } - }); - } - return { - reportedDeclarationError: reportedDeclarationError, - aliasDeclarationEmitInfo: aliasDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencePathsOutput: referencePathsOutput - }; - } - function getDeclarationDiagnostics(program, resolver, targetSourceFile) { - var diagnostics = []; - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); - emitDeclarations(program, resolver, diagnostics, jsFilePath, targetSourceFile); - return diagnostics; - } - ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitFiles(resolver, targetSourceFile) { - var program = resolver.getProgram(); - var compilerHost = program.getCompilerHost(); - var compilerOptions = program.getCompilerOptions(); - var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; - var diagnostics = []; - var newLine = program.getCompilerHost().getNewLine(); - function emitJavaScript(jsFilePath, root) { - var writer = createTextWriter(newLine); - var write = writer.write; - var writeTextOfNode = writer.writeTextOfNode; - var writeLine = writer.writeLine; - var increaseIndent = writer.increaseIndent; - var decreaseIndent = writer.decreaseIndent; - var currentSourceFile; - var extendsEmitted = false; - var tempCount = 0; - var tempVariables; - var tempParameters; - var writeEmittedFiles = writeJavaScriptFile; - var emitLeadingComments = compilerOptions.removeComments ? function (node) { - } : emitLeadingDeclarationComments; - var emitTrailingComments = compilerOptions.removeComments ? function (node) { - } : emitTrailingDeclarationComments; - var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { - } : emitLeadingCommentsOfLocalPosition; - var detachedCommentsInfo; - var emitDetachedComments = compilerOptions.removeComments ? function (node) { - } : emitDetachedCommentsAtPosition; - var emitPinnedOrTripleSlashComments = compilerOptions.removeComments ? function (node) { - } : emitPinnedOrTripleSlashCommentsOfNode; - var writeComment = writeCommentRange; - var emit = emitNode; - var emitStart = function (node) { - }; - var emitEnd = function (node) { - }; - var emitToken = emitTokenText; - var scopeEmitStart = function (scopeDeclaration, scopeName) { - }; - var scopeEmitEnd = function () { - }; - var sourceMapData; - function initializeEmitterWithSourceMaps() { - var sourceMapDir; - var sourceMapSourceIndex = -1; - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; - } - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - var encodedStr = ""; - do { - var currentDigit = inValue & 31; - inValue = inValue >> 5; - if (inValue > 0) { - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } - } - function recordSourceMapSpan(pos) { - var sourceLinePos = currentSourceFile.getLineAndCharacterFromPosition(pos); - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine != emittedLine || lastRecordedSourceMapSpan.emittedColumn != emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - encodeLastRecordedSourceMapSpan(); - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - var sourcesDirectoryPath = compilerOptions.sourceRoot ? program.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - sourceMapData.inputSourceFileNames.push(node.filename); - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - recordScopeNameStart(scopeName); - } - else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { - if (node.name) { - scopeName = node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings) { - if (typeof JSON !== "undefined") { - return JSON.stringify({ - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\"}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - encodeLastRecordedSourceMapSpan(); - writeFile(compilerHost, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings), false); - sourceMapDataList.push(sourceMapData); - writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL, writeByteOrderMark); - } - var sourceMapJsFile = ts.getBaseFilename(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapDecodedMappings: [] - }; - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - sourceMapDir = ts.getDirectoryPath(getSourceFilePathInNewDir(root, program, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - sourceMapDir = ts.combinePaths(program.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), compilerHost.getCurrentDirectory(), compilerHost.getCanonicalFileName, true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithMap(node) { - if (node) { - if (node.kind != 207 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNode(node); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNode(node); - } - } - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithMap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - writeFile(compilerHost, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); - } - function createTempVariable(location, forLoopVariable) { - var name = forLoopVariable ? "_i" : undefined; - while (true) { - if (name && resolver.isUnknownIdentifier(location, name)) { - break; - } - name = "_" + (tempCount < 25 ? String.fromCharCode(tempCount + (tempCount < 8 ? 0 : 1) + 97 /* a */) : tempCount - 25); - tempCount++; - } - var result = ts.createNode(64 /* Identifier */); - result.text = name; - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitTokenText(tokenKind, startPos, emitFn) { - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - return startPos + tokenString.length; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } - function emitCommaList(nodes, count) { - if (!(count >= 0)) { - count = nodes.length; - } - if (nodes) { - for (var i = 0; i < count; i++) { - if (i) { - write(", "); - } - emit(nodes[i]); - } - } - } - function emitMultiLineList(nodes) { - if (nodes) { - for (var i = 0; i < nodes.length; i++) { - if (i) { - write(","); - } - writeLine(); - emit(nodes[i]); - } - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(text) { - if (text.length <= 0) { - return false; - } - if (text.charCodeAt(1) === 66 /* B */ || text.charCodeAt(1) === 98 /* b */ || text.charCodeAt(1) === 79 /* O */ || text.charCodeAt(1) === 111 /* o */) { - return true; - } - return false; - } - function emitLiteral(node) { - var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; - if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { - write(node.text); - } - else { - write(text); - } - } - function getTemplateLiteralAsStringLiteral(node) { - return '"' + ts.escapeString(node.text) + '"'; - } - function emitTemplateExpression(node) { - if (compilerOptions.target >= 2 /* ES6 */) { - ts.forEachChild(node, emit); - return; - } - ts.Debug.assert(node.parent.kind !== 153 /* TaggedTemplateExpression */); - var emitOuterParens = ts.isExpression(node.parent) && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - emitLiteral(node.head); - ts.forEach(node.templateSpans, function (templateSpan) { - var needsParens = templateSpan.expression.kind !== 155 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; - write(" + "); - if (needsParens) { - write("("); - } - emit(templateSpan.expression); - if (needsParens) { - write(")"); - } - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - }); - if (emitOuterParens) { - write(")"); - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 151 /* CallExpression */: - case 152 /* NewExpression */: - return parent.expression === template; - case 155 /* ParenthesizedExpression */: - return false; - case 153 /* TaggedTemplateExpression */: - ts.Debug.fail("Path should be unreachable; tagged templates not supported pre-ES6."); - default: - return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; - } - } - function comparePrecedenceToBinaryPlus(expression) { - ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); - switch (expression.kind) { - case 163 /* BinaryExpression */: - switch (expression.operator) { - case 35 /* AsteriskToken */: - case 36 /* SlashToken */: - case 37 /* PercentToken */: - return 1 /* GreaterThan */; - case 33 /* PlusToken */: - return 0 /* EqualTo */; - default: - return -1 /* LessThan */; - } - case 164 /* ConditionalExpression */: - return -1 /* LessThan */; - default: - return 1 /* GreaterThan */; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - function emitExpressionForPropertyName(node) { - if (node.kind === 8 /* StringLiteral */) { - emitLiteral(node); - } - else if (node.kind === 122 /* ComputedPropertyName */) { - emit(node.expression); - } - else { - write("\""); - if (node.kind === 7 /* NumericLiteral */) { - write(node.text); - } - else { - writeTextOfNode(currentSourceFile, node); - } - write("\""); - } - } - function isNotExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 124 /* Parameter */: - case 189 /* VariableDeclaration */: - case 146 /* BindingElement */: - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - case 204 /* PropertyAssignment */: - case 205 /* ShorthandPropertyAssignment */: - case 206 /* EnumMember */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - case 190 /* FunctionDeclaration */: - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - case 156 /* FunctionExpression */: - case 191 /* ClassDeclaration */: - case 192 /* InterfaceDeclaration */: - case 194 /* EnumDeclaration */: - case 195 /* ModuleDeclaration */: - case 197 /* ImportDeclaration */: - return parent.name === node; - case 179 /* BreakStatement */: - case 178 /* ContinueStatement */: - case 198 /* ExportAssignment */: - return false; - case 183 /* LabeledStatement */: - return node.parent.label === node; - case 203 /* CatchClause */: - return node.parent.name === node; - } - } - function emitExpressionIdentifier(node) { - var prefix = resolver.getExpressionNamePrefix(node); - if (prefix) { - write(prefix); - write("."); - } - writeTextOfNode(currentSourceFile, node); - } - function emitIdentifier(node) { - if (!node.parent) { - write(node.text); - } - else if (!isNotExpressionIdentifier(node)) { - emitExpressionIdentifier(node); - } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { - write("_this"); - } - else { - write("this"); - } - } - function emitSuper(node) { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 16 /* SuperInstance */) { - write("_super.prototype"); - } - else if (flags & 32 /* SuperStatic */) { - write("_super"); - } - else { - write("super"); - } - } - function emitObjectBindingPattern(node) { - write("{ "); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write("]"); - } - function emitArrayLiteral(node) { - if (node.flags & 256 /* MultiLine */) { - write("["); - increaseIndent(); - emitMultiLineList(node.elements); - emitTrailingCommaIfPresent(node.elements); - decreaseIndent(); - writeLine(); - write("]"); - } - else { - write("["); - emitCommaList(node.elements); - emitTrailingCommaIfPresent(node.elements); - write("]"); - } - } - function emitObjectLiteral(node) { - if (!node.properties.length) { - write("{}"); - } - else if (node.flags & 256 /* MultiLine */) { - write("{"); - increaseIndent(); - emitMultiLineList(node.properties); - if (compilerOptions.target >= 1 /* ES5 */) { - emitTrailingCommaIfPresent(node.properties); - } - decreaseIndent(); - writeLine(); - write("}"); - } - else { - write("{ "); - emitCommaList(node.properties); - if (compilerOptions.target >= 1 /* ES5 */) { - emitTrailingCommaIfPresent(node.properties); - } - write(" }"); - } - } - function emitComputedPropertyName(node) { - write("["); - emit(node.expression); - write("]"); - } - function emitMethod(node) { - if (!ts.isObjectLiteralMethod(node)) { - return; - } - emitLeadingComments(node); - emit(node.name); - if (compilerOptions.target < 2 /* ES6 */) { - write(": function "); - } - emitSignatureAndBody(node); - emitTrailingComments(node); - } - function emitPropertyAssignment(node) { - emitLeadingComments(node); - emit(node.name); - write(": "); - emit(node.initializer); - emitTrailingComments(node); - } - function emitShorthandPropertyAssignment(node) { - emitLeadingComments(node); - emit(node.name); - if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { - write(": "); - emitExpressionIdentifier(node.name); - } - emitTrailingComments(node); - } - function tryEmitConstantValue(node) { - var constantValue = resolver.getConstantValue(node); - if (constantValue !== undefined) { - var propertyName = node.kind === 149 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(constantValue.toString() + " /* " + propertyName + " */"); - return true; - } - return false; - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - write("."); - emit(node.name); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function emitCallExpression(node) { - var superCall = false; - if (node.expression.kind === 90 /* SuperKeyword */) { - write("_super"); - superCall = true; - } - else { - emit(node.expression); - superCall = node.expression.kind === 149 /* PropertyAccessExpression */ && node.expression.expression.kind === 90 /* SuperKeyword */; - } - if (superCall) { - write(".call("); - emitThis(node.expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitTaggedTemplateExpression(node) { - ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); - emit(node.tag); - write(" "); - emit(node.template); - } - function emitParenExpression(node) { - if (node.expression.kind === 154 /* TypeAssertionExpression */) { - var operand = node.expression.expression; - while (operand.kind == 154 /* TypeAssertionExpression */) { - operand = operand.expression; - } - if (operand.kind !== 161 /* PrefixUnaryExpression */ && operand.kind !== 160 /* VoidExpression */ && operand.kind !== 159 /* TypeOfExpression */ && operand.kind !== 158 /* DeleteExpression */ && operand.kind !== 162 /* PostfixUnaryExpression */ && operand.kind !== 152 /* NewExpression */ && !(operand.kind === 151 /* CallExpression */ && node.parent.kind === 152 /* NewExpression */) && !(operand.kind === 156 /* FunctionExpression */ && node.parent.kind === 151 /* CallExpression */)) { - emit(operand); - return; - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(73 /* DeleteKeyword */)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(98 /* VoidKeyword */)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(96 /* TypeOfKeyword */)); - write(" "); - emit(node.expression); - } - function emitPrefixUnaryExpression(node) { - write(ts.tokenToString(node.operator)); - if (node.operand.kind === 161 /* PrefixUnaryExpression */) { - var operand = node.operand; - if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { - write(" "); - } - else if (node.operator === 34 /* MinusToken */ && (operand.operator === 34 /* MinusToken */ || operand.operator === 39 /* MinusMinusToken */)) { - write(" "); - } - } - emit(node.operand); - } - function emitPostfixUnaryExpression(node) { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - function emitBinaryExpression(node) { - if (node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { - emitDestructuring(node); - } - else { - emit(node.left); - if (node.operator !== 23 /* CommaToken */) - write(" "); - write(ts.tokenToString(node.operator)); - write(" "); - emit(node.right); - } - } - function emitConditionalExpression(node) { - emit(node.condition); - write(" ? "); - emit(node.whenTrue); - write(" : "); - emit(node.whenFalse); - } - function emitBlock(node) { - emitToken(14 /* OpenBraceToken */, node.pos); - increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 196 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 195 /* ModuleDeclaration */); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 196 /* ModuleBlock */) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); - } - function emitEmbeddedStatement(node) { - if (node.kind === 169 /* Block */) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - var isArrowExpression = node.expression.kind === 157 /* ArrowFunction */; - emitLeadingComments(node); - if (isArrowExpression) - write("("); - emit(node.expression); - if (isArrowExpression) - write(")"); - write(";"); - emitTrailingComments(node); - } - function emitIfStatement(node) { - emitLeadingComments(node); - var endPos = emitToken(83 /* IfKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(75 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 173 /* IfStatement */) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - emitTrailingComments(node); - } - function emitDoStatement(node) { - write("do"); - emitEmbeddedStatement(node.statement); - if (node.statement.kind === 169 /* Block */) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - write("while ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitForStatement(node) { - var endPos = emitToken(81 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.declarations) { - if (node.declarations[0] && ts.isLet(node.declarations[0])) { - emitToken(103 /* LetKeyword */, endPos); - } - else if (node.declarations[0] && ts.isConst(node.declarations[0])) { - emitToken(69 /* ConstKeyword */, endPos); - } - else { - emitToken(97 /* VarKeyword */, endPos); - } - write(" "); - emitCommaList(node.declarations); - } - if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.iterator); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitForInStatement(node) { - var endPos = emitToken(81 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; - if (ts.isLet(decl)) { - emitToken(103 /* LetKeyword */, endPos); - } - else { - emitToken(97 /* VarKeyword */, endPos); - } - write(" "); - emit(decl); - } - } - else { - emit(node.variable); - } - write(" in "); - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.statement); - } - function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 179 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - emitLeadingComments(node); - emitToken(89 /* ReturnKeyword */, node.pos); - emitOptional(" ", node.expression); - write(";"); - emitTrailingComments(node); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(91 /* SwitchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - endPos = emitToken(17 /* CloseParenToken */, node.expression.end); - write(" "); - emitToken(14 /* OpenBraceToken */, endPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.clauses.end); - } - function isOnSameLine(node1, node2) { - return getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 200 /* CaseClause */) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && isOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(67 /* CatchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.name); - emitToken(17 /* CloseParenToken */, node.name.end); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(71 /* DebuggerKeyword */, node.pos); - write(";"); - } - function emitLabelledStatement(node) { - emit(node.label); - write(": "); - emit(node.statement); - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 195 /* ModuleDeclaration */); - return node; - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (node.flags & 1 /* Export */) { - var container = getContainingModule(node); - write(container ? resolver.getLocalNameOfContainer(container) : "exports"); - write("."); - } - emitNode(node.name); - emitEnd(node.name); - } - function emitDestructuring(root, value) { - var emitCount = 0; - var isDeclaration = (root.kind === 189 /* VariableDeclaration */ && !(root.flags & 1 /* Export */)) || root.kind === 124 /* Parameter */; - if (root.kind === 163 /* BinaryExpression */) { - emitAssignmentExpression(root); - } - else { - emitBindingElement(root, value); - } - function emitAssignment(name, value) { - if (emitCount++) { - write(", "); - } - if (name.parent && (name.parent.kind === 189 /* VariableDeclaration */ || name.parent.kind === 146 /* BindingElement */)) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - } - function ensureIdentifier(expr) { - if (expr.kind !== 64 /* Identifier */) { - var identifier = createTempVariable(root); - if (!isDeclaration) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expr); - expr = identifier; - } - return expr; - } - function createVoidZero() { - var zero = ts.createNode(7 /* NumericLiteral */); - zero.text = "0"; - var result = ts.createNode(160 /* VoidExpression */); - result.expression = zero; - return result; - } - function createDefaultValueCheck(value, defaultValue) { - value = ensureIdentifier(value); - var equals = ts.createNode(163 /* BinaryExpression */); - equals.left = value; - equals.operator = 30 /* EqualsEqualsEqualsToken */; - equals.right = createVoidZero(); - var cond = ts.createNode(164 /* ConditionalExpression */); - cond.condition = equals; - cond.whenTrue = defaultValue; - cond.whenFalse = value; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createNode(7 /* NumericLiteral */); - node.text = "" + value; - return node; - } - function parenthesizeForAccess(expr) { - if (expr.kind === 64 /* Identifier */ || expr.kind === 149 /* PropertyAccessExpression */ || expr.kind === 150 /* ElementAccessExpression */) { - return expr; - } - var node = ts.createNode(155 /* ParenthesizedExpression */); - node.expression = expr; - return node; - } - function createPropertyAccess(object, propName) { - if (propName.kind !== 64 /* Identifier */) { - return createElementAccess(object, propName); - } - var node = ts.createNode(149 /* PropertyAccessExpression */); - node.expression = parenthesizeForAccess(object); - node.name = propName; - return node; - } - function createElementAccess(object, index) { - var node = ts.createNode(150 /* ElementAccessExpression */); - node.expression = parenthesizeForAccess(object); - node.argumentExpression = index; - return node; - } - function emitObjectLiteralAssignment(target, value) { - var properties = target.properties; - if (properties.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < properties.length; i++) { - var p = properties[i]; - if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { - var propName = (p.name); - emitDestructuringAssignment(p.initializer || propName, createPropertyAccess(value, propName)); - } - } - } - function emitArrayLiteralAssignment(target, value) { - var elements = target.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 167 /* OmittedExpression */) { - emitDestructuringAssignment(e, createElementAccess(value, createNumericLiteral(i))); - } - } - } - function emitDestructuringAssignment(target, value) { - if (target.kind === 163 /* BinaryExpression */ && target.operator === 52 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); - target = target.left; - } - if (target.kind === 148 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); - } - else if (target.kind === 147 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); - } - else { - emitAssignment(target, value); - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (root.parent.kind === 172 /* ExpressionStatement */) { - emitDestructuringAssignment(target, value); - } - else { - if (root.parent.kind !== 155 /* ParenthesizedExpression */) { - write("("); - } - value = ensureIdentifier(value); - emitDestructuringAssignment(target, value); - write(", "); - emit(value); - if (root.parent.kind !== 155 /* ParenthesizedExpression */) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; - } - else if (!value) { - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - if (elements.length !== 1) { - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if (pattern.kind === 144 /* ObjectBindingPattern */) { - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccess(value, propName)); - } - else if (element.kind !== 167 /* OmittedExpression */) { - emitBindingElement(element, createElementAccess(value, createNumericLiteral(i))); - } - } - } - else { - emitAssignment(target.name, value); - } - } - } - function emitVariableDeclaration(node) { - emitLeadingComments(node); - if (ts.isBindingPattern(node.name)) { - emitDestructuring(node); - } - else { - emitModuleMemberName(node); - emitOptional(" = ", node.initializer); - } - emitTrailingComments(node); - } - function emitVariableStatement(node) { - emitLeadingComments(node); - if (!(node.flags & 1 /* Export */)) { - if (ts.isLet(node)) { - write("let "); - } - else if (ts.isConst(node)) { - write("const "); - } - else { - write("var "); - } - } - emitCommaList(node.declarations); - write(";"); - emitTrailingComments(node); - } - function emitParameter(node) { - emitLeadingComments(node); - if (ts.isBindingPattern(node.name)) { - var name = createTempVariable(node); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name); - emit(name); - } - else { - emit(node.name); - } - emitTrailingComments(node); - } - function emitDefaultValueAssignments(node) { - var tempIndex = 0; - ts.forEach(node.parameters, function (p) { - if (ts.isBindingPattern(p.name)) { - writeLine(); - write("var "); - emitDestructuring(p, tempParameters[tempIndex]); - write(";"); - tempIndex++; - } - else if (p.initializer) { - writeLine(); - emitStart(p); - write("if ("); - emitNode(p.name); - write(" === void 0)"); - emitEnd(p); - write(" { "); - emitStart(p); - emitNode(p.name); - write(" = "); - emitNode(p.initializer); - emitEnd(p); - write("; }"); - } - }); - } - function emitRestParameter(node) { - if (ts.hasRestParameters(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - var tempName = createTempVariable(node, true).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNode(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNode(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - emitLeadingComments(node); - write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); - emit(node.name); - emitSignatureAndBody(node); - emitTrailingComments(node); - } - function emitFunctionDeclaration(node) { - if (!node.body) { - return emitPinnedOrTripleSlashComments(node); - } - if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { - emitLeadingComments(node); - } - write("function "); - if (node.kind === 190 /* FunctionDeclaration */ || (node.kind === 156 /* FunctionExpression */ && node.name)) { - emit(node.name); - } - emitSignatureAndBody(node); - if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - emitCommaList(node.parameters, node.parameters.length - (ts.hasRestParameters(node) ? 1 : 0)); - } - write(")"); - decreaseIndent(); - } - function emitSignatureAndBody(node) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempCount = 0; - tempVariables = undefined; - tempParameters = undefined; - emitSignatureParameters(node); - write(" {"); - scopeEmitStart(node); - increaseIndent(); - emitDetachedComments(node.body.kind === 169 /* Block */ ? node.body.statements : node.body); - var startIndex = 0; - if (node.body.kind === 169 /* Block */) { - startIndex = emitDirectivePrologues(node.body.statements, true); - } - var outPos = writer.getTextPos(); - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - if (node.body.kind !== 169 /* Block */ && outPos === writer.getTextPos()) { - decreaseIndent(); - write(" "); - emitStart(node.body); - write("return "); - emitNode(node.body); - emitEnd(node.body); - write(";"); - emitTempDeclarations(false); - write(" "); - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - else { - if (node.body.kind === 169 /* Block */) { - emitLinesStartingAt(node.body.statements, startIndex); - } - else { - writeLine(); - emitLeadingComments(node.body); - write("return "); - emit(node.body); - write(";"); - emitTrailingComments(node.body); - } - emitTempDeclarations(true); - writeLine(); - if (node.body.kind === 169 /* Block */) { - emitLeadingCommentsOfPosition(node.body.statements.end); - decreaseIndent(); - emitToken(15 /* CloseBraceToken */, node.body.statements.end); - } - else { - decreaseIndent(); - emitStart(node.body); - write("}"); - emitEnd(node.body); - } - } - scopeEmitEnd(); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - emitEnd(node); - write(";"); - } - tempCount = saveTempCount; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 172 /* ExpressionStatement */) { - var expr = statement.expression; - if (expr && expr.kind === 151 /* CallExpression */) { - var func = expr.expression; - if (func && func.kind === 90 /* SuperKeyword */) { - return statement; - } - } - } - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNode(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - if (memberName.kind === 8 /* StringLiteral */ || memberName.kind === 7 /* NumericLiteral */) { - write("["); - emitNode(memberName); - write("]"); - } - else if (memberName.kind === 122 /* ComputedPropertyName */) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNode(memberName); - } - } - function emitMemberAssignments(node, staticFlag) { - ts.forEach(node.members, function (member) { - if (member.kind === 126 /* PropertyDeclaration */ && (member.flags & 128 /* Static */) === staticFlag && member.initializer) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - if (staticFlag) { - emitNode(node.name); - } - else { - write("this"); - } - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emit(member.initializer); - write(";"); - emitEnd(member); - emitTrailingComments(member); - } - }); - } - function emitMemberFunctions(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */) { - if (!member.body) { - return emitPinnedOrTripleSlashComments(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitNode(node.name); - if (!(member.flags & 128 /* Static */)) { - write(".prototype"); - } - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitStart(member); - emitFunctionDeclaration(member); - emitEnd(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) { - var accessors = getAllAccessorDeclarations(node, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitNode(node.name); - if (!(member.flags & 128 /* Static */)) { - write(".prototype"); - } - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitClassDeclaration(node) { - emitLeadingComments(node); - write("var "); - emit(node.name); - write(" = (function ("); - var baseTypeNode = ts.getClassBaseTypeNode(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - increaseIndent(); - scopeEmitStart(node); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emit(node.name); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructorOfClass(); - emitMemberFunctions(node); - emitMemberAssignments(node, 128 /* Static */); - writeLine(); - function emitClassReturnStatement() { - write("return "); - emitNode(node.name); - } - emitToken(15 /* CloseBraceToken */, node.members.end, emitClassReturnStatement); - write(";"); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - emitStart(node); - write(")("); - if (baseTypeNode) { - emit(baseTypeNode.typeName); - } - write(");"); - emitEnd(node); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - emitEnd(node); - write(";"); - } - emitTrailingComments(node); - function emitConstructorOfClass() { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempCount = 0; - tempVariables = undefined; - tempParameters = undefined; - ts.forEach(node.members, function (member) { - if (member.kind === 129 /* Constructor */ && !member.body) { - emitPinnedOrTripleSlashComments(member); - } - }); - var ctor = getFirstConstructorWithBody(node); - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - write("function "); - emit(node.name); - emitSignatureParameters(ctor); - write(" {"); - scopeEmitStart(node, "constructor"); - increaseIndent(); - if (ctor) { - emitDetachedComments(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeNode) { - var superCall = findInitialSuperCall(ctor); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("_super.apply(this, arguments);"); - emitEnd(baseTypeNode); - } - } - emitMemberAssignments(node, 0); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) - statements = statements.slice(1); - emitLines(statements); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(15 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - tempCount = saveTempCount; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - } - function emitInterfaceDeclaration(node) { - emitPinnedOrTripleSlashComments(node); - } - function emitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - if (isConstEnum && !compilerOptions.preserveConstEnums) { - return; - } - emitLeadingComments(node); - if (!(node.flags & 1 /* Export */)) { - emitStart(node); - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(resolver.getLocalNameOfContainer(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - scopeEmitStart(node); - emitEnumMemberDeclarations(isConstEnum); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - emitTrailingComments(node); - function emitEnumMemberDeclarations(isConstEnum) { - ts.forEach(node.members, function (member) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - write(resolver.getLocalNameOfContainer(node)); - write("["); - write(resolver.getLocalNameOfContainer(node)); - write("["); - emitExpressionForPropertyName(member.name); - write("] = "); - if (member.initializer && !isConstEnum) { - emit(member.initializer); - } - else { - write(resolver.getEnumMemberValue(member).toString()); - } - write("] = "); - emitExpressionForPropertyName(member.name); - emitEnd(member); - write(";"); - emitTrailingComments(member); - }); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function emitModuleDeclaration(node) { - var shouldEmit = ts.getModuleInstanceState(node) === 1 /* Instantiated */ || (ts.getModuleInstanceState(node) === 2 /* ConstEnumOnly */ && compilerOptions.preserveConstEnums); - if (!shouldEmit) { - return emitPinnedOrTripleSlashComments(node); - } - emitLeadingComments(node); - emitStart(node); - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(resolver.getLocalNameOfContainer(node)); - emitEnd(node.name); - write(") "); - if (node.body.kind === 196 /* ModuleBlock */) { - var saveTempCount = tempCount; - var saveTempVariables = tempVariables; - tempCount = 0; - tempVariables = undefined; - emit(node.body); - tempCount = saveTempCount; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - scopeEmitStart(node); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(15 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); - } - write(")("); - if (node.flags & 1 /* Export */) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - emitTrailingComments(node); - } - function emitImportDeclaration(node) { - var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); - if (!emitImportDeclaration) { - emitImportDeclaration = !ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportWithEntityName(node); - } - if (emitImportDeclaration) { - if (ts.isExternalModuleImportDeclaration(node) && node.parent.kind === 207 /* SourceFile */ && compilerOptions.module === 2 /* AMD */) { - if (node.flags & 1 /* Export */) { - writeLine(); - emitLeadingComments(node); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emit(node.name); - write(";"); - emitEnd(node); - emitTrailingComments(node); - } - } - else { - writeLine(); - emitLeadingComments(node); - emitStart(node); - if (!(node.flags & 1 /* Export */)) - write("var "); - emitModuleMemberName(node); - write(" = "); - if (ts.isInternalModuleImportDeclaration(node)) { - emit(node.moduleReference); - } - else { - var literal = ts.getExternalModuleImportDeclarationExpression(node); - write("require("); - emitStart(literal); - emitLiteral(literal); - emitEnd(literal); - emitToken(17 /* CloseParenToken */, literal.end); - } - write(";"); - emitEnd(node); - emitTrailingComments(node); - } - } - } - function getExternalImportDeclarations(node) { - var result = []; - ts.forEach(node.statements, function (statement) { - if (ts.isExternalModuleImportDeclaration(statement) && resolver.isReferencedImportDeclaration(statement)) { - result.push(statement); - } - }); - return result; - } - function getFirstExportAssignment(sourceFile) { - return ts.forEach(sourceFile.statements, function (node) { - if (node.kind === 198 /* ExportAssignment */) { - return node; - } - }); - } - function emitAMDModule(node, startIndex) { - var imports = getExternalImportDeclarations(node); - writeLine(); - write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); - } - write("[\"require\", \"exports\""); - ts.forEach(imports, function (imp) { - write(", "); - emitLiteral(ts.getExternalModuleImportDeclarationExpression(imp)); - }); - ts.forEach(node.amdDependencies, function (amdDependency) { - var text = "\"" + amdDependency + "\""; - write(", "); - write(text); - }); - write("], function (require, exports"); - ts.forEach(imports, function (imp) { - write(", "); - emit(imp.name); - }); - write(") {"); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - var exportName = resolver.getExportAssignmentName(node); - if (exportName) { - writeLine(); - var exportAssignement = getFirstExportAssignment(node); - emitStart(exportAssignement); - write("return "); - emitStart(exportAssignement.exportName); - write(exportName); - emitEnd(exportAssignement.exportName); - write(";"); - emitEnd(exportAssignement); - } - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node, startIndex) { - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - var exportName = resolver.getExportAssignmentName(node); - if (exportName) { - writeLine(); - var exportAssignement = getFirstExportAssignment(node); - emitStart(exportAssignement); - write("module.exports = "); - emitStart(exportAssignement.exportName); - write(exportName); - emitEnd(exportAssignement.exportName); - write(";"); - emitEnd(exportAssignement); - } - } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { - if (ts.isPrologueDirective(statements[i])) { - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - return i; - } - } - return statements.length; - } - function emitSourceFile(node) { - currentSourceFile = node; - writeLine(); - emitDetachedComments(node); - var startIndex = emitDirectivePrologues(node.statements, false); - if (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */) { - writeLine(); - write("var __extends = this.__extends || function (d, b) {"); - increaseIndent(); - writeLine(); - write("for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); - writeLine(); - write("function __() { this.constructor = d; }"); - writeLine(); - write("__.prototype = b.prototype;"); - writeLine(); - write("d.prototype = new __();"); - decreaseIndent(); - writeLine(); - write("};"); - extendsEmitted = true; - } - if (ts.isExternalModule(node)) { - if (compilerOptions.module === 2 /* AMD */) { - emitAMDModule(node, startIndex); - } - else { - emitCommonJSModule(node, startIndex); - } - } - else { - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - } - emitLeadingComments(node.endOfFileToken); - } - function emitNode(node) { - if (!node) { - return; - } - if (node.flags & 2 /* Ambient */) { - return emitPinnedOrTripleSlashComments(node); - } - switch (node.kind) { - case 64 /* Identifier */: - return emitIdentifier(node); - case 124 /* Parameter */: - return emitParameter(node); - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - return emitMethod(node); - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return emitAccessor(node); - case 92 /* ThisKeyword */: - return emitThis(node); - case 90 /* SuperKeyword */: - return emitSuper(node); - case 88 /* NullKeyword */: - return write("null"); - case 94 /* TrueKeyword */: - return write("true"); - case 79 /* FalseKeyword */: - return write("false"); - case 7 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 9 /* RegularExpressionLiteral */: - case 10 /* NoSubstitutionTemplateLiteral */: - case 11 /* TemplateHead */: - case 12 /* TemplateMiddle */: - case 13 /* TemplateTail */: - return emitLiteral(node); - case 165 /* TemplateExpression */: - return emitTemplateExpression(node); - case 168 /* TemplateSpan */: - return emitTemplateSpan(node); - case 121 /* QualifiedName */: - return emitQualifiedName(node); - case 144 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 145 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 147 /* ArrayLiteralExpression */: - return emitArrayLiteral(node); - case 148 /* ObjectLiteralExpression */: - return emitObjectLiteral(node); - case 204 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 205 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 122 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - case 149 /* PropertyAccessExpression */: - return emitPropertyAccess(node); - case 150 /* ElementAccessExpression */: - return emitIndexedAccess(node); - case 151 /* CallExpression */: - return emitCallExpression(node); - case 152 /* NewExpression */: - return emitNewExpression(node); - case 153 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 154 /* TypeAssertionExpression */: - return emit(node.expression); - case 155 /* ParenthesizedExpression */: - return emitParenExpression(node); - case 190 /* FunctionDeclaration */: - case 156 /* FunctionExpression */: - case 157 /* ArrowFunction */: - return emitFunctionDeclaration(node); - case 158 /* DeleteExpression */: - return emitDeleteExpression(node); - case 159 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 160 /* VoidExpression */: - return emitVoidExpression(node); - case 161 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 162 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 163 /* BinaryExpression */: - return emitBinaryExpression(node); - case 164 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 167 /* OmittedExpression */: - return; - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: - case 196 /* ModuleBlock */: - return emitBlock(node); - case 170 /* VariableStatement */: - return emitVariableStatement(node); - case 171 /* EmptyStatement */: - return write(";"); - case 172 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 173 /* IfStatement */: - return emitIfStatement(node); - case 174 /* DoStatement */: - return emitDoStatement(node); - case 175 /* WhileStatement */: - return emitWhileStatement(node); - case 176 /* ForStatement */: - return emitForStatement(node); - case 177 /* ForInStatement */: - return emitForInStatement(node); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: - return emitBreakOrContinueStatement(node); - case 180 /* ReturnStatement */: - return emitReturnStatement(node); - case 181 /* WithStatement */: - return emitWithStatement(node); - case 182 /* SwitchStatement */: - return emitSwitchStatement(node); - case 200 /* CaseClause */: - case 201 /* DefaultClause */: - return emitCaseOrDefaultClause(node); - case 183 /* LabeledStatement */: - return emitLabelledStatement(node); - case 184 /* ThrowStatement */: - return emitThrowStatement(node); - case 185 /* TryStatement */: - return emitTryStatement(node); - case 203 /* CatchClause */: - return emitCatchClause(node); - case 188 /* DebuggerStatement */: - return emitDebuggerStatement(node); - case 189 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 191 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 192 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 194 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 195 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 197 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 207 /* SourceFile */: - return emitSourceFile(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function getLeadingCommentsToEmit(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { - var leadingComments; - if (hasDetachedComments(node.pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); - } - return leadingComments; - } - } - function emitLeadingDeclarationComments(node) { - var leadingComments = getLeadingCommentsToEmit(node); - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingDeclarationComments(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); - emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); - } - } - function emitLeadingCommentsOfLocalPosition(pos) { - var leadingComments; - if (hasDetachedComments(pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); - } - emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); - emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedCommentsAtPosition(node) { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - var lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); - var astLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (astLine >= lastCommentLine + 2) { - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - } - } - function emitPinnedOrTripleSlashCommentsOfNode(node) { - var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); - function isPinnedOrTripleSlashComment(comment) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - return currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; - } - else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */ && currentSourceFile.text.substring(comment.pos, comment.end).match(ts.fullTripleSlashReferencePathRegEx)) { - return true; - } - } - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, pinnedComments); - emitComments(currentSourceFile, writer, pinnedComments, true, newLine, writeComment); - } - if (compilerOptions.sourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { - emit(root); - } - else { - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emit(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); - } - function writeDeclarationFile(jsFilePath, sourceFile) { - var emitDeclarationResult = emitDeclarations(program, resolver, diagnostics, jsFilePath, sourceFile); - if (!emitDeclarationResult.reportedDeclarationError) { - var declarationOutput = emitDeclarationResult.referencePathsOutput; - var appliedSyncOutputPos = 0; - ts.forEach(emitDeclarationResult.aliasDeclarationEmitInfo, function (aliasEmitInfo) { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += aliasEmitInfo.asynchronousOutput; - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos); - writeFile(compilerHost, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); - } - } - var hasSemanticErrors = false; - var isEmitBlocked = false; - if (targetSourceFile === undefined) { - hasSemanticErrors = resolver.hasSemanticErrors(); - isEmitBlocked = resolver.isEmitBlocked(); - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, program, ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.out) { - emitFile(compilerOptions.out); - } - } - else { - if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); - isEmitBlocked = resolver.isEmitBlocked(targetSourceFile); - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && compilerOptions.out) { - ts.forEach(program.getSourceFiles(), function (sourceFile) { - if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { - hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); - isEmitBlocked = isEmitBlocked || resolver.isEmitBlocked(sourceFile); - } - }); - emitFile(compilerOptions.out); - } - } - function emitFile(jsFilePath, sourceFile) { - if (!isEmitBlocked) { - emitJavaScript(jsFilePath, sourceFile); - if (!hasSemanticErrors && compilerOptions.declaration) { - writeDeclarationFile(jsFilePath, sourceFile); - } - } - } - diagnostics.sort(ts.compareDiagnostics); - diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); - var hasEmitterError = ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === 1 /* Error */; }); - var emitResultStatus; - if (isEmitBlocked) { - emitResultStatus = 1 /* AllOutputGenerationSkipped */; - } - else if (hasEmitterError) { - emitResultStatus = 4 /* EmitErrorsEncountered */; - } - else if (hasSemanticErrors && compilerOptions.declaration) { - emitResultStatus = 3 /* DeclarationGenerationSkipped */; - } - else if (hasSemanticErrors && !compilerOptions.declaration) { - emitResultStatus = 2 /* JSGeneratedWithSemanticErrors */; - } - else { - emitResultStatus = 0 /* Succeeded */; - } - return { - emitResultStatus: emitResultStatus, - diagnostics: diagnostics, - sourceMaps: sourceMapDataList - }; - } - ts.emitFiles = emitFiles; -})(ts || (ts = {})); -var ts; (function (ts) { var nextSymbolId = 1; var nextNodeId = 1; var nextMergeId = 1; - function createTypeChecker(program, fullTypeCheck) { + function createTypeChecker(host, produceDiagnostics) { var Symbol = ts.objectAllocator.getSymbolConstructor(); var Type = ts.objectAllocator.getTypeConstructor(); var Signature = ts.objectAllocator.getSignatureConstructor(); var typeCount = 0; var emptyArray = []; var emptySymbols = {}; - var compilerOptions = program.getCompilerOptions(); + var compilerOptions = host.getCompilerOptions(); + var emitResolver = createResolver(); var checker = { - getProgram: function () { return program; }, - getNodeCount: function () { return ts.sum(program.getSourceFiles(), "nodeCount"); }, - getIdentifierCount: function () { return ts.sum(program.getSourceFiles(), "identifierCount"); }, - getSymbolCount: function () { return ts.sum(program.getSourceFiles(), "symbolCount"); }, + getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, + getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, + getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount"); }, getTypeCount: function () { return typeCount; }, isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; }, isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; }, - emitFiles: invokeEmitter, getDiagnostics: getDiagnostics, - getDeclarationDiagnostics: getDeclarationDiagnostics, getGlobalDiagnostics: getGlobalDiagnostics, getTypeOfSymbolAtLocation: getTypeOfSymbolAtLocation, getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol, @@ -9808,8 +7342,7 @@ var ts; getSignatureFromDeclaration: getSignatureFromDeclaration, isImplementationOfOverload: isImplementationOfOverload, getAliasedSymbol: resolveImport, - hasEarlyErrors: hasEarlyErrors, - isEmitBlocked: isEmitBlocked + getEmitResolver: function () { return emitResolver; } }; var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); @@ -10018,7 +7551,7 @@ var ts; if (!compilerOptions.out) { return true; } - var sourceFiles = program.getSourceFiles(); + var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(file1) <= sourceFiles.indexOf(file2); } function resolveName(location, name, meaning, nameNotFoundMessage, nameArg) { @@ -10117,7 +7650,7 @@ var ts; return undefined; } if (result.flags & 2 /* BlockScopedVariable */) { - var declaration = ts.forEach(result.declarations, function (d) { return d.flags & 6144 /* BlockScoped */ ? d : undefined; }); + var declaration = ts.forEach(result.declarations, function (d) { return ts.getCombinedNodeFlags(d) & 6144 /* BlockScoped */ ? d : undefined; }); ts.Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); if (!isDefinedBefore(declaration, errorLocation)) { error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, ts.declarationNameToString(declaration.name)); @@ -10213,7 +7746,7 @@ var ts; } while (true) { var filename = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); - var sourceFile = program.getSourceFile(filename + ".ts") || program.getSourceFile(filename + ".d.ts"); + var sourceFile = host.getSourceFile(filename + ".ts") || host.getSourceFile(filename + ".d.ts"); if (sourceFile || isRelative) break; var parentPath = ts.getDirectoryPath(searchPath); @@ -10315,7 +7848,7 @@ var ts; var members = node.members; for (var i = 0; i < members.length; i++) { var member = members[i]; - if (member.kind === 129 /* Constructor */ && member.body) { + if (member.kind === 129 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } } @@ -10410,7 +7943,7 @@ var ts; } function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol) { if (symbol === (resolvedAliasSymbol || symbolFromSymbolTable)) { - return !ts.forEach(symbolFromSymbolTable.declarations, function (declaration) { return hasExternalModuleSymbol(declaration); }) && canQualifySymbol(symbolFromSymbolTable, meaning); + return !ts.forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); } } if (isAccessible(ts.lookUp(symbols, symbol.name))) { @@ -10474,7 +8007,7 @@ var ts; meaningToLook = getQualifiedLeftMeaning(meaning); symbol = getParentOfSymbol(symbol); } - var symbolExternalModule = ts.forEach(initialSymbol.declarations, function (declaration) { return getExternalModuleContainer(declaration); }); + var symbolExternalModule = ts.forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { @@ -10627,7 +8160,7 @@ var ts; } } else { - if (!parentSymbol && ts.forEach(symbol.declarations, function (declaration) { return hasExternalModuleSymbol(declaration); })) { + if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { return; } if (symbol.flags & 2048 /* TypeLiteral */ || symbol.flags & 4096 /* ObjectLiteral */) { @@ -11016,7 +8549,7 @@ var ts; } function determineIfDeclarationIsVisible() { switch (node.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 195 /* ModuleDeclaration */: case 191 /* ClassDeclaration */: @@ -11026,7 +8559,7 @@ var ts; case 194 /* EnumDeclaration */: case 197 /* ImportDeclaration */: var parent = getDeclarationContainer(node); - if (!(node.flags & 1 /* Export */) && !(node.kind !== 197 /* ImportDeclaration */ && parent.kind !== 207 /* SourceFile */ && ts.isInAmbientContext(parent))) { + if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && !(node.kind !== 197 /* ImportDeclaration */ && parent.kind !== 207 /* SourceFile */ && ts.isInAmbientContext(parent))) { return isGlobalSourceFile(parent) || isUsedInExportAssignment(node); } return isDeclarationVisible(parent); @@ -11077,7 +8610,7 @@ var ts; } function getDeclarationContainer(node) { node = getRootDeclaration(node); - return node.kind === 189 /* VariableDeclaration */ ? node.parent.parent : node.parent; + return node.kind === 188 /* VariableDeclaration */ ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype) { var classType = getDeclaredTypeOfSymbol(prototype.parent); @@ -11106,22 +8639,28 @@ var ts; error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; } - return type; } - if (!isTypeAssignableTo(parentType, anyArrayType)) { - error(pattern, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(parentType)); - return unknownType; - } - var propName = "" + ts.indexOf(pattern.elements, declaration); - var type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : getIndexTypeOfType(parentType, 1 /* Number */); - if (!type) { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); - return unknownType; + else { + if (!isTypeAssignableTo(parentType, anyArrayType)) { + error(pattern, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(parentType)); + return unknownType; + } + if (!declaration.dotDotDotToken) { + var propName = "" + ts.indexOf(pattern.elements, declaration); + var type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : getIndexTypeOfType(parentType, 1 /* Number */); + if (!type) { + error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), propName); + return unknownType; + } + } + else { + var type = createArrayType(getIndexTypeOfType(parentType, 1 /* Number */)); + } } return type; } function getTypeForVariableLikeDeclaration(declaration) { - if (declaration.parent.kind === 177 /* ForInStatement */) { + if (declaration.parent.parent.kind === 178 /* ForInStatement */) { return anyType; } if (ts.isBindingPattern(declaration.parent)) { @@ -11160,10 +8699,7 @@ var ts; } return anyType; } - function getTypeFromBindingPattern(pattern) { - if (pattern.kind === 145 /* ArrayBindingPattern */) { - return createTupleType(ts.map(pattern.elements, function (e) { return e.kind === 167 /* OmittedExpression */ ? anyType : getTypeFromBindingElement(e); })); - } + function getTypeFromObjectBindingPattern(pattern) { var members = {}; ts.forEach(pattern.elements, function (e) { var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); @@ -11174,6 +8710,20 @@ var ts; }); return createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); } + function getTypeFromArrayBindingPattern(pattern) { + var hasSpreadElement = false; + var elementTypes = []; + ts.forEach(pattern.elements, function (e) { + elementTypes.push(e.kind === 168 /* OmittedExpression */ || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e)); + if (e.dotDotDotToken) { + hasSpreadElement = true; + } + }); + return !elementTypes.length ? anyArrayType : hasSpreadElement ? createArrayType(getUnionType(elementTypes)) : createTupleType(elementTypes); + } + function getTypeFromBindingPattern(pattern) { + return pattern.kind === 144 /* ObjectBindingPattern */ ? getTypeFromObjectBindingPattern(pattern) : getTypeFromArrayBindingPattern(pattern); + } function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) { var type = getTypeForVariableLikeDeclaration(declaration); if (type) { @@ -11906,7 +9456,7 @@ var ts; var setter = ts.getDeclarationOfKind(declaration.symbol, 131 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } - if (!returnType && !declaration.body) { + if (!returnType && ts.nodeIsMissing(declaration.body)) { returnType = anyType; } } @@ -12519,7 +10069,7 @@ var ts; return false; } function isContextSensitiveFunctionLikeDeclaration(node) { - return !node.typeParameters && !ts.forEach(node.parameters, function (p) { return p.type; }); + return !node.typeParameters && node.parameters.length && !ts.forEach(node.parameters, function (p) { return p.type; }); } function getTypeWithoutConstructors(type) { if (type.flags & 48128 /* ObjectType */) { @@ -12578,7 +10128,7 @@ var ts; if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, host.getCompilerHost().getNewLine())); } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { @@ -13118,7 +10668,7 @@ var ts; result &= related; } } - else if (source.typeParameters || source.typeParameters) { + else if (source.typeParameters || target.typeParameters) { return 0 /* False */; } source = getErasedSignature(source); @@ -13209,7 +10759,7 @@ var ts; return anyType; } if (type.flags & 16384 /* Union */) { - return getUnionType(ts.map(type.types, function (t) { return getWidenedType(t); })); + return getUnionType(ts.map(type.types, getWidenedType)); } if (isTypeOfObjectLiteral(type)) { return getWidenedTypeOfObjectLiteral(type); @@ -13277,7 +10827,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (fullTypeCheck && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -13547,7 +11097,7 @@ var ts; switch (node.kind) { case 163 /* BinaryExpression */: return isAssignedInBinaryExpression(node); - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: return isAssignedInVariableDeclaration(node); case 144 /* ObjectBindingPattern */: @@ -13566,25 +11116,24 @@ var ts; case 160 /* VoidExpression */: case 162 /* PostfixUnaryExpression */: case 164 /* ConditionalExpression */: - case 169 /* Block */: - case 170 /* VariableStatement */: - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 180 /* ReturnStatement */: - case 181 /* WithStatement */: - case 182 /* SwitchStatement */: + case 167 /* SpreadElementExpression */: + case 170 /* Block */: + case 171 /* VariableStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 181 /* ReturnStatement */: + case 182 /* WithStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 184 /* ThrowStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 185 /* ThrowStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return ts.forEachChild(node, isAssignedIn); } return false; @@ -13621,7 +11170,7 @@ var ts; node = node.parent; var narrowedType = type; switch (node.kind) { - case 173 /* IfStatement */: + case 174 /* IfStatement */: if (child !== node.expression) { narrowedType = narrowType(type, node.expression, child === node.thenStatement); } @@ -13965,15 +11514,21 @@ var ts; } return undefined; } - function getContextualTypeForArgument(node) { - var callExpression = node.parent; - var argIndex = ts.indexOf(callExpression.arguments, node); + function getContextualTypeForArgument(callTarget, arg) { + var args = getEffectiveCallArguments(callTarget); + var argIndex = ts.indexOf(args, arg); if (argIndex >= 0) { - var signature = getResolvedSignature(callExpression); + var signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; } + function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { + if (template.parent.kind === 153 /* TaggedTemplateExpression */) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + return undefined; + } function getContextualTypeForBinaryOperand(node) { var binaryExpression = node.parent; var operator = binaryExpression.operator; @@ -14024,7 +11579,7 @@ var ts; return applyToContextualType(type, function (t) { return getIndexTypeOfObjectOrUnionType(t, kind); }); } function contextualTypeIsTupleLikeType(type) { - return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return isTupleLikeType(t); }) : isTupleLikeType(type)); + return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, isTupleLikeType) : isTupleLikeType(type)); } function contextualTypeHasIndexSignature(type, kind) { return !!(type.flags & 16384 /* Union */ ? ts.forEach(type.types, function (t) { return getIndexTypeOfObjectOrUnionType(t, kind); }) : getIndexTypeOfObjectOrUnionType(type, kind)); @@ -14067,18 +11622,18 @@ var ts; } var parent = node.parent; switch (parent.kind) { - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 124 /* Parameter */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 146 /* BindingElement */: return getContextualTypeForInitializerExpression(node); case 157 /* ArrowFunction */: - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return getContextualTypeForReturnExpression(node); case 151 /* CallExpression */: case 152 /* NewExpression */: - return getContextualTypeForArgument(node); + return getContextualTypeForArgument(parent, node); case 154 /* TypeAssertionExpression */: return getTypeFromTypeNode(parent.type); case 163 /* BinaryExpression */: @@ -14089,6 +11644,9 @@ var ts; return getContextualTypeForElementExpression(node); case 164 /* ConditionalExpression */: return getContextualTypeForConditionalOperand(node); + case 169 /* TemplateSpan */: + ts.Debug.assert(parent.parent.kind === 165 /* TemplateExpression */); + return getContextualTypeForSubstitutionExpression(parent.parent, node); } return undefined; } @@ -14159,15 +11717,36 @@ var ts; } return false; } + function checkSpreadElementExpression(node, contextualMapper) { + var type = checkExpressionCached(node.expression, contextualMapper); + if (!isTypeAssignableTo(type, anyArrayType)) { + error(node.expression, ts.Diagnostics.Type_0_is_not_an_array_type, typeToString(type)); + return unknownType; + } + return type; + } function checkArrayLiteral(node, contextualMapper) { var elements = node.elements; if (!elements.length) { return createArrayType(undefinedType); } - var elementTypes = ts.map(elements, function (e) { return checkExpression(e, contextualMapper); }); - var contextualType = getContextualType(node); - if ((contextualType && contextualTypeIsTupleLikeType(contextualType)) || isAssignmentTarget(node)) { - return createTupleType(elementTypes); + var hasSpreadElement = false; + var elementTypes = []; + ts.forEach(elements, function (e) { + var type = checkExpression(e, contextualMapper); + if (e.kind === 167 /* SpreadElementExpression */) { + elementTypes.push(getIndexTypeOfType(type, 1 /* Number */) || anyType); + hasSpreadElement = true; + } + else { + elementTypes.push(type); + } + }); + if (!hasSpreadElement) { + var contextualType = getContextualType(node); + if (contextualType && contextualTypeIsTupleLikeType(contextualType) || isAssignmentTarget(node)) { + return createTupleType(elementTypes); + } } return createArrayType(getUnionType(elementTypes)); } @@ -14246,7 +11825,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 126 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? s.valueDeclaration.flags : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); @@ -14461,7 +12040,7 @@ var ts; var context = createInferenceContext(typeParameters, false); var mapper = createInferenceMapper(context); for (var i = 0; i < args.length; i++) { - if (args[i].kind === 167 /* OmittedExpression */) { + if (args[i].kind === 168 /* OmittedExpression */) { continue; } if (!excludeArgument || excludeArgument[i] === undefined) { @@ -14475,7 +12054,7 @@ var ts; } if (excludeArgument) { for (var i = 0; i < args.length; i++) { - if (args[i].kind === 167 /* OmittedExpression */) { + if (args[i].kind === 168 /* OmittedExpression */) { continue; } if (excludeArgument[i] === false) { @@ -14513,7 +12092,7 @@ var ts; for (var i = 0; i < args.length; i++) { var arg = args[i]; var argType; - if (arg.kind === 167 /* OmittedExpression */) { + if (arg.kind === 168 /* OmittedExpression */) { continue; } var paramType = getTypeAtPosition(signature, i); @@ -14600,7 +12179,7 @@ var ts; else { error(node, ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } - if (!fullTypeCheck) { + if (!produceDiagnostics) { for (var i = 0, n = candidates.length; i < n; i++) { if (hasCorrectArity(node, args, candidates[i])) { return candidates[i]; @@ -14814,7 +12393,7 @@ var ts; function checkTypeAssertion(node) { var exprType = checkExpression(node.expression); var targetType = getTypeFromTypeNode(node.type); - if (fullTypeCheck && targetType !== unknownType) { + if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, ts.Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); @@ -14840,7 +12419,7 @@ var ts; } function getReturnTypeFromBody(func, contextualMapper) { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); - if (func.body.kind !== 169 /* Block */) { + if (func.body.kind !== 170 /* Block */) { var type = checkExpressionCached(func.body, contextualMapper); } else { @@ -14878,16 +12457,16 @@ var ts; }); } function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 184 /* ThrowStatement */); + return (body.statements.length === 1) && (body.statements[0].kind === 185 /* ThrowStatement */); } function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } if (returnType === voidType || returnType === anyType) { return; } - if (!func.body || func.body.kind !== 169 /* Block */) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 170 /* Block */) { return; } var bodyBlock = func.body; @@ -14930,7 +12509,7 @@ var ts; checkSignatureDeclaration(node); } } - if (fullTypeCheck && node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -14942,7 +12521,7 @@ var ts; checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } if (node.body) { - if (node.body.kind === 169 /* Block */) { + if (node.body.kind === 170 /* Block */) { checkSourceElement(node.body); } else { @@ -15117,14 +12696,24 @@ var ts; var elements = node.elements; for (var i = 0; i < elements.length; i++) { var e = elements[i]; - if (e.kind !== 167 /* OmittedExpression */) { - var propName = "" + i; - var type = sourceType.flags & 1 /* Any */ ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : getIndexTypeOfType(sourceType, 1 /* Number */); - if (type) { - checkDestructuringAssignment(e, type, contextualMapper); + if (e.kind !== 168 /* OmittedExpression */) { + if (e.kind !== 167 /* SpreadElementExpression */) { + var propName = "" + i; + var type = sourceType.flags & 1 /* Any */ ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) : getIndexTypeOfType(sourceType, 1 /* Number */); + if (type) { + checkDestructuringAssignment(e, type, contextualMapper); + } + else { + error(e, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + } } else { - error(e, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); + if (i === elements.length - 1) { + checkReferenceAssignment(e.expression, sourceType, contextualMapper); + } + else { + error(e, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } } } } @@ -15141,6 +12730,9 @@ var ts; if (target.kind === 147 /* ArrayLiteralExpression */) { return checkArrayLiteralAssignment(target, sourceType, contextualMapper); } + return checkReferenceAssignment(target, sourceType, contextualMapper); + } + function checkReferenceAssignment(target, sourceType, contextualMapper) { var targetType = checkExpression(target, contextualMapper); if (checkReferenceExpression(target, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { checkTypeAssignableTo(sourceType, targetType, target, undefined); @@ -15260,7 +12852,7 @@ var ts; } } function checkAssignmentOperator(valueType) { - if (fullTypeCheck && operator >= 52 /* FirstAssignment */ && operator <= 63 /* LastAssignment */) { + if (produceDiagnostics && operator >= 52 /* FirstAssignment */ && operator <= 63 /* LastAssignment */) { var ok = checkReferenceExpression(node.left, ts.Diagnostics.Invalid_left_hand_side_of_assignment_expression, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); if (ok) { checkTypeAssignableTo(valueType, leftType, node.left, undefined); @@ -15405,7 +12997,9 @@ var ts; return checkBinaryExpression(node, contextualMapper); case 164 /* ConditionalExpression */: return checkConditionalExpression(node, contextualMapper); - case 167 /* OmittedExpression */: + case 167 /* SpreadElementExpression */: + return checkSpreadElementExpression(node, contextualMapper); + case 168 /* OmittedExpression */: return undefinedType; case 166 /* YieldExpression */: checkYieldExpression(node); @@ -15418,7 +13012,7 @@ var ts; grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected); } checkSourceElement(node.constraint); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0); } @@ -15429,7 +13023,7 @@ var ts; var func = ts.getContainingFunction(node); if (node.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */)) { func = ts.getContainingFunction(node); - if (!(func.kind === 129 /* Constructor */ && func.body)) { + if (!(func.kind === 129 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -15451,7 +13045,7 @@ var ts; if (node.type) { checkSourceElement(node.type); } - if (fullTypeCheck) { + if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { @@ -15519,10 +13113,10 @@ var ts; if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); } - if (!node.body) { + if (ts.nodeIsMissing(node.body)) { return; } - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } function isSuperCallExpression(n) { @@ -15556,7 +13150,7 @@ var ts; var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); if (superCallShouldBeFirst) { var statements = node.body.statements; - if (!statements.length || statements[0].kind !== 172 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { + if (!statements.length || statements[0].kind !== 173 /* ExpressionStatement */ || !isSuperCallExpression(statements[0].expression)) { error(node, ts.Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); } else { @@ -15570,10 +13164,10 @@ var ts; } } function checkAccessorDeclaration(node) { - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (fullTypeCheck) { + if (produceDiagnostics) { + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 130 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } @@ -15605,7 +13199,7 @@ var ts; for (var i = 0; i < len; i++) { checkSourceElement(node.typeArguments[i]); var constraint = getConstraintOfTypeParameter(type.target.typeParameters[i]); - if (fullTypeCheck && constraint) { + if (produceDiagnostics && constraint) { var typeArgument = type.typeArguments[i]; checkTypeAssignableTo(typeArgument, constraint, node, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } @@ -15617,7 +13211,7 @@ var ts; } function checkTypeLiteral(node) { ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -15640,14 +13234,14 @@ var ts; return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } var signature = getSignatureFromDeclaration(signatureDeclarationNode); if (!signature.hasStringLiterals) { return; } - if (signatureDeclarationNode.body) { + if (ts.nodeIsPresent(signatureDeclarationNode.body)) { error(signatureDeclarationNode, ts.Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); return; } @@ -15671,7 +13265,7 @@ var ts; error(signatureDeclarationNode, ts.Diagnostics.Specialized_overload_signature_is_not_assignable_to_any_non_specialized_signature); } function getEffectiveDeclarationFlags(n, flagsToCheck) { - var flags = n.flags; + var flags = ts.getCombinedNodeFlags(n); if (n.parent.kind !== 192 /* InterfaceDeclaration */ && ts.isInAmbientContext(n)) { if (!(flags & 2 /* Ambient */)) { flags |= 1 /* Export */; @@ -15681,7 +13275,7 @@ var ts; return flags & flagsToCheck; } function checkFunctionOrConstructorSymbol(symbol) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } function getCanonicalOverload(overloads, implementation) { @@ -15751,7 +13345,7 @@ var ts; error(errorNode, diagnostic); return; } - else if (subsequentNode.body) { + else if (ts.nodeIsPresent(subsequentNode.body)) { error(errorNode, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name)); return; } @@ -15781,7 +13375,7 @@ var ts; allNodeFlags &= currentNodeFlags; someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node); allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node); - if (node.body && bodyDeclaration) { + if (ts.nodeIsPresent(node.body) && bodyDeclaration) { if (isConstructor) { multipleConstructorImplementation = true; } @@ -15792,7 +13386,7 @@ var ts; else if (!isExportSymbolInsideModule && previousDeclaration && previousDeclaration.parent === node.parent && previousDeclaration.end !== node.pos) { reportImplementationExpectedError(previousDeclaration); } - if (node.body) { + if (ts.nodeIsPresent(node.body)) { if (!bodyDeclaration) { bodyDeclaration = node; } @@ -15837,7 +13431,7 @@ var ts; } } function checkExportsOnMergedDeclarations(node) { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } var symbol; @@ -15892,9 +13486,8 @@ var ts; } } function checkFunctionDeclaration(node) { - checkFunctionLikeDeclaration(node); - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); - if (fullTypeCheck) { + if (produceDiagnostics) { + checkFunctionLikeDeclaration(node) || checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -15919,12 +13512,12 @@ var ts; if (node.type && !isAccessor(node.kind)) { checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, getTypeFromTypeNode(node.type)); } - if (compilerOptions.noImplicitAny && !node.body && !node.type && !isPrivateWithinAmbient(node)) { + if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { reportImplicitAnyError(node, anyType); } } function checkBlock(node) { - if (node.kind === 169 /* Block */) { + if (node.kind === 170 /* Block */) { checkGrammarForStatementInAmbientContext(node); } ts.forEach(node.statements, checkSourceElement); @@ -15933,7 +13526,7 @@ var ts; } } function checkCollisionWithArgumentsInGeneratedCode(node) { - if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || !node.body) { + if (!ts.hasRestParameters(node) || ts.isInAmbientContext(node) || ts.nodeIsMissing(node.body)) { return; } ts.forEach(node.parameters, function (p) { @@ -15953,7 +13546,7 @@ var ts; return false; } var root = getRootDeclaration(node); - if (root.kind === 124 /* Parameter */ && !root.parent.body) { + if (root.kind === 124 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) { return false; } return true; @@ -16010,7 +13603,7 @@ var ts; } } function checkCollisionWithConstDeclarations(node) { - if (node.initializer && (node.flags & 6144 /* BlockScoped */) === 0) { + if (node.initializer && (ts.getCombinedNodeFlags(node) & 6144 /* BlockScoped */) === 0) { var symbol = getSymbolOfNode(node); if (symbol.flags & 1 /* FunctionScopedVariable */) { var localDeclarationSymbol = resolveName(node, node.name.text, 3 /* Variable */, undefined, undefined); @@ -16055,12 +13648,6 @@ var ts; } } function checkVariableLikeDeclaration(node) { - if (node.kind === 146 /* BindingElement */) { - checkGrammarEvalOrArgumentsInStrictMode(node, node.name); - } - else if (node.kind === 189 /* VariableDeclaration */) { - checkGrammarVariableDeclaration(node); - } checkSourceElement(node.type); if (ts.hasComputedNameButNotSymbol(node)) { if (node.initializer) { @@ -16071,7 +13658,7 @@ var ts; if (ts.isBindingPattern(node.name)) { ts.forEach(node.name.elements, checkSourceElement); } - if (node.initializer && getRootDeclaration(node).kind === 124 /* Parameter */ && !ts.getContainingFunction(node).body) { + if (node.initializer && getRootDeclaration(node).kind === 124 /* Parameter */ && ts.nodeIsMissing(ts.getContainingFunction(node).body)) { error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -16107,9 +13694,32 @@ var ts; checkCollisionWithRequireExportsInGeneratedCode(node, node.name); } } + function checkVariableDeclaration(node) { + checkGrammarVariableDeclaration(node); + return checkVariableLikeDeclaration(node); + } + function checkBindingElement(node) { + checkGrammarBindingElement(node); + return checkVariableLikeDeclaration(node); + } function checkVariableStatement(node) { - checkGrammarModifiers(node) || checkGrammarVariableDeclarations(node, node.declarations) || checkGrammarForDisallowedLetOrConstStatement(node); - ts.forEach(node.declarations, checkSourceElement); + checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); + ts.forEach(node.declarationList.declarations, checkSourceElement); + } + function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) { + if (node.modifiers) { + if (inBlockOrObjectLiteralExpression(node)) { + return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here); + } + } + } + function inBlockOrObjectLiteralExpression(node) { + while (node) { + if (node.kind === 170 /* Block */ || node.kind === 148 /* ObjectLiteralExpression */) { + return true; + } + node = node.parent; + } } function checkExpressionStatement(node) { checkGrammarForStatementInAmbientContext(node); @@ -16132,11 +13742,19 @@ var ts; checkSourceElement(node.statement); } function checkForStatement(node) { - checkGrammarForStatementInAmbientContext(node) || checkGrammarVariableDeclarations(node, node.declarations); - if (node.declarations) - ts.forEach(node.declarations, checkVariableLikeDeclaration); - if (node.initializer) - checkExpression(node.initializer); + if (!checkGrammarForStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind == 189 /* VariableDeclarationList */) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + if (node.initializer) { + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + ts.forEach(node.initializer.declarations, checkVariableDeclaration); + } + else { + checkExpression(node.initializer); + } + } if (node.condition) checkExpression(node.condition); if (node.iterator) @@ -16145,29 +13763,33 @@ var ts; } function checkForInStatement(node) { if (!checkGrammarForStatementInAmbientContext(node)) { - var declarations = node.declarations; - if (!checkGrammarVariableDeclarations(node, declarations)) { - if (declarations && declarations.length > 1) { - grammarErrorOnFirstToken(declarations[1], ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableList = node.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + if (variableList.declarations.length > 1) { + grammarErrorOnFirstToken(variableList.declarations[1], ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + } } } } - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; - checkVariableLikeDeclaration(decl); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + checkVariableDeclaration(decl); if (decl.type) { error(decl, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation); } } } - if (node.variable) { - var exprType = checkExpression(node.variable); + else { + var varExpr = node.initializer; + var exprType = checkExpression(varExpr); if (exprType !== anyType && exprType !== stringType) { - error(node.variable, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { - checkReferenceExpression(node.variable, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + checkReferenceExpression(varExpr, ts.Diagnostics.Invalid_left_hand_side_in_for_in_statement, ts.Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); } } var exprType = checkExpression(node.expression); @@ -16237,7 +13859,7 @@ var ts; hasDuplicateDefaultClause = true; } } - if (fullTypeCheck && clause.kind === 200 /* CaseClause */) { + if (produceDiagnostics && clause.kind === 200 /* CaseClause */) { var caseClause = clause; var caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { @@ -16254,7 +13876,7 @@ var ts; if (ts.isAnyFunction(current)) { break; } - if (current.kind === 183 /* LabeledStatement */ && current.label.text === node.label.text) { + if (current.kind === 184 /* LabeledStatement */ && current.label.text === node.label.text) { var sourceFile = ts.getSourceFileOfNode(node); grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; @@ -16352,7 +13974,7 @@ var ts; for (var i = 0; i < typeParameterDeclarations.length; i++) { var node = typeParameterDeclarations[i]; checkTypeParameter(node); - if (fullTypeCheck) { + if (produceDiagnostics) { for (var j = 0; j < i; j++) { if (typeParameterDeclarations[j].symbol === node.symbol) { error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name)); @@ -16378,7 +14000,7 @@ var ts; checkTypeReference(baseTypeNode); } if (type.baseTypes.length) { - if (fullTypeCheck) { + if (produceDiagnostics) { var baseType = type.baseTypes[0]; checkTypeAssignableTo(type, baseType, node.name, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); var staticBaseType = getTypeOfSymbol(baseType.symbol); @@ -16394,7 +14016,7 @@ var ts; if (implementedTypeNodes) { ts.forEach(implementedTypeNodes, function (typeRefNode) { checkTypeReference(typeRefNode); - if (fullTypeCheck) { + if (produceDiagnostics) { var t = getTypeFromTypeReferenceNode(typeRefNode); if (t !== unknownType) { var declaredType = (t.flags & 4096 /* Reference */) ? t.target : t; @@ -16409,7 +14031,7 @@ var ts; }); } ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -16514,7 +14136,7 @@ var ts; var typeName2 = typeToString(base); var errorInfo = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, host.getCompilerHost().getNewLine())); } } } @@ -16524,7 +14146,7 @@ var ts; function checkInterfaceDeclaration(node) { checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); @@ -16546,7 +14168,7 @@ var ts; } ts.forEach(ts.getInterfaceBaseTypeNodes(node), checkTypeReference); ts.forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); } } @@ -16691,10 +14313,10 @@ var ts; } } function checkEnumDeclaration(node) { - checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } + checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -16736,31 +14358,31 @@ var ts; var declarations = symbol.declarations; for (var i = 0; i < declarations.length; i++) { var declaration = declarations[i]; - if ((declaration.kind === 191 /* ClassDeclaration */ || (declaration.kind === 190 /* FunctionDeclaration */ && declaration.body)) && !ts.isInAmbientContext(declaration)) { + if ((declaration.kind === 191 /* ClassDeclaration */ || (declaration.kind === 190 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { return declaration; } } return undefined; } function checkModuleDeclaration(node) { - if (!checkGrammarModifiers(node)) { - if (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { - grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - else if (node.name.kind === 64 /* Identifier */ && node.body.kind === 196 /* ModuleBlock */) { - var statements = node.body.statements; - for (var i = 0, n = statements.length; i < n; i++) { - var statement = statements[i]; - if (statement.kind === 198 /* ExportAssignment */) { - grammarErrorOnNode(statement, ts.Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); - } - else if (ts.isExternalModuleImportDeclaration(statement)) { - grammarErrorOnNode(ts.getExternalModuleImportDeclarationExpression(statement), ts.Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + if (produceDiagnostics) { + if (!checkGrammarModifiers(node)) { + if (!ts.isInAmbientContext(node) && node.name.kind === 8 /* StringLiteral */) { + grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + else if (node.name.kind === 64 /* Identifier */ && node.body.kind === 196 /* ModuleBlock */) { + var statements = node.body.statements; + for (var i = 0, n = statements.length; i < n; i++) { + var statement = statements[i]; + if (statement.kind === 198 /* ExportAssignment */) { + grammarErrorOnNode(statement, ts.Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); + } + else if (ts.isExternalModuleImportDeclaration(statement)) { + grammarErrorOnNode(ts.getExternalModuleImportDeclarationExpression(statement), ts.Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + } } } } - } - if (fullTypeCheck) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); @@ -16897,41 +14519,42 @@ var ts; return checkSourceElement(node.type); case 190 /* FunctionDeclaration */: return checkFunctionDeclaration(node); - case 169 /* Block */: + case 170 /* Block */: case 196 /* ModuleBlock */: return checkBlock(node); - case 170 /* VariableStatement */: + case 171 /* VariableStatement */: return checkVariableStatement(node); - case 172 /* ExpressionStatement */: + case 173 /* ExpressionStatement */: return checkExpressionStatement(node); - case 173 /* IfStatement */: + case 174 /* IfStatement */: return checkIfStatement(node); - case 174 /* DoStatement */: + case 175 /* DoStatement */: return checkDoStatement(node); - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return checkWhileStatement(node); - case 176 /* ForStatement */: + case 177 /* ForStatement */: return checkForStatement(node); - case 177 /* ForInStatement */: + case 178 /* ForInStatement */: return checkForInStatement(node); - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: return checkBreakOrContinueStatement(node); - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return checkReturnStatement(node); - case 181 /* WithStatement */: + case 182 /* WithStatement */: return checkWithStatement(node); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return checkSwitchStatement(node); - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return checkLabeledStatement(node); - case 184 /* ThrowStatement */: + case 185 /* ThrowStatement */: return checkThrowStatement(node); - case 185 /* TryStatement */: + case 186 /* TryStatement */: return checkTryStatement(node); - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: + return checkVariableDeclaration(node); case 146 /* BindingElement */: - return checkVariableLikeDeclaration(node); + return checkBindingElement(node); case 191 /* ClassDeclaration */: return checkClassDeclaration(node); case 192 /* InterfaceDeclaration */: @@ -16946,10 +14569,10 @@ var ts; return checkImportDeclaration(node); case 198 /* ExportAssignment */: return checkExportAssignment(node); - case 171 /* EmptyStatement */: + case 172 /* EmptyStatement */: checkGrammarForStatementInAmbientContext(node); return; - case 188 /* DebuggerStatement */: + case 187 /* DebuggerStatement */: checkGrammarForStatementInAmbientContext(node); return; } @@ -16974,7 +14597,7 @@ var ts; case 190 /* FunctionDeclaration */: ts.forEach(node.parameters, checkFunctionExpressionBodies); break; - case 181 /* WithStatement */: + case 182 /* WithStatement */: checkFunctionExpressionBodies(node.expression); break; case 124 /* Parameter */: @@ -16991,6 +14614,8 @@ var ts; case 151 /* CallExpression */: case 152 /* NewExpression */: case 153 /* TaggedTemplateExpression */: + case 165 /* TemplateExpression */: + case 169 /* TemplateSpan */: case 154 /* TypeAssertionExpression */: case 155 /* ParenthesizedExpression */: case 159 /* TypeOfExpression */: @@ -17000,28 +14625,28 @@ var ts; case 162 /* PostfixUnaryExpression */: case 163 /* BinaryExpression */: case 164 /* ConditionalExpression */: - case 169 /* Block */: + case 167 /* SpreadElementExpression */: + case 170 /* Block */: case 196 /* ModuleBlock */: - case 170 /* VariableStatement */: - case 172 /* ExpressionStatement */: - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 178 /* ContinueStatement */: - case 179 /* BreakStatement */: - case 180 /* ReturnStatement */: - case 182 /* SwitchStatement */: + case 171 /* VariableStatement */: + case 173 /* ExpressionStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: + case 181 /* ReturnStatement */: + case 183 /* SwitchStatement */: case 200 /* CaseClause */: case 201 /* DefaultClause */: - case 183 /* LabeledStatement */: - case 184 /* ThrowStatement */: - case 185 /* TryStatement */: - case 186 /* TryBlock */: + case 184 /* LabeledStatement */: + case 185 /* ThrowStatement */: + case 186 /* TryStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: + case 189 /* VariableDeclarationList */: case 191 /* ClassDeclaration */: case 194 /* EnumDeclaration */: case 206 /* EnumMember */: @@ -17056,7 +14681,7 @@ var ts; } } function getSortedDiagnostics() { - ts.Debug.assert(fullTypeCheck, "diagnostics are available only in the full typecheck mode"); + ts.Debug.assert(produceDiagnostics, "diagnostics are available only in the full typecheck mode"); if (diagnosticsModified) { diagnostics.sort(ts.compareDiagnostics); diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); @@ -17065,25 +14690,27 @@ var ts; return diagnostics; } function getDiagnostics(sourceFile) { + throwIfNonDiagnosticsProducing(); if (sourceFile) { checkSourceFile(sourceFile); return ts.filter(getSortedDiagnostics(), function (d) { return d.file === sourceFile; }); } - ts.forEach(program.getSourceFiles(), checkSourceFile); + ts.forEach(host.getSourceFiles(), checkSourceFile); return getSortedDiagnostics(); } - function getDeclarationDiagnostics(targetSourceFile) { - var resolver = createResolver(); - checkSourceFile(targetSourceFile); - return ts.getDeclarationDiagnostics(program, resolver, targetSourceFile); - } function getGlobalDiagnostics() { + throwIfNonDiagnosticsProducing(); return ts.filter(getSortedDiagnostics(), function (d) { return !d.file; }); } + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } + } function isInsideWithStatementBody(node) { if (node) { while (node.parent) { - if (node.parent.kind === 181 /* WithStatement */ && node.parent.statement === node) { + if (node.parent.kind === 182 /* WithStatement */ && node.parent.statement === node) { return true; } node = node.parent; @@ -17203,7 +14830,7 @@ var ts; case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 124 /* Parameter */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: return node === parent.type; case 190 /* FunctionDeclaration */: case 156 /* FunctionExpression */: @@ -17424,8 +15051,17 @@ var ts; } function isUniqueLocalName(name, container) { for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name) && node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */)) { - return false; + if (node.locals && ts.hasProperty(node.locals, name)) { + var symbolWithRelevantName = node.locals[name]; + if (symbolWithRelevantName.flags & (107455 /* Value */ | 1048576 /* ExportValue */)) { + return false; + } + if (symbolWithRelevantName.flags & 8388608 /* Import */) { + var importDeclarationWithRelevantName = ts.getDeclarationOfKind(symbolWithRelevantName, 197 /* ImportDeclaration */); + if (isReferencedImportDeclaration(importDeclarationWithRelevantName)) { + return false; + } + } } } return true; @@ -17477,12 +15113,6 @@ var ts; function hasSemanticErrors(sourceFile) { return getDiagnostics(sourceFile).length > 0 || getGlobalDiagnostics().length > 0; } - function isEmitBlocked(sourceFile) { - return program.getDiagnostics(sourceFile).length !== 0 || hasEarlyErrors(sourceFile) || (compilerOptions.noEmitOnError && getDiagnostics(sourceFile).length !== 0); - } - function hasEarlyErrors(sourceFile) { - return ts.forEach(getDiagnostics(sourceFile), function (d) { return d.isEarly; }); - } function isImportResolvedToValue(symbol) { var target = resolveImport(symbol); return target !== unknownSymbol && target.flags & 107455 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target); @@ -17501,7 +15131,7 @@ var ts; return false; } function isImplementationOfOverload(node) { - if (node.body) { + if (ts.nodeIsPresent(node.body)) { var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); return signaturesOfSymbol.length > 1 || (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node); @@ -17540,7 +15170,6 @@ var ts; } function createResolver() { return { - getProgram: function () { return program; }, getLocalNameOfContainer: getLocalNameOfContainer, getExpressionNamePrefix: getExpressionNamePrefix, getExportAssignmentName: getExportAssignmentName, @@ -17549,7 +15178,6 @@ var ts; getEnumMemberValue: getEnumMemberValue, isTopLevelValueImportWithEntityName: isTopLevelValueImportWithEntityName, hasSemanticErrors: hasSemanticErrors, - isEmitBlocked: isEmitBlocked, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, writeTypeOfDeclaration: writeTypeOfDeclaration, @@ -17560,16 +15188,12 @@ var ts; isUnknownIdentifier: isUnknownIdentifier }; } - function invokeEmitter(targetSourceFile) { - var resolver = createResolver(); - return ts.emitFiles(resolver, targetSourceFile); - } function initializeTypeChecker() { - ts.forEach(program.getSourceFiles(), function (file) { + ts.forEach(host.getSourceFiles(), function (file) { ts.bindSourceFile(file); ts.forEach(file.semanticDiagnostics, addDiagnostic); }); - ts.forEach(program.getSourceFiles(), function (file) { + ts.forEach(host.getSourceFiles(), function (file) { if (!ts.isExternalModule(file)) { extendSymbolTable(globals, file.locals); } @@ -17604,7 +15228,7 @@ var ts; case 195 /* ModuleDeclaration */: case 194 /* EnumDeclaration */: case 198 /* ExportAssignment */: - case 170 /* VariableStatement */: + case 171 /* VariableStatement */: case 190 /* FunctionDeclaration */: case 193 /* TypeAliasDeclaration */: case 197 /* ImportDeclaration */: @@ -17821,7 +15445,7 @@ var ts; var sourceFile = ts.getSourceFileOfNode(node); for (var i = 0, n = arguments.length; i < n; i++) { var arg = arguments[i]; - if (arg.kind === 167 /* OmittedExpression */) { + if (arg.kind === 168 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } } @@ -17929,7 +15553,7 @@ var ts; for (var i = 0, n = node.properties.length; i < n; i++) { var prop = node.properties[i]; var name = prop.name; - if (prop.kind === 167 /* OmittedExpression */ || name.kind === 122 /* ComputedPropertyName */) { + if (prop.kind === 168 /* OmittedExpression */ || name.kind === 122 /* ComputedPropertyName */) { checkGrammarComputedPropertyName(name); continue; } @@ -18024,9 +15648,17 @@ var ts; } } function checkGrammarMethod(node) { - if (checkGrammarFunctionLikeDeclaration(node) || checkGrammarForGenerator(node)) { + if (checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarFunctionLikeDeclaration(node) || checkGrammarForGenerator(node)) { return true; } + if (node.parent.kind === 148 /* ObjectLiteralExpression */) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, ts.Diagnostics._0_expected, "{"); + } + } if (node.parent.kind === 191 /* ClassDeclaration */) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, ts.Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; @@ -18047,12 +15679,12 @@ var ts; } function isIterationStatement(node, lookInLabeledStatements) { switch (node.kind) { - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: return true; - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements); } return false; @@ -18064,17 +15696,17 @@ var ts; return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary); } switch (current.kind) { - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: if (node.label && current.label.text === node.label.text) { - var isMisplacedContinueLabel = node.kind === 178 /* ContinueStatement */ && !isIterationStatement(current.statement, true); + var isMisplacedContinueLabel = node.kind === 179 /* ContinueStatement */ && !isIterationStatement(current.statement, true); if (isMisplacedContinueLabel) { return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement); } return false; } break; - case 182 /* SwitchStatement */: - if (node.kind === 179 /* BreakStatement */ && !node.label) { + case 183 /* SwitchStatement */: + if (node.kind === 180 /* BreakStatement */ && !node.label) { return false; } break; @@ -18087,14 +15719,26 @@ var ts; current = current.parent; } if (node.label) { - var message = node.kind === 179 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; + var message = node.kind === 180 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - var message = node.kind === 179 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; + var message = node.kind === 180 /* BreakStatement */ ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } } + function checkGrammarBindingElement(node) { + if (node.dotDotDotToken) { + var elements = node.parent.elements; + if (node !== elements[elements.length - 1]) { + return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); + } + if (node.initializer) { + return grammarErrorAtPos(ts.getSourceFileOfNode(node), node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); + } + } + return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); + } function checkGrammarVariableDeclaration(node) { if (ts.isInAmbientContext(node)) { if (ts.isBindingPattern(node.name)) { @@ -18116,45 +15760,43 @@ var ts; } return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } - function checkGrammarVariableDeclarations(container, declarations) { - if (declarations) { - if (checkGrammarForDisallowedTrailingComma(declarations)) { - return true; + function checkGrammarVariableDeclarationList(declarationList) { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); + } + if (compilerOptions.target < 2 /* ES6 */) { + if (ts.isLet(declarationList)) { + return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } - if (!declarations.length) { - return grammarErrorAtPos(ts.getSourceFileOfNode(container), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); - } - var decl = declarations[0]; - if (compilerOptions.target < 2 /* ES6 */) { - if (ts.isLet(decl)) { - return grammarErrorOnFirstToken(decl, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } - else if (ts.isConst(decl)) { - return grammarErrorOnFirstToken(decl, ts.Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } + else if (ts.isConst(declarationList)) { + return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } } } function allowLetAndConstDeclarations(parent) { switch (parent.kind) { - case 173 /* IfStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 181 /* WithStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: + case 174 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 182 /* WithStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: return false; - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return allowLetAndConstDeclarations(parent.parent); } return true; } function checkGrammarForDisallowedLetOrConstStatement(node) { if (!allowLetAndConstDeclarations(node.parent)) { - if (ts.isLet(node)) { + if (ts.isLet(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (ts.isConst(node)) { + else if (ts.isConst(node.declarationList)) { return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } @@ -18275,7 +15917,7 @@ var ts; function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) { for (var i = 0, n = file.statements.length; i < n; i++) { var decl = file.statements[i]; - if (ts.isDeclaration(decl) || decl.kind === 170 /* VariableStatement */) { + if (ts.isDeclaration(decl) || decl.kind === 171 /* VariableStatement */) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; } @@ -18294,7 +15936,7 @@ var ts; if (!links.hasReportedStatementInAmbientContext && ts.isAnyFunction(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } - if (node.parent.kind === 169 /* Block */ || node.parent.kind === 196 /* ModuleBlock */ || node.parent.kind === 207 /* SourceFile */) { + if (node.parent.kind === 170 /* Block */ || node.parent.kind === 196 /* ModuleBlock */ || node.parent.kind === 207 /* SourceFile */) { var links = getNodeLinks(node.parent); if (!links.hasReportedStatementInAmbientContext) { return links.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -18329,6 +15971,3837 @@ var ts; ts.createTypeChecker = createTypeChecker; })(ts || (ts = {})); var ts; +(function (ts) { + var indentStrings = ["", " "]; + function getIndentString(level) { + if (indentStrings[level] === undefined) { + indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; + } + return indentStrings[level]; + } + ts.getIndentString = getIndentString; + function getIndentSize() { + return indentStrings[1].length; + } + function shouldEmitToOwnFile(sourceFile, compilerOptions) { + if (!ts.isDeclarationFile(sourceFile)) { + if ((ts.isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + return true; + } + return false; + } + return false; + } + ts.shouldEmitToOwnFile = shouldEmitToOwnFile; + function isExternalModuleOrDeclarationFile(sourceFile) { + return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); + } + ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + function createTextWriter(newLine) { + var output = ""; + var indent = 0; + var lineStart = true; + var lineCount = 0; + var linePos = 0; + function write(s) { + if (s && s.length) { + if (lineStart) { + output += getIndentString(indent); + lineStart = false; + } + output += s; + } + } + function rawWrite(s) { + if (s !== undefined) { + if (lineStart) { + lineStart = false; + } + output += s; + } + } + function writeLiteral(s) { + if (s && s.length) { + write(s); + var lineStartsOfS = ts.computeLineStarts(s); + if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; + linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + } + } + } + function writeLine() { + if (!lineStart) { + output += newLine; + lineCount++; + linePos = output.length; + lineStart = true; + } + } + function writeTextOfNode(sourceFile, node) { + write(ts.getSourceTextOfNodeFromSourceFile(sourceFile, node)); + } + return { + write: write, + rawWrite: rawWrite, + writeTextOfNode: writeTextOfNode, + writeLiteral: writeLiteral, + writeLine: writeLine, + increaseIndent: function () { return indent++; }, + decreaseIndent: function () { return indent--; }, + getIndent: function () { return indent; }, + getTextPos: function () { return output.length; }, + getLine: function () { return lineCount + 1; }, + getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, + getText: function () { return output; } + }; + } + function getLineOfLocalPosition(currentSourceFile, pos) { + return currentSourceFile.getLineAndCharacterFromPosition(pos).line; + } + function emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments) { + if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos && getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) { + writer.writeLine(); + } + } + function emitComments(currentSourceFile, writer, comments, trailingSeparator, newLine, writeComment) { + var emitLeadingSpace = !trailingSeparator; + ts.forEach(comments, function (comment) { + if (emitLeadingSpace) { + writer.write(" "); + emitLeadingSpace = false; + } + writeComment(currentSourceFile, writer, comment, newLine); + if (comment.hasTrailingNewLine) { + writer.writeLine(); + } + else if (trailingSeparator) { + writer.write(" "); + } + else { + emitLeadingSpace = true; + } + }); + } + function writeCommentRange(currentSourceFile, writer, comment, newLine) { + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); + var firstCommentLineIndent; + for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { + var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); + if (pos !== comment.pos) { + if (firstCommentLineIndent === undefined) { + firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); + } + var currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + if (spacesToEmit > 0) { + var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); + var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + writer.rawWrite(indentSizeSpaceString); + while (numberOfSingleSpacesToEmit) { + writer.rawWrite(" "); + numberOfSingleSpacesToEmit--; + } + } + else { + writer.rawWrite(""); + } + } + writeTrimmedCurrentLine(pos, nextLineStart); + pos = nextLineStart; + } + } + else { + writer.write(currentSourceFile.text.substring(comment.pos, comment.end)); + } + function writeTrimmedCurrentLine(pos, nextLineStart) { + var end = Math.min(comment.end, nextLineStart - 1); + var currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ''); + if (currentLineText) { + writer.write(currentLineText); + if (end !== comment.end) { + writer.writeLine(); + } + } + else { + writer.writeLiteral(newLine); + } + } + function calculateIndent(pos, end) { + var currentLineIndent = 0; + for (; pos < end && ts.isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) { + if (currentSourceFile.text.charCodeAt(pos) === 9 /* tab */) { + currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize()); + } + else { + currentLineIndent++; + } + } + return currentLineIndent; + } + } + function getFirstConstructorWithBody(node) { + return ts.forEach(node.members, function (member) { + if (member.kind === 129 /* Constructor */ && ts.nodeIsPresent(member.body)) { + return member; + } + }); + } + function getAllAccessorDeclarations(node, accessor) { + var firstAccessor; + var getAccessor; + var setAccessor; + if (accessor.name.kind === 122 /* ComputedPropertyName */) { + firstAccessor = accessor; + if (accessor.kind === 130 /* GetAccessor */) { + getAccessor = accessor; + } + else if (accessor.kind === 131 /* SetAccessor */) { + setAccessor = accessor; + } + else { + ts.Debug.fail("Accessor has wrong kind"); + } + } + else { + ts.forEach(node.members, function (member) { + if ((member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) && member.name.text === accessor.name.text && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { + if (!firstAccessor) { + firstAccessor = member; + } + if (member.kind === 130 /* GetAccessor */ && !getAccessor) { + getAccessor = member; + } + if (member.kind === 131 /* SetAccessor */ && !setAccessor) { + setAccessor = member; + } + } + }); + } + return { + firstAccessor: firstAccessor, + getAccessor: getAccessor, + setAccessor: setAccessor + }; + } + function getSourceFilePathInNewDir(sourceFile, host, newDirPath) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, host.getCurrentDirectory()); + sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); + return ts.combinePaths(newDirPath, sourceFilePath); + } + function getOwnEmitOutputFilePath(sourceFile, host, extension) { + var compilerOptions = host.getCompilerOptions(); + if (compilerOptions.outDir) { + var emitOutputFilePathWithoutExtension = ts.removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); + } + else { + var emitOutputFilePathWithoutExtension = ts.removeFileExtension(sourceFile.filename); + } + return emitOutputFilePathWithoutExtension + extension; + } + function writeFile(host, diagnostics, filename, data, writeByteOrderMark) { + host.writeFile(filename, data, writeByteOrderMark, function (hostErrorMessage) { + diagnostics.push(ts.createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); + }); + } + function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { + var newLine = host.getNewLine(); + var compilerOptions = host.getCompilerOptions(); + var write; + var writeLine; + var increaseIndent; + var decreaseIndent; + var writeTextOfNode; + var writer = createAndSetNewTextWriterWithSymbolWriter(); + var enclosingDeclaration; + var currentSourceFile; + var reportedDeclarationError = false; + var emitJsDocComments = compilerOptions.removeComments ? function (declaration) { + } : writeJsDocComments; + var aliasDeclarationEmitInfo = []; + function createAndSetNewTextWriterWithSymbolWriter() { + var writer = createTextWriter(newLine); + writer.trackSymbol = trackSymbol; + writer.writeKeyword = writer.write; + writer.writeOperator = writer.write; + writer.writePunctuation = writer.write; + writer.writeSpace = writer.write; + writer.writeStringLiteral = writer.writeLiteral; + writer.writeParameter = writer.write; + writer.writeSymbol = writer.write; + setWriter(writer); + return writer; + } + function setWriter(newWriter) { + writer = newWriter; + write = newWriter.write; + writeTextOfNode = newWriter.writeTextOfNode; + writeLine = newWriter.writeLine; + increaseIndent = newWriter.increaseIndent; + decreaseIndent = newWriter.decreaseIndent; + } + function writeAsychronousImportDeclarations(importDeclarations) { + var oldWriter = writer; + ts.forEach(importDeclarations, function (aliasToWrite) { + var aliasEmitInfo = ts.forEach(aliasDeclarationEmitInfo, function (declEmitInfo) { return declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined; }); + if (aliasEmitInfo) { + createAndSetNewTextWriterWithSymbolWriter(); + for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) { + increaseIndent(); + } + writeImportDeclaration(aliasToWrite); + aliasEmitInfo.asynchronousOutput = writer.getText(); + } + }); + setWriter(oldWriter); + } + function handleSymbolAccessibilityError(symbolAccesibilityResult) { + if (symbolAccesibilityResult.accessibility === 0 /* Accessible */) { + if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) { + writeAsychronousImportDeclarations(symbolAccesibilityResult.aliasesToMakeVisible); + } + } + else { + reportedDeclarationError = true; + var errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName), symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + else { + diagnostics.push(ts.createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccesibilityResult.errorSymbolName, symbolAccesibilityResult.errorModuleName)); + } + } + } + } + function trackSymbol(symbol, enclosingDeclaration, meaning) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + } + function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (type) { + emitType(type); + } + else { + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + } + } + function writeReturnTypeAtSignature(signature, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + write(": "); + if (signature.type) { + emitType(signature.type); + } + else { + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + } + } + function emitLines(nodes) { + for (var i = 0, n = nodes.length; i < n; i++) { + emitNode(nodes[i]); + } + } + function emitSeparatedList(nodes, separator, eachNodeEmitFn) { + var currentWriterPos = writer.getTextPos(); + for (var i = 0, n = nodes.length; i < n; i++) { + if (currentWriterPos !== writer.getTextPos()) { + write(separator); + } + currentWriterPos = writer.getTextPos(); + eachNodeEmitFn(nodes[i]); + } + } + function emitCommaList(nodes, eachNodeEmitFn) { + emitSeparatedList(nodes, ", ", eachNodeEmitFn); + } + function writeJsDocComments(declaration) { + if (declaration) { + var jsDocComments = ts.getJsDocComments(declaration, currentSourceFile); + emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); + emitComments(currentSourceFile, writer, jsDocComments, true, newLine, writeCommentRange); + } + } + function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type, getSymbolAccessibilityDiagnostic) { + writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; + emitType(type); + } + function emitType(type) { + switch (type.kind) { + case 110 /* AnyKeyword */: + case 119 /* StringKeyword */: + case 117 /* NumberKeyword */: + case 111 /* BooleanKeyword */: + case 98 /* VoidKeyword */: + case 8 /* StringLiteral */: + return writeTextOfNode(currentSourceFile, type); + case 135 /* TypeReference */: + return emitTypeReference(type); + case 138 /* TypeQuery */: + return emitTypeQuery(type); + case 140 /* ArrayType */: + return emitArrayType(type); + case 141 /* TupleType */: + return emitTupleType(type); + case 142 /* UnionType */: + return emitUnionType(type); + case 143 /* ParenthesizedType */: + return emitParenType(type); + case 136 /* FunctionType */: + case 137 /* ConstructorType */: + return emitSignatureDeclarationWithJsDocComments(type); + case 139 /* TypeLiteral */: + return emitTypeLiteral(type); + case 64 /* Identifier */: + return emitEntityName(type); + case 121 /* QualifiedName */: + return emitEntityName(type); + default: + ts.Debug.fail("Unknown type annotation: " + type.kind); + } + function emitEntityName(entityName) { + var visibilityResult = resolver.isEntityNameVisible(entityName, entityName.parent.kind === 197 /* ImportDeclaration */ ? entityName.parent : enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + writeEntityName(entityName); + function writeEntityName(entityName) { + if (entityName.kind === 64 /* Identifier */) { + writeTextOfNode(currentSourceFile, entityName); + } + else { + var qualifiedName = entityName; + writeEntityName(qualifiedName.left); + write("."); + writeTextOfNode(currentSourceFile, qualifiedName.right); + } + } + } + function emitTypeReference(type) { + emitEntityName(type.typeName); + if (type.typeArguments) { + write("<"); + emitCommaList(type.typeArguments, emitType); + write(">"); + } + } + function emitTypeQuery(type) { + write("typeof "); + emitEntityName(type.exprName); + } + function emitArrayType(type) { + emitType(type.elementType); + write("[]"); + } + function emitTupleType(type) { + write("["); + emitCommaList(type.elementTypes, emitType); + write("]"); + } + function emitUnionType(type) { + emitSeparatedList(type.types, " | ", emitType); + } + function emitParenType(type) { + write("("); + emitType(type.type); + write(")"); + } + function emitTypeLiteral(type) { + write("{"); + if (type.members.length) { + writeLine(); + increaseIndent(); + emitLines(type.members); + decreaseIndent(); + } + write("}"); + } + } + function emitSourceFile(node) { + currentSourceFile = node; + enclosingDeclaration = node; + emitLines(node.statements); + } + function emitExportAssignment(node) { + write("export = "); + writeTextOfNode(currentSourceFile, node.exportName); + write(";"); + writeLine(); + } + function emitModuleElementDeclarationFlags(node) { + if (node.parent === currentSourceFile) { + if (node.flags & 1 /* Export */) { + write("export "); + } + if (node.kind !== 192 /* InterfaceDeclaration */) { + write("declare "); + } + } + } + function emitClassMemberDeclarationFlags(node) { + if (node.flags & 32 /* Private */) { + write("private "); + } + else if (node.flags & 64 /* Protected */) { + write("protected "); + } + if (node.flags & 128 /* Static */) { + write("static "); + } + } + function emitImportDeclaration(node) { + var nodeEmitInfo = { + declaration: node, + outputPos: writer.getTextPos(), + indent: writer.getIndent(), + hasWritten: resolver.isDeclarationVisible(node) + }; + aliasDeclarationEmitInfo.push(nodeEmitInfo); + if (nodeEmitInfo.hasWritten) { + writeImportDeclaration(node); + } + } + function writeImportDeclaration(node) { + emitJsDocComments(node); + if (node.flags & 1 /* Export */) { + write("export "); + } + write("import "); + writeTextOfNode(currentSourceFile, node.name); + write(" = "); + if (ts.isInternalModuleImportDeclaration(node)) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); + write(";"); + } + else { + write("require("); + writeTextOfNode(currentSourceFile, ts.getExternalModuleImportDeclarationExpression(node)); + write(");"); + } + writer.writeLine(); + function getImportEntityNameVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: node.name + }; + } + } + function emitModuleDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("module "); + writeTextOfNode(currentSourceFile, node.name); + while (node.body.kind !== 196 /* ModuleBlock */) { + node = node.body; + write("."); + writeTextOfNode(currentSourceFile, node.name); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.body.statements); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitTypeAliasDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("type "); + writeTextOfNode(currentSourceFile, node.name); + write(" = "); + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); + write(";"); + writeLine(); + } + function getTypeAliasDeclarationVisibilityError(symbolAccesibilityResult) { + return { + diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: node.type, + typeName: node.name + }; + } + } + function emitEnumDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isConst(node)) { + write("const "); + } + write("enum "); + writeTextOfNode(currentSourceFile, node.name); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + } + } + function emitEnumMemberDeclaration(node) { + emitJsDocComments(node); + writeTextOfNode(currentSourceFile, node.name); + var enumMemberValue = resolver.getEnumMemberValue(node); + if (enumMemberValue !== undefined) { + write(" = "); + write(enumMemberValue.toString()); + } + write(","); + writeLine(); + } + function isPrivateMethodTypeParameter(node) { + return node.parent.kind === 128 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + } + function emitTypeParameters(typeParameters) { + function emitTypeParameter(node) { + increaseIndent(); + emitJsDocComments(node); + decreaseIndent(); + writeTextOfNode(currentSourceFile, node.name); + if (node.constraint && !isPrivateMethodTypeParameter(node)) { + write(" extends "); + if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || (node.parent.parent && node.parent.parent.kind === 139 /* TypeLiteral */)) { + ts.Debug.assert(node.parent.kind === 128 /* MethodDeclaration */ || node.parent.kind === 127 /* MethodSignature */ || node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.kind === 132 /* CallSignature */ || node.parent.kind === 133 /* ConstructSignature */); + emitType(node.constraint); + } + else { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); + } + } + function getTypeParameterConstraintVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.parent.kind) { + case 191 /* ClassDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + case 192 /* InterfaceDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + case 133 /* ConstructSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 132 /* CallSignature */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + } + if (typeParameters) { + write("<"); + emitCommaList(typeParameters, emitTypeParameter); + write(">"); + } + } + function emitHeritageClause(typeReferences, isImplementsList) { + if (typeReferences) { + write(isImplementsList ? " implements " : " extends "); + emitCommaList(typeReferences, emitTypeOfTypeReference); + } + function emitTypeOfTypeReference(node) { + emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); + function getHeritageClauseVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = isImplementsList ? ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : ts.Diagnostics.Extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = ts.Diagnostics.Extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.parent.parent.name + }; + } + } + } + function emitClassDeclaration(node) { + function emitParameterProperties(constructorDeclaration) { + if (constructorDeclaration) { + ts.forEach(constructorDeclaration.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + emitPropertyDeclaration(param); + } + }); + } + } + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("class "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + var baseTypeNode = ts.getClassBaseTypeNode(node); + if (baseTypeNode) { + emitHeritageClause([baseTypeNode], false); + } + emitHeritageClause(ts.getClassImplementedTypeNodes(node), true); + write(" {"); + writeLine(); + increaseIndent(); + emitParameterProperties(getFirstConstructorWithBody(node)); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitInterfaceDeclaration(node) { + if (resolver.isDeclarationVisible(node)) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + write("interface "); + writeTextOfNode(currentSourceFile, node.name); + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitTypeParameters(node.typeParameters); + emitHeritageClause(ts.getInterfaceBaseTypeNodes(node), false); + write(" {"); + writeLine(); + increaseIndent(); + emitLines(node.members); + decreaseIndent(); + write("}"); + writeLine(); + enclosingDeclaration = prevEnclosingDeclaration; + } + } + function emitPropertyDeclaration(node) { + emitJsDocComments(node); + emitClassMemberDeclarationFlags(node); + emitVariableDeclaration(node); + write(";"); + writeLine(); + } + function emitVariableDeclaration(node) { + if (node.kind !== 188 /* VariableDeclaration */ || resolver.isDeclarationVisible(node)) { + writeTextOfNode(currentSourceFile, node.name); + if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && ts.hasQuestionToken(node)) { + write("?"); + } + if ((node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) && node.parent.kind === 139 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); + } + } + function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (node.kind === 188 /* VariableDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + else if (node.kind === 126 /* PropertyDeclaration */ || node.kind === 125 /* PropertySignature */) { + if (node.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + return diagnosticMessage !== undefined ? { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + } : undefined; + } + } + function emitTypeOfVariableDeclarationFromTypeLiteral(node) { + if (node.type) { + write(": "); + emitType(node.type); + } + } + function emitVariableStatement(node) { + var hasDeclarationWithEmit = ts.forEach(node.declarationList.declarations, function (varDeclaration) { return resolver.isDeclarationVisible(varDeclaration); }); + if (hasDeclarationWithEmit) { + emitJsDocComments(node); + emitModuleElementDeclarationFlags(node); + if (ts.isLet(node.declarationList)) { + write("let "); + } + else if (ts.isConst(node.declarationList)) { + write("const "); + } + else { + write("var "); + } + emitCommaList(node.declarationList.declarations, emitVariableDeclaration); + write(";"); + writeLine(); + } + } + function emitAccessorDeclaration(node) { + var accessors = getAllAccessorDeclarations(node.parent, node); + if (node === accessors.firstAccessor) { + emitJsDocComments(accessors.getAccessor); + emitJsDocComments(accessors.setAccessor); + emitClassMemberDeclarationFlags(node); + writeTextOfNode(currentSourceFile, node.name); + if (!(node.flags & 32 /* Private */)) { + var accessorWithTypeAnnotation = node; + var type = getTypeAnnotationFromAccessor(node); + if (!type) { + var anotherAccessor = node.kind === 130 /* GetAccessor */ ? accessors.setAccessor : accessors.getAccessor; + type = getTypeAnnotationFromAccessor(anotherAccessor); + if (type) { + accessorWithTypeAnnotation = anotherAccessor; + } + } + writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); + } + write(";"); + writeLine(); + } + function getTypeAnnotationFromAccessor(accessor) { + if (accessor) { + return accessor.kind === 130 /* GetAccessor */ ? accessor.type : accessor.parameters[0].type; + } + } + function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + if (accessorWithTypeAnnotation.kind === 131 /* SetAccessor */) { + if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_property_setter_from_exported_class_has_or_is_using_private_name_1; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.parameters[0], + typeName: accessorWithTypeAnnotation.name + }; + } + else { + if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_property_getter_from_exported_class_has_or_is_using_private_name_0; + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: accessorWithTypeAnnotation.name, + typeName: undefined + }; + } + } + } + function emitFunctionDeclaration(node) { + if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { + emitJsDocComments(node); + if (node.kind === 190 /* FunctionDeclaration */) { + emitModuleElementDeclarationFlags(node); + } + else if (node.kind === 128 /* MethodDeclaration */) { + emitClassMemberDeclarationFlags(node); + } + if (node.kind === 190 /* FunctionDeclaration */) { + write("function "); + writeTextOfNode(currentSourceFile, node.name); + } + else if (node.kind === 129 /* Constructor */) { + write("constructor"); + } + else { + writeTextOfNode(currentSourceFile, node.name); + if (ts.hasQuestionToken(node)) { + write("?"); + } + } + emitSignatureDeclaration(node); + } + } + function emitSignatureDeclarationWithJsDocComments(node) { + emitJsDocComments(node); + emitSignatureDeclaration(node); + } + function emitSignatureDeclaration(node) { + if (node.kind === 133 /* ConstructSignature */ || node.kind === 137 /* ConstructorType */) { + write("new "); + } + emitTypeParameters(node.typeParameters); + if (node.kind === 134 /* IndexSignature */) { + write("["); + } + else { + write("("); + } + var prevEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = node; + emitCommaList(node.parameters, emitParameterDeclaration); + if (node.kind === 134 /* IndexSignature */) { + write("]"); + } + else { + write(")"); + } + var isFunctionTypeOrConstructorType = node.kind === 136 /* FunctionType */ || node.kind === 137 /* ConstructorType */; + if (isFunctionTypeOrConstructorType || node.parent.kind === 139 /* TypeLiteral */) { + if (node.type) { + write(isFunctionTypeOrConstructorType ? " => " : ": "); + emitType(node.type); + } + } + else if (node.kind !== 129 /* Constructor */ && !(node.flags & 32 /* Private */)) { + writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); + } + enclosingDeclaration = prevEnclosingDeclaration; + if (!isFunctionTypeOrConstructorType) { + write(";"); + writeLine(); + } + function getReturnTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.kind) { + case 133 /* ConstructSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 132 /* CallSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 134 /* IndexSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + default: + ts.Debug.fail("This is unknown kind for signature: " + node.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node.name || node + }; + } + } + function emitParameterDeclaration(node) { + increaseIndent(); + emitJsDocComments(node); + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + write("_" + ts.indexOf(node.parent.parameters, node)); + } + else { + writeTextOfNode(currentSourceFile, node.name); + } + if (node.initializer || ts.hasQuestionToken(node)) { + write("?"); + } + decreaseIndent(); + if (node.parent.kind === 136 /* FunctionType */ || node.parent.kind === 137 /* ConstructorType */ || node.parent.parent.kind === 139 /* TypeLiteral */) { + emitTypeOfVariableDeclarationFromTypeLiteral(node); + } + else if (!(node.parent.flags & 32 /* Private */)) { + writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); + } + function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { + var diagnosticMessage; + switch (node.parent.kind) { + case 129 /* Constructor */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + break; + case 133 /* ConstructSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 132 /* CallSignature */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + if (node.parent.flags & 128 /* Static */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + case 190 /* FunctionDeclaration */: + diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + default: + ts.Debug.fail("This is unknown parent for parameter: " + node.parent.kind); + } + return { + diagnosticMessage: diagnosticMessage, + errorNode: node, + typeName: node.name + }; + } + } + function emitNode(node) { + switch (node.kind) { + case 129 /* Constructor */: + case 190 /* FunctionDeclaration */: + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + return emitFunctionDeclaration(node); + case 133 /* ConstructSignature */: + case 132 /* CallSignature */: + case 134 /* IndexSignature */: + return emitSignatureDeclarationWithJsDocComments(node); + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + return emitAccessorDeclaration(node); + case 171 /* VariableStatement */: + return emitVariableStatement(node); + case 126 /* PropertyDeclaration */: + case 125 /* PropertySignature */: + return emitPropertyDeclaration(node); + case 192 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 191 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 193 /* TypeAliasDeclaration */: + return emitTypeAliasDeclaration(node); + case 206 /* EnumMember */: + return emitEnumMemberDeclaration(node); + case 194 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 195 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 197 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 198 /* ExportAssignment */: + return emitExportAssignment(node); + case 207 /* SourceFile */: + return emitSourceFile(node); + } + } + var referencePathsOutput = ""; + function writeReferencePath(referencedFile) { + var declFileName = referencedFile.flags & 1024 /* DeclarationFile */ ? referencedFile.filename : shouldEmitToOwnFile(referencedFile, compilerOptions) ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") : ts.removeFileExtension(compilerOptions.out) + ".d.ts"; + declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(jsFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); + referencePathsOutput += "/// " + newLine; + } + if (root) { + if (!compilerOptions.noResolve) { + var addedGlobalFileReference = false; + ts.forEach(root.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); + if (referencedFile && ((referencedFile.flags & 1024 /* DeclarationFile */) || shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { + writeReferencePath(referencedFile); + if (!isExternalModuleOrDeclarationFile(referencedFile)) { + addedGlobalFileReference = true; + } + } + }); + } + emitNode(root); + } + else { + var emittedReferencedFiles = []; + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + if (!compilerOptions.noResolve) { + ts.forEach(sourceFile.referencedFiles, function (fileReference) { + var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); + if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && !ts.contains(emittedReferencedFiles, referencedFile))) { + writeReferencePath(referencedFile); + emittedReferencedFiles.push(referencedFile); + } + }); + } + emitNode(sourceFile); + } + }); + } + return { + reportedDeclarationError: reportedDeclarationError, + aliasDeclarationEmitInfo: aliasDeclarationEmitInfo, + synchronousDeclarationOutput: writer.getText(), + referencePathsOutput: referencePathsOutput + }; + } + function getDeclarationDiagnostics(host, resolver, targetSourceFile) { + var diagnostics = []; + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); + return diagnostics; + } + ts.getDeclarationDiagnostics = getDeclarationDiagnostics; + function emitFiles(resolver, host, targetSourceFile) { + var compilerOptions = host.getCompilerOptions(); + var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; + var diagnostics = []; + var newLine = host.getNewLine(); + function emitJavaScript(jsFilePath, root) { + var writer = createTextWriter(newLine); + var write = writer.write; + var writeTextOfNode = writer.writeTextOfNode; + var writeLine = writer.writeLine; + var increaseIndent = writer.increaseIndent; + var decreaseIndent = writer.decreaseIndent; + var currentSourceFile; + var extendsEmitted = false; + var tempCount = 0; + var tempVariables; + var tempParameters; + var writeEmittedFiles = writeJavaScriptFile; + var emitLeadingComments = compilerOptions.removeComments ? function (node) { + } : emitLeadingDeclarationComments; + var emitTrailingComments = compilerOptions.removeComments ? function (node) { + } : emitTrailingDeclarationComments; + var emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos) { + } : emitLeadingCommentsOfLocalPosition; + var detachedCommentsInfo; + var emitDetachedComments = compilerOptions.removeComments ? function (node) { + } : emitDetachedCommentsAtPosition; + var emitPinnedOrTripleSlashComments = compilerOptions.removeComments ? function (node) { + } : emitPinnedOrTripleSlashCommentsOfNode; + var writeComment = writeCommentRange; + var emit = emitNode; + var emitStart = function (node) { + }; + var emitEnd = function (node) { + }; + var emitToken = emitTokenText; + var scopeEmitStart = function (scopeDeclaration, scopeName) { + }; + var scopeEmitEnd = function () { + }; + var sourceMapData; + function initializeEmitterWithSourceMaps() { + var sourceMapDir; + var sourceMapSourceIndex = -1; + var sourceMapNameIndexMap = {}; + var sourceMapNameIndices = []; + function getSourceMapNameIndex() { + return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + } + var lastRecordedSourceMapSpan; + var lastEncodedSourceMapSpan = { + emittedLine: 1, + emittedColumn: 1, + sourceLine: 1, + sourceColumn: 1, + sourceIndex: 0 + }; + var lastEncodedNameIndex = 0; + function encodeLastRecordedSourceMapSpan() { + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { + return; + } + var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; + if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { + if (sourceMapData.sourceMapMappings) { + sourceMapData.sourceMapMappings += ","; + } + } + else { + for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { + sourceMapData.sourceMapMappings += ";"; + } + prevEncodedEmittedColumn = 1; + } + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); + if (lastRecordedSourceMapSpan.nameIndex >= 0) { + sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); + lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; + } + lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; + sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); + function base64VLQFormatEncode(inValue) { + function base64FormatEncode(inValue) { + if (inValue < 64) { + return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); + } + throw TypeError(inValue + ": not a 64 based value"); + } + if (inValue < 0) { + inValue = ((-inValue) << 1) + 1; + } + else { + inValue = inValue << 1; + } + var encodedStr = ""; + do { + var currentDigit = inValue & 31; + inValue = inValue >> 5; + if (inValue > 0) { + currentDigit = currentDigit | 32; + } + encodedStr = encodedStr + base64FormatEncode(currentDigit); + } while (inValue > 0); + return encodedStr; + } + } + function recordSourceMapSpan(pos) { + var sourceLinePos = currentSourceFile.getLineAndCharacterFromPosition(pos); + var emittedLine = writer.getLine(); + var emittedColumn = writer.getColumn(); + if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan.emittedLine != emittedLine || lastRecordedSourceMapSpan.emittedColumn != emittedColumn || (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { + encodeLastRecordedSourceMapSpan(); + lastRecordedSourceMapSpan = { + emittedLine: emittedLine, + emittedColumn: emittedColumn, + sourceLine: sourceLinePos.line, + sourceColumn: sourceLinePos.character, + nameIndex: getSourceMapNameIndex(), + sourceIndex: sourceMapSourceIndex + }; + } + else { + lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; + lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; + lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; + } + } + function recordEmitNodeStartSpan(node) { + recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); + } + function recordEmitNodeEndSpan(node) { + recordSourceMapSpan(node.end); + } + function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { + var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + recordSourceMapSpan(tokenStartPos); + var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + recordSourceMapSpan(tokenEndPos); + return tokenEndPos; + } + function recordNewSourceFileStart(node) { + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, host.getCurrentDirectory(), host.getCanonicalFileName, true)); + sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; + sourceMapData.inputSourceFileNames.push(node.filename); + } + function recordScopeNameOfNode(node, scopeName) { + function recordScopeNameIndex(scopeNameIndex) { + sourceMapNameIndices.push(scopeNameIndex); + } + function recordScopeNameStart(scopeName) { + var scopeNameIndex = -1; + if (scopeName) { + var parentIndex = getSourceMapNameIndex(); + if (parentIndex !== -1) { + scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; + } + scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); + if (scopeNameIndex === undefined) { + scopeNameIndex = sourceMapData.sourceMapNames.length; + sourceMapData.sourceMapNames.push(scopeName); + sourceMapNameIndexMap[scopeName] = scopeNameIndex; + } + } + recordScopeNameIndex(scopeNameIndex); + } + if (scopeName) { + recordScopeNameStart(scopeName); + } + else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { + if (node.name) { + scopeName = node.name.text; + } + recordScopeNameStart(scopeName); + } + else { + recordScopeNameIndex(getSourceMapNameIndex()); + } + } + function recordScopeNameEnd() { + sourceMapNameIndices.pop(); + } + ; + function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { + recordSourceMapSpan(comment.pos); + writeCommentRange(currentSourceFile, writer, comment, newLine); + recordSourceMapSpan(comment.end); + } + function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings) { + if (typeof JSON !== "undefined") { + return JSON.stringify({ + version: version, + file: file, + sourceRoot: sourceRoot, + sources: sources, + names: names, + mappings: mappings + }); + } + return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\"}"; + function serializeStringArray(list) { + var output = ""; + for (var i = 0, n = list.length; i < n; i++) { + if (i) { + output += ","; + } + output += "\"" + ts.escapeString(list[i]) + "\""; + } + return output; + } + } + function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { + encodeLastRecordedSourceMapSpan(); + writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings), false); + sourceMapDataList.push(sourceMapData); + writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL, writeByteOrderMark); + } + var sourceMapJsFile = ts.getBaseFilename(ts.normalizeSlashes(jsFilePath)); + sourceMapData = { + sourceMapFilePath: jsFilePath + ".map", + jsSourceMappingURL: sourceMapJsFile + ".map", + sourceMapFile: sourceMapJsFile, + sourceMapSourceRoot: compilerOptions.sourceRoot || "", + sourceMapSources: [], + inputSourceFileNames: [], + sourceMapNames: [], + sourceMapMappings: "", + sourceMapDecodedMappings: [] + }; + sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); + if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { + sourceMapData.sourceMapSourceRoot += ts.directorySeparator; + } + if (compilerOptions.mapRoot) { + sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); + if (root) { + sourceMapDir = ts.getDirectoryPath(getSourceFilePathInNewDir(root, host, sourceMapDir)); + } + if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { + sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); + sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, true); + } + else { + sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); + } + } + else { + sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); + } + function emitNodeWithMap(node) { + if (node) { + if (node.kind != 207 /* SourceFile */) { + recordEmitNodeStartSpan(node); + emitNode(node); + recordEmitNodeEndSpan(node); + } + else { + recordNewSourceFileStart(node); + emitNode(node); + } + } + } + writeEmittedFiles = writeJavaScriptAndSourceMapFile; + emit = emitNodeWithMap; + emitStart = recordEmitNodeStartSpan; + emitEnd = recordEmitNodeEndSpan; + emitToken = writeTextWithSpanRecord; + scopeEmitStart = recordScopeNameOfNode; + scopeEmitEnd = recordScopeNameEnd; + writeComment = writeCommentRangeWithMap; + } + function writeJavaScriptFile(emitOutput, writeByteOrderMark) { + writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + } + function createTempVariable(location, forLoopVariable) { + var name = forLoopVariable ? "_i" : undefined; + while (true) { + if (name && resolver.isUnknownIdentifier(location, name)) { + break; + } + name = "_" + (tempCount < 25 ? String.fromCharCode(tempCount + (tempCount < 8 ? 0 : 1) + 97 /* a */) : tempCount - 25); + tempCount++; + } + var result = ts.createNode(64 /* Identifier */); + result.text = name; + return result; + } + function recordTempDeclaration(name) { + if (!tempVariables) { + tempVariables = []; + } + tempVariables.push(name); + } + function emitTempDeclarations(newLine) { + if (tempVariables) { + if (newLine) { + writeLine(); + } + else { + write(" "); + } + write("var "); + emitCommaList(tempVariables); + write(";"); + } + } + function emitTokenText(tokenKind, startPos, emitFn) { + var tokenString = ts.tokenToString(tokenKind); + if (emitFn) { + emitFn(); + } + else { + write(tokenString); + } + return startPos + tokenString.length; + } + function emitOptional(prefix, node) { + if (node) { + write(prefix); + emit(node); + } + } + function emitParenthesized(node, parenthesized) { + if (parenthesized) { + write("("); + } + emit(node); + if (parenthesized) { + write(")"); + } + } + function emitTrailingCommaIfPresent(nodeList) { + if (nodeList.hasTrailingComma) { + write(","); + } + } + function emitList(nodes, start, count, multiLine, trailingComma) { + if (multiLine) { + increaseIndent(); + } + for (var i = 0; i < count; i++) { + if (multiLine) { + if (i) { + write(","); + } + writeLine(); + } + else { + if (i) { + write(", "); + } + } + emit(nodes[start + i]); + } + if (trailingComma) { + write(","); + } + if (multiLine) { + decreaseIndent(); + writeLine(); + } + } + function emitCommaList(nodes) { + if (nodes) { + emitList(nodes, 0, nodes.length, false, false); + } + } + function emitMultiLineList(nodes) { + if (nodes) { + emitList(nodes, 0, nodes.length, true, false); + } + } + function emitLines(nodes) { + emitLinesStartingAt(nodes, 0); + } + function emitLinesStartingAt(nodes, startIndex) { + for (var i = startIndex; i < nodes.length; i++) { + writeLine(); + emit(nodes[i]); + } + } + function isBinaryOrOctalIntegerLiteral(text) { + if (text.length <= 0) { + return false; + } + if (text.charCodeAt(1) === 66 /* B */ || text.charCodeAt(1) === 98 /* b */ || text.charCodeAt(1) === 79 /* O */ || text.charCodeAt(1) === 111 /* o */) { + return true; + } + return false; + } + function emitLiteral(node) { + var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; + if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { + writer.writeLiteral(text); + } + else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { + write(node.text); + } + else { + write(text); + } + } + function getTemplateLiteralAsStringLiteral(node) { + return '"' + ts.escapeString(node.text) + '"'; + } + function emitTemplateExpression(node) { + if (compilerOptions.target >= 2 /* ES6 */) { + ts.forEachChild(node, emit); + return; + } + ts.Debug.assert(node.parent.kind !== 153 /* TaggedTemplateExpression */); + var emitOuterParens = ts.isExpression(node.parent) && templateNeedsParens(node, node.parent); + if (emitOuterParens) { + write("("); + } + emitLiteral(node.head); + ts.forEach(node.templateSpans, function (templateSpan) { + var needsParens = templateSpan.expression.kind !== 155 /* ParenthesizedExpression */ && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; + write(" + "); + emitParenthesized(templateSpan.expression, needsParens); + if (templateSpan.literal.text.length !== 0) { + write(" + "); + emitLiteral(templateSpan.literal); + } + }); + if (emitOuterParens) { + write(")"); + } + function templateNeedsParens(template, parent) { + switch (parent.kind) { + case 151 /* CallExpression */: + case 152 /* NewExpression */: + return parent.expression === template; + case 155 /* ParenthesizedExpression */: + return false; + case 153 /* TaggedTemplateExpression */: + ts.Debug.fail("Path should be unreachable; tagged templates not supported pre-ES6."); + default: + return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; + } + } + function comparePrecedenceToBinaryPlus(expression) { + ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); + switch (expression.kind) { + case 163 /* BinaryExpression */: + switch (expression.operator) { + case 35 /* AsteriskToken */: + case 36 /* SlashToken */: + case 37 /* PercentToken */: + return 1 /* GreaterThan */; + case 33 /* PlusToken */: + return 0 /* EqualTo */; + default: + return -1 /* LessThan */; + } + case 164 /* ConditionalExpression */: + return -1 /* LessThan */; + default: + return 1 /* GreaterThan */; + } + } + } + function emitTemplateSpan(span) { + emit(span.expression); + emit(span.literal); + } + function emitExpressionForPropertyName(node) { + if (node.kind === 8 /* StringLiteral */) { + emitLiteral(node); + } + else if (node.kind === 122 /* ComputedPropertyName */) { + emit(node.expression); + } + else { + write("\""); + if (node.kind === 7 /* NumericLiteral */) { + write(node.text); + } + else { + writeTextOfNode(currentSourceFile, node); + } + write("\""); + } + } + function isNotExpressionIdentifier(node) { + var parent = node.parent; + switch (parent.kind) { + case 124 /* Parameter */: + case 188 /* VariableDeclaration */: + case 146 /* BindingElement */: + case 126 /* PropertyDeclaration */: + case 125 /* PropertySignature */: + case 204 /* PropertyAssignment */: + case 205 /* ShorthandPropertyAssignment */: + case 206 /* EnumMember */: + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + case 190 /* FunctionDeclaration */: + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + case 156 /* FunctionExpression */: + case 191 /* ClassDeclaration */: + case 192 /* InterfaceDeclaration */: + case 194 /* EnumDeclaration */: + case 195 /* ModuleDeclaration */: + case 197 /* ImportDeclaration */: + return parent.name === node; + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: + case 198 /* ExportAssignment */: + return false; + case 184 /* LabeledStatement */: + return node.parent.label === node; + case 203 /* CatchClause */: + return node.parent.name === node; + } + } + function emitExpressionIdentifier(node) { + var prefix = resolver.getExpressionNamePrefix(node); + if (prefix) { + write(prefix); + write("."); + } + writeTextOfNode(currentSourceFile, node); + } + function emitIdentifier(node) { + if (!node.parent) { + write(node.text); + } + else if (!isNotExpressionIdentifier(node)) { + emitExpressionIdentifier(node); + } + else { + writeTextOfNode(currentSourceFile, node); + } + } + function emitThis(node) { + if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { + write("_this"); + } + else { + write("this"); + } + } + function emitSuper(node) { + var flags = resolver.getNodeCheckFlags(node); + if (flags & 16 /* SuperInstance */) { + write("_super.prototype"); + } + else if (flags & 32 /* SuperStatic */) { + write("_super"); + } + else { + write("super"); + } + } + function emitObjectBindingPattern(node) { + write("{ "); + var elements = node.elements; + emitList(elements, 0, elements.length, false, elements.hasTrailingComma); + write(" }"); + } + function emitArrayBindingPattern(node) { + write("["); + var elements = node.elements; + emitList(elements, 0, elements.length, false, elements.hasTrailingComma); + write("]"); + } + function emitBindingElement(node) { + if (node.propertyName) { + emit(node.propertyName); + write(": "); + } + if (node.dotDotDotToken) { + write("..."); + } + if (ts.isBindingPattern(node.name)) { + emit(node.name); + } + else { + emitModuleMemberName(node); + } + emitOptional(" = ", node.initializer); + } + function emitSpreadElementExpression(node) { + write("..."); + emit(node.expression); + } + function needsParenthesisForPropertyAccess(node) { + switch (node.kind) { + case 64 /* Identifier */: + case 147 /* ArrayLiteralExpression */: + case 149 /* PropertyAccessExpression */: + case 150 /* ElementAccessExpression */: + case 151 /* CallExpression */: + case 155 /* ParenthesizedExpression */: + return false; + } + return true; + } + function emitArrayLiteral(node) { + var elements = node.elements; + var length = elements.length; + if (length === 0) { + write("[]"); + return; + } + if (compilerOptions.target >= 2 /* ES6 */) { + write("["); + emitList(elements, 0, elements.length, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); + write("]"); + return; + } + var pos = 0; + var group = 0; + while (pos < length) { + if (group === 1) { + write(".concat("); + } + else if (group > 1) { + write(", "); + } + var e = elements[pos]; + if (e.kind === 167 /* SpreadElementExpression */) { + e = e.expression; + emitParenthesized(e, group === 0 && needsParenthesisForPropertyAccess(e)); + pos++; + } + else { + var i = pos; + while (i < length && elements[i].kind !== 167 /* SpreadElementExpression */) { + i++; + } + write("["); + emitList(elements, pos, i - pos, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); + write("]"); + pos = i; + } + group++; + } + if (group > 1) { + write(")"); + } + } + function emitObjectLiteral(node) { + write("{"); + var properties = node.properties; + if (properties.length) { + var multiLine = (node.flags & 256 /* MultiLine */) !== 0; + if (!multiLine) { + write(" "); + } + emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && compilerOptions.target >= 1 /* ES5 */); + if (!multiLine) { + write(" "); + } + } + write("}"); + } + function emitComputedPropertyName(node) { + write("["); + emit(node.expression); + write("]"); + } + function emitMethod(node) { + if (!ts.isObjectLiteralMethod(node)) { + return; + } + emitLeadingComments(node); + emit(node.name); + if (compilerOptions.target < 2 /* ES6 */) { + write(": function "); + } + emitSignatureAndBody(node); + emitTrailingComments(node); + } + function emitPropertyAssignment(node) { + emitLeadingComments(node); + emit(node.name); + write(": "); + emit(node.initializer); + emitTrailingComments(node); + } + function emitShorthandPropertyAssignment(node) { + emitLeadingComments(node); + emit(node.name); + if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { + write(": "); + emitExpressionIdentifier(node.name); + } + emitTrailingComments(node); + } + function tryEmitConstantValue(node) { + var constantValue = resolver.getConstantValue(node); + if (constantValue !== undefined) { + var propertyName = node.kind === 149 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); + write(constantValue.toString() + " /* " + propertyName + " */"); + return true; + } + return false; + } + function emitPropertyAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + write("."); + emit(node.name); + } + function emitQualifiedName(node) { + emit(node.left); + write("."); + emit(node.right); + } + function emitIndexedAccess(node) { + if (tryEmitConstantValue(node)) { + return; + } + emit(node.expression); + write("["); + emit(node.argumentExpression); + write("]"); + } + function emitCallExpression(node) { + var superCall = false; + if (node.expression.kind === 90 /* SuperKeyword */) { + write("_super"); + superCall = true; + } + else { + emit(node.expression); + superCall = node.expression.kind === 149 /* PropertyAccessExpression */ && node.expression.expression.kind === 90 /* SuperKeyword */; + } + if (superCall) { + write(".call("); + emitThis(node.expression); + if (node.arguments.length) { + write(", "); + emitCommaList(node.arguments); + } + write(")"); + } + else { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitNewExpression(node) { + write("new "); + emit(node.expression); + if (node.arguments) { + write("("); + emitCommaList(node.arguments); + write(")"); + } + } + function emitTaggedTemplateExpression(node) { + ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); + emit(node.tag); + write(" "); + emit(node.template); + } + function emitParenExpression(node) { + if (node.expression.kind === 154 /* TypeAssertionExpression */) { + var operand = node.expression.expression; + while (operand.kind == 154 /* TypeAssertionExpression */) { + operand = operand.expression; + } + if (operand.kind !== 161 /* PrefixUnaryExpression */ && operand.kind !== 160 /* VoidExpression */ && operand.kind !== 159 /* TypeOfExpression */ && operand.kind !== 158 /* DeleteExpression */ && operand.kind !== 162 /* PostfixUnaryExpression */ && operand.kind !== 152 /* NewExpression */ && !(operand.kind === 151 /* CallExpression */ && node.parent.kind === 152 /* NewExpression */) && !(operand.kind === 156 /* FunctionExpression */ && node.parent.kind === 151 /* CallExpression */)) { + emit(operand); + return; + } + } + write("("); + emit(node.expression); + write(")"); + } + function emitDeleteExpression(node) { + write(ts.tokenToString(73 /* DeleteKeyword */)); + write(" "); + emit(node.expression); + } + function emitVoidExpression(node) { + write(ts.tokenToString(98 /* VoidKeyword */)); + write(" "); + emit(node.expression); + } + function emitTypeOfExpression(node) { + write(ts.tokenToString(96 /* TypeOfKeyword */)); + write(" "); + emit(node.expression); + } + function emitPrefixUnaryExpression(node) { + write(ts.tokenToString(node.operator)); + if (node.operand.kind === 161 /* PrefixUnaryExpression */) { + var operand = node.operand; + if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { + write(" "); + } + else if (node.operator === 34 /* MinusToken */ && (operand.operator === 34 /* MinusToken */ || operand.operator === 39 /* MinusMinusToken */)) { + write(" "); + } + } + emit(node.operand); + } + function emitPostfixUnaryExpression(node) { + emit(node.operand); + write(ts.tokenToString(node.operator)); + } + function emitBinaryExpression(node) { + if (compilerOptions.target < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { + emitDestructuring(node); + } + else { + emit(node.left); + if (node.operator !== 23 /* CommaToken */) + write(" "); + write(ts.tokenToString(node.operator)); + write(" "); + emit(node.right); + } + } + function emitConditionalExpression(node) { + emit(node.condition); + write(" ? "); + emit(node.whenTrue); + write(" : "); + emit(node.whenFalse); + } + function emitBlock(node) { + emitToken(14 /* OpenBraceToken */, node.pos); + increaseIndent(); + scopeEmitStart(node.parent); + if (node.kind === 196 /* ModuleBlock */) { + ts.Debug.assert(node.parent.kind === 195 /* ModuleDeclaration */); + emitCaptureThisForNodeIfNecessary(node.parent); + } + emitLines(node.statements); + if (node.kind === 196 /* ModuleBlock */) { + emitTempDeclarations(true); + } + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.statements.end); + scopeEmitEnd(); + } + function emitEmbeddedStatement(node) { + if (node.kind === 170 /* Block */) { + write(" "); + emit(node); + } + else { + increaseIndent(); + writeLine(); + emit(node); + decreaseIndent(); + } + } + function emitExpressionStatement(node) { + emitLeadingComments(node); + emitParenthesized(node.expression, node.expression.kind === 157 /* ArrowFunction */); + write(";"); + emitTrailingComments(node); + } + function emitIfStatement(node) { + emitLeadingComments(node); + var endPos = emitToken(83 /* IfKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + emit(node.expression); + emitToken(17 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.thenStatement); + if (node.elseStatement) { + writeLine(); + emitToken(75 /* ElseKeyword */, node.thenStatement.end); + if (node.elseStatement.kind === 174 /* IfStatement */) { + write(" "); + emit(node.elseStatement); + } + else { + emitEmbeddedStatement(node.elseStatement); + } + } + emitTrailingComments(node); + } + function emitDoStatement(node) { + write("do"); + emitEmbeddedStatement(node.statement); + if (node.statement.kind === 170 /* Block */) { + write(" "); + } + else { + writeLine(); + } + write("while ("); + emit(node.expression); + write(");"); + } + function emitWhileStatement(node) { + write("while ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForStatement(node) { + var endPos = emitToken(81 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + if (node.initializer && node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + var declarations = variableDeclarationList.declarations; + if (declarations[0] && ts.isLet(declarations[0])) { + emitToken(103 /* LetKeyword */, endPos); + } + else if (declarations[0] && ts.isConst(declarations[0])) { + emitToken(69 /* ConstKeyword */, endPos); + } + else { + emitToken(97 /* VarKeyword */, endPos); + } + write(" "); + emitCommaList(variableDeclarationList.declarations); + } + else if (node.initializer) { + emit(node.initializer); + } + write(";"); + emitOptional(" ", node.condition); + write(";"); + emitOptional(" ", node.iterator); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitForInStatement(node) { + var endPos = emitToken(81 /* ForKeyword */, node.pos); + write(" "); + endPos = emitToken(16 /* OpenParenToken */, endPos); + if (node.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; + if (ts.isLet(decl)) { + emitToken(103 /* LetKeyword */, endPos); + } + else { + emitToken(97 /* VarKeyword */, endPos); + } + write(" "); + emit(decl); + } + } + else { + emit(node.initializer); + } + write(" in "); + emit(node.expression); + emitToken(17 /* CloseParenToken */, node.expression.end); + emitEmbeddedStatement(node.statement); + } + function emitBreakOrContinueStatement(node) { + emitToken(node.kind === 180 /* BreakStatement */ ? 65 /* BreakKeyword */ : 70 /* ContinueKeyword */, node.pos); + emitOptional(" ", node.label); + write(";"); + } + function emitReturnStatement(node) { + emitLeadingComments(node); + emitToken(89 /* ReturnKeyword */, node.pos); + emitOptional(" ", node.expression); + write(";"); + emitTrailingComments(node); + } + function emitWithStatement(node) { + write("with ("); + emit(node.expression); + write(")"); + emitEmbeddedStatement(node.statement); + } + function emitSwitchStatement(node) { + var endPos = emitToken(91 /* SwitchKeyword */, node.pos); + write(" "); + emitToken(16 /* OpenParenToken */, endPos); + emit(node.expression); + endPos = emitToken(17 /* CloseParenToken */, node.expression.end); + write(" "); + emitToken(14 /* OpenBraceToken */, endPos); + increaseIndent(); + emitLines(node.clauses); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.clauses.end); + } + function isOnSameLine(node1, node2) { + return getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); + } + function emitCaseOrDefaultClause(node) { + if (node.kind === 200 /* CaseClause */) { + write("case "); + emit(node.expression); + write(":"); + } + else { + write("default:"); + } + if (node.statements.length === 1 && isOnSameLine(node, node.statements[0])) { + write(" "); + emit(node.statements[0]); + } + else { + increaseIndent(); + emitLines(node.statements); + decreaseIndent(); + } + } + function emitThrowStatement(node) { + write("throw "); + emit(node.expression); + write(";"); + } + function emitTryStatement(node) { + write("try "); + emit(node.tryBlock); + emit(node.catchClause); + if (node.finallyBlock) { + writeLine(); + write("finally "); + emit(node.finallyBlock); + } + } + function emitCatchClause(node) { + writeLine(); + var endPos = emitToken(67 /* CatchKeyword */, node.pos); + write(" "); + emitToken(16 /* OpenParenToken */, endPos); + emit(node.name); + emitToken(17 /* CloseParenToken */, node.name.end); + write(" "); + emitBlock(node.block); + } + function emitDebuggerStatement(node) { + emitToken(71 /* DebuggerKeyword */, node.pos); + write(";"); + } + function emitLabelledStatement(node) { + emit(node.label); + write(": "); + emit(node.statement); + } + function getContainingModule(node) { + do { + node = node.parent; + } while (node && node.kind !== 195 /* ModuleDeclaration */); + return node; + } + function emitModuleMemberName(node) { + emitStart(node.name); + if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + var container = getContainingModule(node); + write(container ? resolver.getLocalNameOfContainer(container) : "exports"); + write("."); + } + emitNode(node.name); + emitEnd(node.name); + } + function emitDestructuring(root, value) { + var emitCount = 0; + var isDeclaration = (root.kind === 188 /* VariableDeclaration */ && !(ts.getCombinedNodeFlags(root) & 1 /* Export */)) || root.kind === 124 /* Parameter */; + if (root.kind === 163 /* BinaryExpression */) { + emitAssignmentExpression(root); + } + else { + emitBindingElement(root, value); + } + function emitAssignment(name, value) { + if (emitCount++) { + write(", "); + } + if (name.parent && (name.parent.kind === 188 /* VariableDeclaration */ || name.parent.kind === 146 /* BindingElement */)) { + emitModuleMemberName(name.parent); + } + else { + emit(name); + } + write(" = "); + emit(value); + } + function ensureIdentifier(expr) { + if (expr.kind !== 64 /* Identifier */) { + var identifier = createTempVariable(root); + if (!isDeclaration) { + recordTempDeclaration(identifier); + } + emitAssignment(identifier, expr); + expr = identifier; + } + return expr; + } + function createVoidZero() { + var zero = ts.createNode(7 /* NumericLiteral */); + zero.text = "0"; + var result = ts.createNode(160 /* VoidExpression */); + result.expression = zero; + return result; + } + function createDefaultValueCheck(value, defaultValue) { + value = ensureIdentifier(value); + var equals = ts.createNode(163 /* BinaryExpression */); + equals.left = value; + equals.operator = 30 /* EqualsEqualsEqualsToken */; + equals.right = createVoidZero(); + var cond = ts.createNode(164 /* ConditionalExpression */); + cond.condition = equals; + cond.whenTrue = defaultValue; + cond.whenFalse = value; + return cond; + } + function createNumericLiteral(value) { + var node = ts.createNode(7 /* NumericLiteral */); + node.text = "" + value; + return node; + } + function parenthesizeForAccess(expr) { + if (expr.kind === 64 /* Identifier */ || expr.kind === 149 /* PropertyAccessExpression */ || expr.kind === 150 /* ElementAccessExpression */) { + return expr; + } + var node = ts.createNode(155 /* ParenthesizedExpression */); + node.expression = expr; + return node; + } + function createPropertyAccess(object, propName) { + if (propName.kind !== 64 /* Identifier */) { + return createElementAccess(object, propName); + } + var node = ts.createNode(149 /* PropertyAccessExpression */); + node.expression = parenthesizeForAccess(object); + node.name = propName; + return node; + } + function createElementAccess(object, index) { + var node = ts.createNode(150 /* ElementAccessExpression */); + node.expression = parenthesizeForAccess(object); + node.argumentExpression = index; + return node; + } + function emitObjectLiteralAssignment(target, value) { + var properties = target.properties; + if (properties.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < properties.length; i++) { + var p = properties[i]; + if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { + var propName = (p.name); + emitDestructuringAssignment(p.initializer || propName, createPropertyAccess(value, propName)); + } + } + } + function emitArrayLiteralAssignment(target, value) { + var elements = target.elements; + if (elements.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < elements.length; i++) { + var e = elements[i]; + if (e.kind !== 168 /* OmittedExpression */) { + if (e.kind !== 167 /* SpreadElementExpression */) { + emitDestructuringAssignment(e, createElementAccess(value, createNumericLiteral(i))); + } + else { + if (i === elements.length - 1) { + value = ensureIdentifier(value); + emitAssignment(e.expression, value); + write(".slice(" + i + ")"); + } + } + } + } + } + function emitDestructuringAssignment(target, value) { + if (target.kind === 163 /* BinaryExpression */ && target.operator === 52 /* EqualsToken */) { + value = createDefaultValueCheck(value, target.right); + target = target.left; + } + if (target.kind === 148 /* ObjectLiteralExpression */) { + emitObjectLiteralAssignment(target, value); + } + else if (target.kind === 147 /* ArrayLiteralExpression */) { + emitArrayLiteralAssignment(target, value); + } + else { + emitAssignment(target, value); + } + } + function emitAssignmentExpression(root) { + var target = root.left; + var value = root.right; + if (root.parent.kind === 173 /* ExpressionStatement */) { + emitDestructuringAssignment(target, value); + } + else { + if (root.parent.kind !== 155 /* ParenthesizedExpression */) { + write("("); + } + value = ensureIdentifier(value); + emitDestructuringAssignment(target, value); + write(", "); + emit(value); + if (root.parent.kind !== 155 /* ParenthesizedExpression */) { + write(")"); + } + } + } + function emitBindingElement(target, value) { + if (target.initializer) { + value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; + } + else if (!value) { + value = createVoidZero(); + } + if (ts.isBindingPattern(target.name)) { + var pattern = target.name; + var elements = pattern.elements; + if (elements.length !== 1) { + value = ensureIdentifier(value); + } + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + if (pattern.kind === 144 /* ObjectBindingPattern */) { + var propName = element.propertyName || element.name; + emitBindingElement(element, createPropertyAccess(value, propName)); + } + else if (element.kind !== 168 /* OmittedExpression */) { + if (!element.dotDotDotToken) { + emitBindingElement(element, createElementAccess(value, createNumericLiteral(i))); + } + else { + if (i === elements.length - 1) { + value = ensureIdentifier(value); + emitAssignment(element.name, value); + write(".slice(" + i + ")"); + } + } + } + } + } + else { + emitAssignment(target.name, value); + } + } + } + function emitVariableDeclaration(node) { + emitLeadingComments(node); + if (ts.isBindingPattern(node.name)) { + if (compilerOptions.target < 2 /* ES6 */) { + emitDestructuring(node); + } + else { + emit(node.name); + emitOptional(" = ", node.initializer); + } + } + else { + emitModuleMemberName(node); + emitOptional(" = ", node.initializer); + } + emitTrailingComments(node); + } + function emitVariableStatement(node) { + emitLeadingComments(node); + if (!(node.flags & 1 /* Export */)) { + if (ts.isLet(node.declarationList)) { + write("let "); + } + else if (ts.isConst(node.declarationList)) { + write("const "); + } + else { + write("var "); + } + } + emitCommaList(node.declarationList.declarations); + write(";"); + emitTrailingComments(node); + } + function emitParameter(node) { + emitLeadingComments(node); + if (compilerOptions.target < 2 /* ES6 */) { + if (ts.isBindingPattern(node.name)) { + var name = createTempVariable(node); + if (!tempParameters) { + tempParameters = []; + } + tempParameters.push(name); + emit(name); + } + else { + emit(node.name); + } + } + else { + if (node.dotDotDotToken) { + write("..."); + } + emit(node.name); + emitOptional(" = ", node.initializer); + } + emitTrailingComments(node); + } + function emitDefaultValueAssignments(node) { + if (compilerOptions.target < 2 /* ES6 */) { + var tempIndex = 0; + ts.forEach(node.parameters, function (p) { + if (ts.isBindingPattern(p.name)) { + writeLine(); + write("var "); + emitDestructuring(p, tempParameters[tempIndex]); + write(";"); + tempIndex++; + } + else if (p.initializer) { + writeLine(); + emitStart(p); + write("if ("); + emitNode(p.name); + write(" === void 0)"); + emitEnd(p); + write(" { "); + emitStart(p); + emitNode(p.name); + write(" = "); + emitNode(p.initializer); + emitEnd(p); + write("; }"); + } + }); + } + } + function emitRestParameter(node) { + if (compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node)) { + var restIndex = node.parameters.length - 1; + var restParam = node.parameters[restIndex]; + var tempName = createTempVariable(node, true).text; + writeLine(); + emitLeadingComments(restParam); + emitStart(restParam); + write("var "); + emitNode(restParam.name); + write(" = [];"); + emitEnd(restParam); + emitTrailingComments(restParam); + writeLine(); + write("for ("); + emitStart(restParam); + write("var " + tempName + " = " + restIndex + ";"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + " < arguments.length;"); + emitEnd(restParam); + write(" "); + emitStart(restParam); + write(tempName + "++"); + emitEnd(restParam); + write(") {"); + increaseIndent(); + writeLine(); + emitStart(restParam); + emitNode(restParam.name); + write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); + emitEnd(restParam); + decreaseIndent(); + writeLine(); + write("}"); + } + } + function emitAccessor(node) { + emitLeadingComments(node); + write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); + emit(node.name); + emitSignatureAndBody(node); + emitTrailingComments(node); + } + function emitFunctionDeclaration(node) { + if (ts.nodeIsMissing(node.body)) { + return emitPinnedOrTripleSlashComments(node); + } + if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + emitLeadingComments(node); + } + write("function "); + if (node.kind === 190 /* FunctionDeclaration */ || (node.kind === 156 /* FunctionExpression */ && node.name)) { + emit(node.name); + } + emitSignatureAndBody(node); + if (node.kind !== 128 /* MethodDeclaration */ && node.kind !== 127 /* MethodSignature */) { + emitTrailingComments(node); + } + } + function emitCaptureThisForNodeIfNecessary(node) { + if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { + writeLine(); + emitStart(node); + write("var _this = this;"); + emitEnd(node); + } + } + function emitSignatureParameters(node) { + increaseIndent(); + write("("); + if (node) { + var parameters = node.parameters; + var omitCount = compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + emitList(parameters, 0, parameters.length - omitCount, false, false); + } + write(")"); + decreaseIndent(); + } + function emitSignatureAndBody(node) { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempCount = 0; + tempVariables = undefined; + tempParameters = undefined; + emitSignatureParameters(node); + write(" {"); + scopeEmitStart(node); + increaseIndent(); + emitDetachedComments(node.body.kind === 170 /* Block */ ? node.body.statements : node.body); + var startIndex = 0; + if (node.body.kind === 170 /* Block */) { + startIndex = emitDirectivePrologues(node.body.statements, true); + } + var outPos = writer.getTextPos(); + emitCaptureThisForNodeIfNecessary(node); + emitDefaultValueAssignments(node); + emitRestParameter(node); + if (node.body.kind !== 170 /* Block */ && outPos === writer.getTextPos()) { + decreaseIndent(); + write(" "); + emitStart(node.body); + write("return "); + emitNode(node.body); + emitEnd(node.body); + write(";"); + emitTempDeclarations(false); + write(" "); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + else { + if (node.body.kind === 170 /* Block */) { + emitLinesStartingAt(node.body.statements, startIndex); + } + else { + writeLine(); + emitLeadingComments(node.body); + write("return "); + emit(node.body); + write(";"); + emitTrailingComments(node.body); + } + emitTempDeclarations(true); + writeLine(); + if (node.body.kind === 170 /* Block */) { + emitLeadingCommentsOfPosition(node.body.statements.end); + decreaseIndent(); + emitToken(15 /* CloseBraceToken */, node.body.statements.end); + } + else { + decreaseIndent(); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + } + scopeEmitEnd(); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + tempCount = saveTempCount; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + function findInitialSuperCall(ctor) { + if (ctor.body) { + var statement = ctor.body.statements[0]; + if (statement && statement.kind === 173 /* ExpressionStatement */) { + var expr = statement.expression; + if (expr && expr.kind === 151 /* CallExpression */) { + var func = expr.expression; + if (func && func.kind === 90 /* SuperKeyword */) { + return statement; + } + } + } + } + } + function emitParameterPropertyAssignments(node) { + ts.forEach(node.parameters, function (param) { + if (param.flags & 112 /* AccessibilityModifier */) { + writeLine(); + emitStart(param); + emitStart(param.name); + write("this."); + emitNode(param.name); + emitEnd(param.name); + write(" = "); + emit(param.name); + write(";"); + emitEnd(param); + } + }); + } + function emitMemberAccessForPropertyName(memberName) { + if (memberName.kind === 8 /* StringLiteral */ || memberName.kind === 7 /* NumericLiteral */) { + write("["); + emitNode(memberName); + write("]"); + } + else if (memberName.kind === 122 /* ComputedPropertyName */) { + emitComputedPropertyName(memberName); + } + else { + write("."); + emitNode(memberName); + } + } + function emitMemberAssignments(node, staticFlag) { + ts.forEach(node.members, function (member) { + if (member.kind === 126 /* PropertyDeclaration */ && (member.flags & 128 /* Static */) === staticFlag && member.initializer) { + writeLine(); + emitLeadingComments(member); + emitStart(member); + emitStart(member.name); + if (staticFlag) { + emitNode(node.name); + } + else { + write("this"); + } + emitMemberAccessForPropertyName(member.name); + emitEnd(member.name); + write(" = "); + emit(member.initializer); + write(";"); + emitEnd(member); + emitTrailingComments(member); + } + }); + } + function emitMemberFunctions(node) { + ts.forEach(node.members, function (member) { + if (member.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */) { + if (!member.body) { + return emitPinnedOrTripleSlashComments(member); + } + writeLine(); + emitLeadingComments(member); + emitStart(member); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 128 /* Static */)) { + write(".prototype"); + } + emitMemberAccessForPropertyName(member.name); + emitEnd(member.name); + write(" = "); + emitStart(member); + emitFunctionDeclaration(member); + emitEnd(member); + emitEnd(member); + write(";"); + emitTrailingComments(member); + } + else if (member.kind === 130 /* GetAccessor */ || member.kind === 131 /* SetAccessor */) { + var accessors = getAllAccessorDeclarations(node, member); + if (member === accessors.firstAccessor) { + writeLine(); + emitStart(member); + write("Object.defineProperty("); + emitStart(member.name); + emitNode(node.name); + if (!(member.flags & 128 /* Static */)) { + write(".prototype"); + } + write(", "); + emitExpressionForPropertyName(member.name); + emitEnd(member.name); + write(", {"); + increaseIndent(); + if (accessors.getAccessor) { + writeLine(); + emitLeadingComments(accessors.getAccessor); + write("get: "); + emitStart(accessors.getAccessor); + write("function "); + emitSignatureAndBody(accessors.getAccessor); + emitEnd(accessors.getAccessor); + emitTrailingComments(accessors.getAccessor); + write(","); + } + if (accessors.setAccessor) { + writeLine(); + emitLeadingComments(accessors.setAccessor); + write("set: "); + emitStart(accessors.setAccessor); + write("function "); + emitSignatureAndBody(accessors.setAccessor); + emitEnd(accessors.setAccessor); + emitTrailingComments(accessors.setAccessor); + write(","); + } + writeLine(); + write("enumerable: true,"); + writeLine(); + write("configurable: true"); + decreaseIndent(); + writeLine(); + write("});"); + emitEnd(member); + } + } + }); + } + function emitClassDeclaration(node) { + emitLeadingComments(node); + write("var "); + emit(node.name); + write(" = (function ("); + var baseTypeNode = ts.getClassBaseTypeNode(node); + if (baseTypeNode) { + write("_super"); + } + write(") {"); + increaseIndent(); + scopeEmitStart(node); + if (baseTypeNode) { + writeLine(); + emitStart(baseTypeNode); + write("__extends("); + emit(node.name); + write(", _super);"); + emitEnd(baseTypeNode); + } + writeLine(); + emitConstructorOfClass(); + emitMemberFunctions(node); + emitMemberAssignments(node, 128 /* Static */); + writeLine(); + function emitClassReturnStatement() { + write("return "); + emitNode(node.name); + } + emitToken(15 /* CloseBraceToken */, node.members.end, emitClassReturnStatement); + write(";"); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + emitStart(node); + write(")("); + if (baseTypeNode) { + emit(baseTypeNode.typeName); + } + write(");"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + emitEnd(node); + write(";"); + } + emitTrailingComments(node); + function emitConstructorOfClass() { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + var saveTempParameters = tempParameters; + tempCount = 0; + tempVariables = undefined; + tempParameters = undefined; + ts.forEach(node.members, function (member) { + if (member.kind === 129 /* Constructor */ && !member.body) { + emitPinnedOrTripleSlashComments(member); + } + }); + var ctor = getFirstConstructorWithBody(node); + if (ctor) { + emitLeadingComments(ctor); + } + emitStart(ctor || node); + write("function "); + emit(node.name); + emitSignatureParameters(ctor); + write(" {"); + scopeEmitStart(node, "constructor"); + increaseIndent(); + if (ctor) { + emitDetachedComments(ctor.body.statements); + } + emitCaptureThisForNodeIfNecessary(node); + if (ctor) { + emitDefaultValueAssignments(ctor); + emitRestParameter(ctor); + if (baseTypeNode) { + var superCall = findInitialSuperCall(ctor); + if (superCall) { + writeLine(); + emit(superCall); + } + } + emitParameterPropertyAssignments(ctor); + } + else { + if (baseTypeNode) { + writeLine(); + emitStart(baseTypeNode); + write("_super.apply(this, arguments);"); + emitEnd(baseTypeNode); + } + } + emitMemberAssignments(node, 0); + if (ctor) { + var statements = ctor.body.statements; + if (superCall) + statements = statements.slice(1); + emitLines(statements); + } + emitTempDeclarations(true); + writeLine(); + if (ctor) { + emitLeadingCommentsOfPosition(ctor.body.statements.end); + } + decreaseIndent(); + emitToken(15 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); + scopeEmitEnd(); + emitEnd(ctor || node); + if (ctor) { + emitTrailingComments(ctor); + } + tempCount = saveTempCount; + tempVariables = saveTempVariables; + tempParameters = saveTempParameters; + } + } + function emitInterfaceDeclaration(node) { + emitPinnedOrTripleSlashComments(node); + } + function emitEnumDeclaration(node) { + var isConstEnum = ts.isConst(node); + if (isConstEnum && !compilerOptions.preserveConstEnums) { + return; + } + emitLeadingComments(node); + if (!(node.flags & 1 /* Export */)) { + emitStart(node); + write("var "); + emit(node.name); + emitEnd(node); + write(";"); + } + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") {"); + increaseIndent(); + scopeEmitStart(node); + emitEnumMemberDeclarations(isConstEnum); + decreaseIndent(); + writeLine(); + emitToken(15 /* CloseBraceToken */, node.members.end); + scopeEmitEnd(); + write(")("); + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + if (node.flags & 1 /* Export */) { + writeLine(); + emitStart(node); + write("var "); + emit(node.name); + write(" = "); + emitModuleMemberName(node); + emitEnd(node); + write(";"); + } + emitTrailingComments(node); + function emitEnumMemberDeclarations(isConstEnum) { + ts.forEach(node.members, function (member) { + writeLine(); + emitLeadingComments(member); + emitStart(member); + write(resolver.getLocalNameOfContainer(node)); + write("["); + write(resolver.getLocalNameOfContainer(node)); + write("["); + emitExpressionForPropertyName(member.name); + write("] = "); + if (member.initializer && !isConstEnum) { + emit(member.initializer); + } + else { + write(resolver.getEnumMemberValue(member).toString()); + } + write("] = "); + emitExpressionForPropertyName(member.name); + emitEnd(member); + write(";"); + emitTrailingComments(member); + }); + } + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { + if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { + var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + return recursiveInnerModule || moduleDeclaration.body; + } + } + function emitModuleDeclaration(node) { + var shouldEmit = ts.getModuleInstanceState(node) === 1 /* Instantiated */ || (ts.getModuleInstanceState(node) === 2 /* ConstEnumOnly */ && compilerOptions.preserveConstEnums); + if (!shouldEmit) { + return emitPinnedOrTripleSlashComments(node); + } + emitLeadingComments(node); + emitStart(node); + write("var "); + emit(node.name); + write(";"); + emitEnd(node); + writeLine(); + emitStart(node); + write("(function ("); + emitStart(node.name); + write(resolver.getLocalNameOfContainer(node)); + emitEnd(node.name); + write(") "); + if (node.body.kind === 196 /* ModuleBlock */) { + var saveTempCount = tempCount; + var saveTempVariables = tempVariables; + tempCount = 0; + tempVariables = undefined; + emit(node.body); + tempCount = saveTempCount; + tempVariables = saveTempVariables; + } + else { + write("{"); + increaseIndent(); + scopeEmitStart(node); + emitCaptureThisForNodeIfNecessary(node); + writeLine(); + emit(node.body); + decreaseIndent(); + writeLine(); + var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + emitToken(15 /* CloseBraceToken */, moduleBlock.statements.end); + scopeEmitEnd(); + } + write(")("); + if (node.flags & 1 /* Export */) { + emit(node.name); + write(" = "); + } + emitModuleMemberName(node); + write(" || ("); + emitModuleMemberName(node); + write(" = {}));"); + emitEnd(node); + emitTrailingComments(node); + } + function emitImportDeclaration(node) { + var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); + if (!emitImportDeclaration) { + emitImportDeclaration = !ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportWithEntityName(node); + } + if (emitImportDeclaration) { + if (ts.isExternalModuleImportDeclaration(node) && node.parent.kind === 207 /* SourceFile */ && compilerOptions.module === 2 /* AMD */) { + if (node.flags & 1 /* Export */) { + writeLine(); + emitLeadingComments(node); + emitStart(node); + emitModuleMemberName(node); + write(" = "); + emit(node.name); + write(";"); + emitEnd(node); + emitTrailingComments(node); + } + } + else { + writeLine(); + emitLeadingComments(node); + emitStart(node); + if (!(node.flags & 1 /* Export */)) + write("var "); + emitModuleMemberName(node); + write(" = "); + if (ts.isInternalModuleImportDeclaration(node)) { + emit(node.moduleReference); + } + else { + var literal = ts.getExternalModuleImportDeclarationExpression(node); + write("require("); + emitStart(literal); + emitLiteral(literal); + emitEnd(literal); + emitToken(17 /* CloseParenToken */, literal.end); + } + write(";"); + emitEnd(node); + emitTrailingComments(node); + } + } + } + function getExternalImportDeclarations(node) { + var result = []; + ts.forEach(node.statements, function (statement) { + if (ts.isExternalModuleImportDeclaration(statement) && resolver.isReferencedImportDeclaration(statement)) { + result.push(statement); + } + }); + return result; + } + function getFirstExportAssignment(sourceFile) { + return ts.forEach(sourceFile.statements, function (node) { + if (node.kind === 198 /* ExportAssignment */) { + return node; + } + }); + } + function emitAMDModule(node, startIndex) { + var imports = getExternalImportDeclarations(node); + writeLine(); + write("define("); + if (node.amdModuleName) { + write("\"" + node.amdModuleName + "\", "); + } + write("[\"require\", \"exports\""); + ts.forEach(imports, function (imp) { + write(", "); + emitLiteral(ts.getExternalModuleImportDeclarationExpression(imp)); + }); + ts.forEach(node.amdDependencies, function (amdDependency) { + var text = "\"" + amdDependency + "\""; + write(", "); + write(text); + }); + write("], function (require, exports"); + ts.forEach(imports, function (imp) { + write(", "); + emit(imp.name); + }); + write(") {"); + increaseIndent(); + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignment = getFirstExportAssignment(node); + emitStart(exportAssignment); + write("return "); + emitStart(exportAssignment.exportName); + write(exportName); + emitEnd(exportAssignment.exportName); + write(";"); + emitEnd(exportAssignment); + } + decreaseIndent(); + writeLine(); + write("});"); + } + function emitCommonJSModule(node, startIndex) { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + var exportName = resolver.getExportAssignmentName(node); + if (exportName) { + writeLine(); + var exportAssignment = getFirstExportAssignment(node); + emitStart(exportAssignment); + write("module.exports = "); + emitStart(exportAssignment.exportName); + write(exportName); + emitEnd(exportAssignment.exportName); + write(";"); + emitEnd(exportAssignment); + } + } + function emitDirectivePrologues(statements, startWithNewLine) { + for (var i = 0; i < statements.length; ++i) { + if (ts.isPrologueDirective(statements[i])) { + if (startWithNewLine || i > 0) { + writeLine(); + } + emit(statements[i]); + } + else { + return i; + } + } + return statements.length; + } + function emitSourceFile(node) { + currentSourceFile = node; + writeLine(); + emitDetachedComments(node); + var startIndex = emitDirectivePrologues(node.statements, false); + if (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */) { + writeLine(); + write("var __extends = this.__extends || function (d, b) {"); + increaseIndent(); + writeLine(); + write("for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];"); + writeLine(); + write("function __() { this.constructor = d; }"); + writeLine(); + write("__.prototype = b.prototype;"); + writeLine(); + write("d.prototype = new __();"); + decreaseIndent(); + writeLine(); + write("};"); + extendsEmitted = true; + } + if (ts.isExternalModule(node)) { + if (compilerOptions.module === 2 /* AMD */) { + emitAMDModule(node, startIndex); + } + else { + emitCommonJSModule(node, startIndex); + } + } + else { + emitCaptureThisForNodeIfNecessary(node); + emitLinesStartingAt(node.statements, startIndex); + emitTempDeclarations(true); + } + emitLeadingComments(node.endOfFileToken); + } + function emitNode(node) { + if (!node) { + return; + } + if (node.flags & 2 /* Ambient */) { + return emitPinnedOrTripleSlashComments(node); + } + switch (node.kind) { + case 64 /* Identifier */: + return emitIdentifier(node); + case 124 /* Parameter */: + return emitParameter(node); + case 128 /* MethodDeclaration */: + case 127 /* MethodSignature */: + return emitMethod(node); + case 130 /* GetAccessor */: + case 131 /* SetAccessor */: + return emitAccessor(node); + case 92 /* ThisKeyword */: + return emitThis(node); + case 90 /* SuperKeyword */: + return emitSuper(node); + case 88 /* NullKeyword */: + return write("null"); + case 94 /* TrueKeyword */: + return write("true"); + case 79 /* FalseKeyword */: + return write("false"); + case 7 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 9 /* RegularExpressionLiteral */: + case 10 /* NoSubstitutionTemplateLiteral */: + case 11 /* TemplateHead */: + case 12 /* TemplateMiddle */: + case 13 /* TemplateTail */: + return emitLiteral(node); + case 165 /* TemplateExpression */: + return emitTemplateExpression(node); + case 169 /* TemplateSpan */: + return emitTemplateSpan(node); + case 121 /* QualifiedName */: + return emitQualifiedName(node); + case 144 /* ObjectBindingPattern */: + return emitObjectBindingPattern(node); + case 145 /* ArrayBindingPattern */: + return emitArrayBindingPattern(node); + case 146 /* BindingElement */: + return emitBindingElement(node); + case 147 /* ArrayLiteralExpression */: + return emitArrayLiteral(node); + case 148 /* ObjectLiteralExpression */: + return emitObjectLiteral(node); + case 204 /* PropertyAssignment */: + return emitPropertyAssignment(node); + case 205 /* ShorthandPropertyAssignment */: + return emitShorthandPropertyAssignment(node); + case 122 /* ComputedPropertyName */: + return emitComputedPropertyName(node); + case 149 /* PropertyAccessExpression */: + return emitPropertyAccess(node); + case 150 /* ElementAccessExpression */: + return emitIndexedAccess(node); + case 151 /* CallExpression */: + return emitCallExpression(node); + case 152 /* NewExpression */: + return emitNewExpression(node); + case 153 /* TaggedTemplateExpression */: + return emitTaggedTemplateExpression(node); + case 154 /* TypeAssertionExpression */: + return emit(node.expression); + case 155 /* ParenthesizedExpression */: + return emitParenExpression(node); + case 190 /* FunctionDeclaration */: + case 156 /* FunctionExpression */: + case 157 /* ArrowFunction */: + return emitFunctionDeclaration(node); + case 158 /* DeleteExpression */: + return emitDeleteExpression(node); + case 159 /* TypeOfExpression */: + return emitTypeOfExpression(node); + case 160 /* VoidExpression */: + return emitVoidExpression(node); + case 161 /* PrefixUnaryExpression */: + return emitPrefixUnaryExpression(node); + case 162 /* PostfixUnaryExpression */: + return emitPostfixUnaryExpression(node); + case 163 /* BinaryExpression */: + return emitBinaryExpression(node); + case 164 /* ConditionalExpression */: + return emitConditionalExpression(node); + case 167 /* SpreadElementExpression */: + return emitSpreadElementExpression(node); + case 168 /* OmittedExpression */: + return; + case 170 /* Block */: + case 196 /* ModuleBlock */: + return emitBlock(node); + case 171 /* VariableStatement */: + return emitVariableStatement(node); + case 172 /* EmptyStatement */: + return write(";"); + case 173 /* ExpressionStatement */: + return emitExpressionStatement(node); + case 174 /* IfStatement */: + return emitIfStatement(node); + case 175 /* DoStatement */: + return emitDoStatement(node); + case 176 /* WhileStatement */: + return emitWhileStatement(node); + case 177 /* ForStatement */: + return emitForStatement(node); + case 178 /* ForInStatement */: + return emitForInStatement(node); + case 179 /* ContinueStatement */: + case 180 /* BreakStatement */: + return emitBreakOrContinueStatement(node); + case 181 /* ReturnStatement */: + return emitReturnStatement(node); + case 182 /* WithStatement */: + return emitWithStatement(node); + case 183 /* SwitchStatement */: + return emitSwitchStatement(node); + case 200 /* CaseClause */: + case 201 /* DefaultClause */: + return emitCaseOrDefaultClause(node); + case 184 /* LabeledStatement */: + return emitLabelledStatement(node); + case 185 /* ThrowStatement */: + return emitThrowStatement(node); + case 186 /* TryStatement */: + return emitTryStatement(node); + case 203 /* CatchClause */: + return emitCatchClause(node); + case 187 /* DebuggerStatement */: + return emitDebuggerStatement(node); + case 188 /* VariableDeclaration */: + return emitVariableDeclaration(node); + case 191 /* ClassDeclaration */: + return emitClassDeclaration(node); + case 192 /* InterfaceDeclaration */: + return emitInterfaceDeclaration(node); + case 194 /* EnumDeclaration */: + return emitEnumDeclaration(node); + case 195 /* ModuleDeclaration */: + return emitModuleDeclaration(node); + case 197 /* ImportDeclaration */: + return emitImportDeclaration(node); + case 207 /* SourceFile */: + return emitSourceFile(node); + } + } + function hasDetachedComments(pos) { + return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + } + function getLeadingCommentsWithoutDetachedComments() { + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + if (detachedCommentsInfo.length - 1) { + detachedCommentsInfo.pop(); + } + else { + detachedCommentsInfo = undefined; + } + return leadingComments; + } + function getLeadingCommentsToEmit(node) { + if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { + var leadingComments; + if (hasDetachedComments(node.pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + } + return leadingComments; + } + } + function emitLeadingDeclarationComments(node) { + var leadingComments = getLeadingCommentsToEmit(node); + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + } + function emitTrailingDeclarationComments(node) { + if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { + var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + } + } + function emitLeadingCommentsOfLocalPosition(pos) { + var leadingComments; + if (hasDetachedComments(pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); + } + emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); + emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); + } + function emitDetachedCommentsAtPosition(node) { + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + if (leadingComments) { + var detachedComments = []; + var lastComment; + ts.forEach(leadingComments, function (comment) { + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + return detachedComments; + } + } + detachedComments.push(comment); + lastComment = comment; + }); + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var astLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (astLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); + } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; + } + } + } + } + } + function emitPinnedOrTripleSlashCommentsOfNode(node) { + var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment); + function isPinnedOrTripleSlashComment(comment) { + if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { + return currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */ && currentSourceFile.text.substring(comment.pos, comment.end).match(ts.fullTripleSlashReferencePathRegEx)) { + return true; + } + } + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, pinnedComments); + emitComments(currentSourceFile, writer, pinnedComments, true, newLine, writeComment); + } + if (compilerOptions.sourceMap) { + initializeEmitterWithSourceMaps(); + } + if (root) { + emit(root); + } + else { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!isExternalModuleOrDeclarationFile(sourceFile)) { + emit(sourceFile); + } + }); + } + writeLine(); + writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); + } + function writeDeclarationFile(jsFilePath, sourceFile) { + var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); + if (!emitDeclarationResult.reportedDeclarationError) { + var declarationOutput = emitDeclarationResult.referencePathsOutput; + var appliedSyncOutputPos = 0; + ts.forEach(emitDeclarationResult.aliasDeclarationEmitInfo, function (aliasEmitInfo) { + if (aliasEmitInfo.asynchronousOutput) { + declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); + declarationOutput += aliasEmitInfo.asynchronousOutput; + appliedSyncOutputPos = aliasEmitInfo.outputPos; + } + }); + declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos); + writeFile(host, diagnostics, ts.removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); + } + } + var hasSemanticErrors = false; + var isEmitBlocked = false; + if (targetSourceFile === undefined) { + hasSemanticErrors = resolver.hasSemanticErrors(); + isEmitBlocked = host.isEmitBlocked(); + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js"); + emitFile(jsFilePath, sourceFile); + } + }); + if (compilerOptions.out) { + emitFile(compilerOptions.out); + } + } + else { + if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { + hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); + isEmitBlocked = host.isEmitBlocked(targetSourceFile); + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitFile(jsFilePath, targetSourceFile); + } + else if (!ts.isDeclarationFile(targetSourceFile) && compilerOptions.out) { + ts.forEach(host.getSourceFiles(), function (sourceFile) { + if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { + hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); + isEmitBlocked = isEmitBlocked || host.isEmitBlocked(sourceFile); + } + }); + emitFile(compilerOptions.out); + } + } + function emitFile(jsFilePath, sourceFile) { + if (!isEmitBlocked) { + emitJavaScript(jsFilePath, sourceFile); + if (!hasSemanticErrors && compilerOptions.declaration) { + writeDeclarationFile(jsFilePath, sourceFile); + } + } + } + diagnostics.sort(ts.compareDiagnostics); + diagnostics = ts.deduplicateSortedDiagnostics(diagnostics); + var hasEmitterError = ts.forEach(diagnostics, function (diagnostic) { return diagnostic.category === 1 /* Error */; }); + var emitResultStatus; + if (isEmitBlocked) { + emitResultStatus = 1 /* AllOutputGenerationSkipped */; + } + else if (hasEmitterError) { + emitResultStatus = 4 /* EmitErrorsEncountered */; + } + else if (hasSemanticErrors && compilerOptions.declaration) { + emitResultStatus = 3 /* DeclarationGenerationSkipped */; + } + else if (hasSemanticErrors && !compilerOptions.declaration) { + emitResultStatus = 2 /* JSGeneratedWithSemanticErrors */; + } + else { + emitResultStatus = 0 /* Succeeded */; + } + return { + emitResultStatus: emitResultStatus, + diagnostics: diagnostics, + sourceMaps: sourceMapDataList + }; + } + ts.emitFiles = emitFiles; +})(ts || (ts = {})); +var ts; +(function (ts) { + function createCompilerHost(options) { + var currentDirectory; + var existingDirectories = {}; + function getCanonicalFileName(fileName) { + return ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + var unsupportedFileEncodingErrorCode = -2147024809; + function getSourceFile(filename, languageVersion, onError) { + try { + var text = ts.sys.readFile(filename, options.charset); + } + catch (e) { + if (onError) { + onError(e.number === unsupportedFileEncodingErrorCode ? ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText : e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(filename, text, languageVersion) : undefined; + } + function writeFile(fileName, data, writeByteOrderMark, onError) { + function directoryExists(directoryPath) { + if (ts.hasProperty(existingDirectories, directoryPath)) { + return true; + } + if (ts.sys.directoryExists(directoryPath)) { + existingDirectories[directoryPath] = true; + return true; + } + return false; + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + ts.sys.createDirectory(directoryPath); + } + } + try { + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + ts.sys.writeFile(fileName, data, writeByteOrderMark); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + return { + getSourceFile: getSourceFile, + getDefaultLibFilename: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"); }, + writeFile: writeFile, + getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, + useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return ts.sys.newLine; } + }; + } + ts.createCompilerHost = createCompilerHost; + function createProgram(rootNames, options, host) { + var program; + var files = []; + var filesByName = {}; + var errors = []; + var seenNoDefaultLib = options.noLib; + var commonSourceDirectory; + ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); + if (!seenNoDefaultLib) { + processRootFile(host.getDefaultLibFilename(options), true); + } + verifyCompilerOptions(); + errors.sort(ts.compareDiagnostics); + var diagnosticsProducingTypeChecker; + var noDiagnosticsTypeChecker; + var emitHost; + program = { + getSourceFile: getSourceFile, + getSourceFiles: function () { return files; }, + getCompilerOptions: function () { return options; }, + getCompilerHost: function () { return host; }, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker: getTypeChecker, + getCommonSourceDirectory: function () { return commonSourceDirectory; }, + emitFiles: invokeEmitter, + isEmitBlocked: isEmitBlocked, + getCurrentDirectory: host.getCurrentDirectory + }; + return program; + function getEmitHost() { + return emitHost || (emitHost = ts.createEmitHostFromProgram(program)); + } + function hasEarlyErrors(sourceFile) { + return ts.forEach(getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile), function (d) { return d.isEarly; }); + } + function isEmitBlocked(sourceFile) { + return getDiagnostics(sourceFile).length !== 0 || hasEarlyErrors(sourceFile) || (options.noEmitOnError && getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0); + } + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); + } + function getTypeChecker(produceDiagnostics) { + if (produceDiagnostics) { + return getDiagnosticsProducingTypeChecker(); + } + else { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, produceDiagnostics)); + } + } + function getDeclarationDiagnostics(targetSourceFile) { + var typeChecker = getDiagnosticsProducingTypeChecker(); + typeChecker.getDiagnostics(targetSourceFile); + var resolver = typeChecker.getEmitResolver(); + return ts.getDeclarationDiagnostics(getEmitHost(), resolver, targetSourceFile); + } + function invokeEmitter(targetSourceFile) { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(); + return ts.emitFiles(resolver, getEmitHost(), targetSourceFile); + } + function getSourceFile(filename) { + filename = host.getCanonicalFileName(filename); + return ts.hasProperty(filesByName, filename) ? filesByName[filename] : undefined; + } + function getDiagnostics(sourceFile) { + return sourceFile ? ts.filter(errors, function (e) { return e.file === sourceFile; }) : errors; + } + function getGlobalDiagnostics() { + return ts.filter(errors, function (e) { return !e.file; }); + } + function hasExtension(filename) { + return ts.getBaseFilename(filename).indexOf(".") >= 0; + } + function processRootFile(filename, isDefaultLib) { + processSourceFile(ts.normalizePath(filename), isDefaultLib); + } + function processSourceFile(filename, isDefaultLib, refFile, refPos, refEnd) { + if (refEnd !== undefined && refPos !== undefined) { + var start = refPos; + var length = refEnd - refPos; + } + var diagnostic; + if (hasExtension(filename)) { + if (!options.allowNonTsExtensions && !ts.fileExtensionIs(filename, ".ts")) { + diagnostic = ts.Diagnostics.File_0_must_have_extension_ts_or_d_ts; + } + else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { + diagnostic = ts.Diagnostics.File_0_not_found; + } + else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { + diagnostic = ts.Diagnostics.A_file_cannot_have_a_reference_to_itself; + } + } + else { + if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { + diagnostic = ts.Diagnostics.File_0_not_found; + filename += ".ts"; + } + } + if (diagnostic) { + if (refFile) { + errors.push(ts.createFileDiagnostic(refFile, start, length, diagnostic, filename)); + } + else { + errors.push(ts.createCompilerDiagnostic(diagnostic, filename)); + } + } + } + function findSourceFile(filename, isDefaultLib, refFile, refStart, refLength) { + var canonicalName = host.getCanonicalFileName(filename); + if (ts.hasProperty(filesByName, canonicalName)) { + return getSourceFileFromCache(filename, canonicalName, false); + } + else { + var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); + var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); + if (ts.hasProperty(filesByName, canonicalAbsolutePath)) { + return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, true); + } + var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, function (hostErrorMessage) { + if (refFile) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + }); + if (file) { + seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + filesByName[canonicalAbsolutePath] = file; + if (!options.noResolve) { + var basePath = ts.getDirectoryPath(filename); + processReferencedFiles(file, basePath); + processImportedModules(file, basePath); + } + if (isDefaultLib) { + files.unshift(file); + } + else { + files.push(file); + } + ts.forEach(file.getSyntacticDiagnostics(), function (e) { + errors.push(e); + }); + } + } + return file; + function getSourceFileFromCache(filename, canonicalName, useAbsolutePath) { + var file = filesByName[canonicalName]; + if (file && host.useCaseSensitiveFileNames()) { + var sourceFileName = useAbsolutePath ? ts.getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; + if (canonicalName !== sourceFileName) { + errors.push(ts.createFileDiagnostic(refFile, refStart, refLength, ts.Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); + } + } + return file; + } + } + function processReferencedFiles(file, basePath) { + ts.forEach(file.referencedFiles, function (ref) { + var referencedFilename = ts.isRootedDiskPath(ref.filename) ? ref.filename : ts.combinePaths(basePath, ref.filename); + processSourceFile(ts.normalizePath(referencedFilename), false, file, ref.pos, ref.end); + }); + } + function processImportedModules(file, basePath) { + ts.forEach(file.statements, function (node) { + if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { + var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + var searchPath = basePath; + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(searchPath, moduleName)); + if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { + break; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + } + } + else if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + ts.forEachChild(node.body, function (node) { + if (ts.isExternalModuleImportDeclaration(node) && ts.getExternalModuleImportDeclarationExpression(node).kind === 8 /* StringLiteral */) { + var nameLiteral = ts.getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + var searchName = ts.normalizePath(ts.combinePaths(basePath, moduleName)); + var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); + if (!tsFile) { + findModuleSourceFile(searchName + ".d.ts", nameLiteral); + } + } + } + }); + } + }); + function findModuleSourceFile(filename, nameLiteral) { + return findSourceFile(filename, false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); + } + } + function verifyCompilerOptions() { + if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { + if (options.mapRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + if (options.sourceRoot) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + return; + } + var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); + if (firstExternalModule && options.module === 0 /* None */) { + var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); + var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); + var errorLength = externalModuleErrorSpan.end - errorStart; + errors.push(ts.createFileDiagnostic(firstExternalModule, errorStart, errorLength, ts.Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); + } + if (options.outDir || options.sourceRoot || (options.mapRoot && (!options.out || firstExternalModule !== undefined))) { + var commonPathComponents; + ts.forEach(files, function (sourceFile) { + if (!(sourceFile.flags & 1024 /* DeclarationFile */) && !ts.fileExtensionIs(sourceFile.filename, ".js")) { + var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); + sourcePathComponents.pop(); + if (commonPathComponents) { + for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { + if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (i === 0) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + return; + } + commonPathComponents.length = i; + break; + } + } + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + } + else { + commonPathComponents = sourcePathComponents; + } + } + }); + commonSourceDirectory = ts.getNormalizedPathFromPathComponents(commonPathComponents); + if (commonSourceDirectory) { + commonSourceDirectory += ts.directorySeparator; + } + } + if (options.noEmit) { + if (options.out || options.outDir) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_out_or_outDir)); + } + if (options.declaration) { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); + } + } + } + } + ts.createProgram = createProgram; +})(ts || (ts = {})); +var ts; (function (ts) { var OutliningElementsCollector; (function (OutliningElementsCollector) { @@ -18338,8 +19811,8 @@ var ts; function addOutliningSpan(hintSpanNode, startElement, endElement, autoCollapse) { if (hintSpanNode && startElement && endElement) { var span = { - textSpan: ts.TextSpan.fromBounds(startElement.pos, endElement.end), - hintSpan: ts.TextSpan.fromBounds(hintSpanNode.getStart(), hintSpanNode.end), + textSpan: ts.createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: ts.createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), bannerText: collapseText, autoCollapse: autoCollapse }; @@ -18363,28 +19836,39 @@ var ts; return; } switch (n.kind) { - case 169 /* Block */: + case 170 /* Block */: if (!ts.isFunctionBlock(n)) { var parent = n.parent; var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); - if (parent.kind === 174 /* DoStatement */ || parent.kind === 177 /* ForInStatement */ || parent.kind === 176 /* ForStatement */ || parent.kind === 173 /* IfStatement */ || parent.kind === 175 /* WhileStatement */ || parent.kind === 181 /* WithStatement */ || parent.kind === 203 /* CatchClause */) { + if (parent.kind === 175 /* DoStatement */ || parent.kind === 178 /* ForInStatement */ || parent.kind === 177 /* ForStatement */ || parent.kind === 174 /* IfStatement */ || parent.kind === 176 /* WhileStatement */ || parent.kind === 182 /* WithStatement */ || parent.kind === 203 /* CatchClause */) { addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + break; } - else { - var span = ts.TextSpan.fromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + if (parent.kind === 186 /* TryStatement */) { + var tryStatement = parent; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = ts.findChildOfKind(tryStatement, 80 /* FinallyKeyword */, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } } + var span = ts.createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span, + hintSpan: span, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); break; } case 196 /* ModuleBlock */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); @@ -18393,7 +19877,7 @@ var ts; case 192 /* InterfaceDeclaration */: case 194 /* EnumDeclaration */: case 148 /* ObjectLiteralExpression */: - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: var openBrace = ts.findChildOfKind(n, 14 /* OpenBraceToken */, sourceFile); var closeBrace = ts.findChildOfKind(n, 15 /* CloseBraceToken */, sourceFile); addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); @@ -18444,14 +19928,14 @@ var ts; var childNodes = []; function visit(node) { switch (node.kind) { - case 170 /* VariableStatement */: - ts.forEach(node.declarations, visit); + case 171 /* VariableStatement */: + ts.forEach(node.declarationList.declarations, visit); break; case 144 /* ObjectBindingPattern */: case 145 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: if (ts.isBindingPattern(node)) { visit(node.name); break; @@ -18516,7 +20000,7 @@ var ts; } function isTopLevelFunctionDeclaration(functionDeclaration) { if (functionDeclaration.kind === 190 /* FunctionDeclaration */) { - if (functionDeclaration.body && functionDeclaration.body.kind === 169 /* Block */) { + if (functionDeclaration.body && functionDeclaration.body.kind === 170 /* Block */) { if (ts.forEach(functionDeclaration.body.statements, function (s) { return s.kind === 190 /* FunctionDeclaration */ && !isEmpty(s.name.text); })) { return true; } @@ -18598,7 +20082,7 @@ var ts; return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); case 190 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: if (ts.isBindingPattern(node.name)) { break; } @@ -18673,7 +20157,7 @@ var ts; return getNavigationBarItem(moduleName, ts.ScriptElementKind.moduleElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } function createFunctionItem(node) { - if (node.name && node.body && node.body.kind === 169 /* Block */) { + if (node.name && node.body && node.body.kind === 170 /* Block */) { var childItems = getItemsWorker(sortNodes(node.body.statements), createChildItem); return getNavigationBarItem(node.name.text, ts.ScriptElementKind.functionElement, ts.getNodeModifiers(node), [getNodeSpan(node)], childItems, getIndent(node)); } @@ -18721,7 +20205,7 @@ var ts; return node; } function getNodeSpan(node) { - return node.kind === 207 /* SourceFile */ ? ts.TextSpan.fromBounds(node.getFullStart(), node.getEnd()) : ts.TextSpan.fromBounds(node.getStart(), node.getEnd()); + return node.kind === 207 /* SourceFile */ ? ts.createTextSpanFromBounds(node.getFullStart(), node.getEnd()) : ts.createTextSpanFromBounds(node.getStart(), node.getEnd()); } function getTextOfNode(node) { return ts.getTextOfNodeFromSourceText(sourceFile.text, node); @@ -18735,6 +20219,12 @@ var ts; var SignatureHelp; (function (SignatureHelp) { var emptyArray = []; + var ArgumentListKind; + (function (ArgumentListKind) { + ArgumentListKind[ArgumentListKind["TypeArguments"] = 0] = "TypeArguments"; + ArgumentListKind[ArgumentListKind["CallArguments"] = 1] = "CallArguments"; + ArgumentListKind[ArgumentListKind["TaggedTemplateArguments"] = 2] = "TaggedTemplateArguments"; + })(ArgumentListKind || (ArgumentListKind = {})); function getSignatureHelpItems(sourceFile, position, typeInfoResolver, cancellationToken) { var startingToken = ts.findTokenOnLeftOfPosition(sourceFile, position); if (!startingToken) { @@ -18794,7 +20284,7 @@ var ts; var argumentIndex = ts.isInsideTemplateLiteral(node, position) ? 0 : 1; return getArgumentListInfoForTemplate(tagExpression, argumentIndex); } - else if (node.parent.kind === 168 /* TemplateSpan */ && node.parent.parent.parent.kind === 153 /* TaggedTemplateExpression */) { + else if (node.parent.kind === 169 /* TemplateSpan */ && node.parent.parent.parent.kind === 153 /* TaggedTemplateExpression */) { var templateSpan = node.parent; var templateExpression = templateSpan.parent; var tagExpression = templateExpression.parent; @@ -18834,7 +20324,7 @@ var ts; function getApplicableSpanForArguments(argumentsList) { var applicableSpanStart = argumentsList.getFullStart(); var applicableSpanEnd = ts.skipTrivia(sourceFile.text, argumentsList.getEnd(), false); - return new ts.TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate) { var template = taggedTemplate.template; @@ -18846,7 +20336,7 @@ var ts; applicableSpanEnd = ts.skipTrivia(sourceFile.text, applicableSpanEnd, false); } } - return new ts.TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node) { for (var n = node; n.kind !== 207 /* SourceFile */; n = n.parent) { @@ -19034,7 +20524,7 @@ var ts; ts.findChildOfKind = findChildOfKind; function findContainingList(node) { var syntaxList = ts.forEach(node.parent.getChildren(), function (c) { - if (c.kind === 209 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { + if (c.kind === 208 /* SyntaxList */ && c.pos <= node.pos && c.end >= node.end) { return c; } }); @@ -19157,7 +20647,7 @@ var ts; return n.getWidth() !== 0; } function getNodeModifiers(node) { - var flags = node.flags; + var flags = ts.getCombinedNodeFlags(node); var result = []; if (flags & 32 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); @@ -19394,6 +20884,13 @@ var ts; var formatting; (function (formatting) { var scanner = ts.createScanner(2 /* Latest */, false); + var ScanAction; + (function (ScanAction) { + ScanAction[ScanAction["Scan"] = 0] = "Scan"; + ScanAction[ScanAction["RescanGreaterThanToken"] = 1] = "RescanGreaterThanToken"; + ScanAction[ScanAction["RescanSlashToken"] = 2] = "RescanSlashToken"; + ScanAction[ScanAction["RescanTemplateToken"] = 3] = "RescanTemplateToken"; + })(ScanAction || (ScanAction = {})); function getFormattingScanner(sourceFile, startPos, endPos) { scanner.setText(sourceFile.text); scanner.setTextPos(startPos); @@ -19634,6 +21131,20 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (FormattingRequestKind) { + FormattingRequestKind[FormattingRequestKind["FormatDocument"] = 0] = "FormatDocument"; + FormattingRequestKind[FormattingRequestKind["FormatSelection"] = 1] = "FormatSelection"; + FormattingRequestKind[FormattingRequestKind["FormatOnEnter"] = 2] = "FormatOnEnter"; + FormattingRequestKind[FormattingRequestKind["FormatOnSemicolon"] = 3] = "FormatOnSemicolon"; + FormattingRequestKind[FormattingRequestKind["FormatOnClosingCurlyBrace"] = 4] = "FormatOnClosingCurlyBrace"; + })(formatting.FormattingRequestKind || (formatting.FormattingRequestKind = {})); + var FormattingRequestKind = formatting.FormattingRequestKind; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var formatting; (function (formatting) { @@ -19653,6 +21164,19 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (RuleAction) { + RuleAction[RuleAction["Ignore"] = 1] = "Ignore"; + RuleAction[RuleAction["Space"] = 2] = "Space"; + RuleAction[RuleAction["NewLine"] = 4] = "NewLine"; + RuleAction[RuleAction["Delete"] = 8] = "Delete"; + })(formatting.RuleAction || (formatting.RuleAction = {})); + var RuleAction = formatting.RuleAction; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var formatting; (function (formatting) { @@ -19682,6 +21206,17 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var formatting; + (function (formatting) { + (function (RuleFlags) { + RuleFlags[RuleFlags["None"] = 0] = "None"; + RuleFlags[RuleFlags["CanDeleteNewLines"] = 1] = "CanDeleteNewLines"; + })(formatting.RuleFlags || (formatting.RuleFlags = {})); + var RuleFlags = formatting.RuleFlags; + })(formatting = ts.formatting || (ts.formatting = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var formatting; (function (formatting) { @@ -19909,7 +21444,7 @@ var ts; throw new Error("Unknown rule"); }; Rules.IsForContext = function (context) { - return context.contextNode.kind === 176 /* ForStatement */; + return context.contextNode.kind === 177 /* ForStatement */; }; Rules.IsNotForContext = function (context) { return !Rules.IsForContext(context); @@ -19920,13 +21455,13 @@ var ts; case 164 /* ConditionalExpression */: return true; case 197 /* ImportDeclaration */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 124 /* Parameter */: case 206 /* EnumMember */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: return context.currentTokenSpan.kind === 52 /* EqualsToken */ || context.nextTokenSpan.kind === 52 /* EqualsToken */; - case 177 /* ForInStatement */: + case 178 /* ForInStatement */: return context.currentTokenSpan.kind === 85 /* InKeyword */ || context.nextTokenSpan.kind === 85 /* InKeyword */; } return false; @@ -19957,11 +21492,9 @@ var ts; return true; } switch (node.kind) { - case 169 /* Block */: - case 182 /* SwitchStatement */: + case 170 /* Block */: + case 183 /* SwitchStatement */: case 148 /* ObjectLiteralExpression */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: case 196 /* ModuleBlock */: return true; } @@ -20002,28 +21535,25 @@ var ts; case 191 /* ClassDeclaration */: case 195 /* ModuleDeclaration */: case 194 /* EnumDeclaration */: - case 169 /* Block */: - case 186 /* TryBlock */: + case 170 /* Block */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: case 196 /* ModuleBlock */: - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return true; } return false; }; Rules.IsControlDeclContext = function (context) { switch (context.contextNode.kind) { - case 173 /* IfStatement */: - case 182 /* SwitchStatement */: - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 175 /* WhileStatement */: - case 185 /* TryStatement */: - case 174 /* DoStatement */: - case 181 /* WithStatement */: + case 174 /* IfStatement */: + case 183 /* SwitchStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 176 /* WhileStatement */: + case 186 /* TryStatement */: + case 175 /* DoStatement */: + case 182 /* WithStatement */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return true; default: return false; @@ -20315,10 +21845,8 @@ var ts; TokenRange.Any = TokenRange.AllTokens(); TokenRange.AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([3 /* MultiLineCommentTrivia */])); TokenRange.Keywords = TokenRange.FromRange(65 /* FirstKeyword */, 120 /* LastKeyword */); - TokenRange.Operators = TokenRange.FromRange(22 /* FirstOperator */, 63 /* LastOperator */); TokenRange.BinaryOperators = TokenRange.FromRange(24 /* FirstBinaryOperator */, 63 /* LastBinaryOperator */); TokenRange.BinaryKeywordOperators = TokenRange.FromTokens([85 /* InKeyword */, 86 /* InstanceOfKeyword */]); - TokenRange.ReservedKeywords = TokenRange.FromRange(101 /* FirstFutureReservedWord */, 109 /* LastFutureReservedWord */); TokenRange.UnaryPrefixOperators = TokenRange.FromTokens([38 /* PlusPlusToken */, 39 /* MinusMinusToken */, 47 /* TildeToken */, 46 /* ExclamationToken */]); TokenRange.UnaryPrefixExpressions = TokenRange.FromTokens([7 /* NumericLiteral */, 64 /* Identifier */, 16 /* OpenParenToken */, 18 /* OpenBracketToken */, 14 /* OpenBraceToken */, 92 /* ThisKeyword */, 87 /* NewKeyword */]); TokenRange.UnaryPreincrementExpressions = TokenRange.FromTokens([64 /* Identifier */, 16 /* OpenParenToken */, 92 /* ThisKeyword */, 87 /* NewKeyword */]); @@ -20423,6 +21951,10 @@ var ts; (function (ts) { var formatting; (function (formatting) { + var Constants; + (function (Constants) { + Constants[Constants["Unknown"] = -1] = "Unknown"; + })(Constants || (Constants = {})); function formatOnEnter(position, sourceFile, rulesProvider, options) { var line = sourceFile.getLineAndCharacterFromPosition(position).line; ts.Debug.assert(line >= 2); @@ -20486,11 +22018,9 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 195 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 169 /* Block */ && ts.rangeContainsRange(body.statements, node); + return body && body.kind === 170 /* Block */ && ts.rangeContainsRange(body.statements, node); case 207 /* SourceFile */: - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: + case 170 /* Block */: case 196 /* ModuleBlock */: return ts.rangeContainsRange(parent.statements, node); case 203 /* CatchClause */: @@ -20958,7 +22488,7 @@ var ts; } } function newTextChange(start, len, newText) { - return { span: new ts.TextSpan(start, len), newText: newText }; + return { span: ts.createTextSpan(start, len), newText: newText }; } function recordDelete(start, len) { if (len) { @@ -21003,10 +22533,7 @@ var ts; } function isSomeBlock(kind) { switch (kind) { - case 169 /* Block */: - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: + case 170 /* Block */: case 196 /* ModuleBlock */: return true; } @@ -21226,7 +22753,7 @@ var ts; return candidate.end > position || !isCompletedNode(candidate, sourceFile); } function childStartsOnTheSameLineWithElseInIfStatement(parent, child, childStartLine, sourceFile) { - if (parent.kind === 173 /* IfStatement */ && parent.elseStatement === child) { + if (parent.kind === 174 /* IfStatement */ && parent.elseStatement === child) { var elseKeyword = ts.findChildOfKind(parent, 75 /* ElseKeyword */, sourceFile); ts.Debug.assert(elseKeyword !== undefined); var elseKeywordStartLine = getStartLineAndCharacterForNode(elseKeyword, sourceFile).line; @@ -21327,22 +22854,20 @@ var ts; case 192 /* InterfaceDeclaration */: case 194 /* EnumDeclaration */: case 147 /* ArrayLiteralExpression */: - case 169 /* Block */: - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: + case 170 /* Block */: case 196 /* ModuleBlock */: case 148 /* ObjectLiteralExpression */: case 139 /* TypeLiteral */: - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: case 201 /* DefaultClause */: case 200 /* CaseClause */: case 155 /* ParenthesizedExpression */: case 151 /* CallExpression */: case 152 /* NewExpression */: - case 170 /* VariableStatement */: - case 189 /* VariableDeclaration */: + case 171 /* VariableStatement */: + case 188 /* VariableDeclaration */: case 198 /* ExportAssignment */: - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: case 164 /* ConditionalExpression */: return true; } @@ -21353,11 +22878,11 @@ var ts; return true; } switch (parent) { - case 174 /* DoStatement */: - case 175 /* WhileStatement */: - case 177 /* ForInStatement */: - case 176 /* ForStatement */: - case 173 /* IfStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: + case 178 /* ForInStatement */: + case 177 /* ForStatement */: + case 174 /* IfStatement */: case 190 /* FunctionDeclaration */: case 156 /* FunctionExpression */: case 128 /* MethodDeclaration */: @@ -21366,7 +22891,7 @@ var ts; case 129 /* Constructor */: case 130 /* GetAccessor */: case 131 /* SetAccessor */: - return child !== 169 /* Block */; + return child !== 170 /* Block */; default: return false; } @@ -21394,10 +22919,9 @@ var ts; case 192 /* InterfaceDeclaration */: case 194 /* EnumDeclaration */: case 148 /* ObjectLiteralExpression */: - case 169 /* Block */: - case 187 /* FinallyBlock */: + case 170 /* Block */: case 196 /* ModuleBlock */: - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return nodeEndsWith(n, 15 /* CloseBraceToken */, sourceFile); case 203 /* CatchClause */: return isCompletedNode(n.block, sourceFile); @@ -21414,21 +22938,21 @@ var ts; return !n.body || isCompletedNode(n.body, sourceFile); case 195 /* ModuleDeclaration */: return n.body && isCompletedNode(n.body, sourceFile); - case 173 /* IfStatement */: + case 174 /* IfStatement */: if (n.elseStatement) { return isCompletedNode(n.elseStatement, sourceFile); } return isCompletedNode(n.thenStatement, sourceFile); - case 172 /* ExpressionStatement */: + case 173 /* ExpressionStatement */: return isCompletedNode(n.expression, sourceFile); case 147 /* ArrayLiteralExpression */: return nodeEndsWith(n, 19 /* CloseBracketToken */, sourceFile); case 200 /* CaseClause */: case 201 /* DefaultClause */: return false; - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return isCompletedNode(n.statement, sourceFile); - case 174 /* DoStatement */: + case 175 /* DoStatement */: var hasWhileKeyword = ts.findChildOfKind(n, 99 /* WhileKeyword */, sourceFile); if (hasWhileKeyword) { return nodeEndsWith(n, 17 /* CloseParenToken */, sourceFile); @@ -21530,7 +23054,7 @@ var ts; return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(209 /* SyntaxList */, nodes.pos, nodes.end, 512 /* Synthetic */, this); + var list = createNode(208 /* SyntaxList */, nodes.pos, nodes.end, 512 /* Synthetic */, this); list._children = []; var pos = nodes.pos; for (var i = 0, len = nodes.length; i < len; i++) { @@ -21662,7 +23186,7 @@ var ts; while (declaration.kind === 195 /* ModuleDeclaration */ && declaration.parent.kind === 195 /* ModuleDeclaration */) { declaration = declaration.parent; } - ts.forEach(getJsDocCommentTextRange(declaration.kind === 189 /* VariableDeclaration */ ? declaration.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + ts.forEach(getJsDocCommentTextRange(declaration.kind === 188 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); @@ -21924,9 +23448,6 @@ var ts; function SourceFileObject() { _super.apply(this, arguments); } - SourceFileObject.prototype.getScriptSnapshot = function () { - return this.scriptSnapshot; - }; SourceFileObject.prototype.getNamedDeclarations = function () { if (!this.namedDeclarations) { var sourceFile = this; @@ -21963,13 +23484,14 @@ var ts; namedDeclarations.push(node); } case 129 /* Constructor */: - case 170 /* VariableStatement */: + case 171 /* VariableStatement */: + case 189 /* VariableDeclarationList */: case 144 /* ObjectBindingPattern */: case 145 /* ArrayBindingPattern */: case 196 /* ModuleBlock */: ts.forEachChild(node, visit); break; - case 169 /* Block */: + case 170 /* Block */: if (ts.isFunctionBlock(node)) { ts.forEachChild(node, visit); } @@ -21978,7 +23500,7 @@ var ts; if (!(node.flags & 112 /* AccessibilityModifier */)) { break; } - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: if (ts.isBindingPattern(node.name)) { ts.forEachChild(node.name, visit); @@ -21995,145 +23517,8 @@ var ts; } return this.namedDeclarations; }; - SourceFileObject.prototype.update = function (scriptSnapshot, version, isOpen, textChangeRange) { - if (textChangeRange && ts.Debug.shouldAssert(1 /* Normal */)) { - var oldText = this.scriptSnapshot; - var newText = scriptSnapshot; - ts.Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); - if (ts.Debug.shouldAssert(3 /* VeryAggressive */)) { - var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); - var newTextPrefix = newText.getText(0, textChangeRange.span().start()); - ts.Debug.assert(oldTextPrefix === newTextPrefix); - var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); - var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); - ts.Debug.assert(oldTextSuffix === newTextSuffix); - } - } - return createLanguageServiceSourceFile(this.filename, scriptSnapshot, this.languageVersion, version, isOpen, true); - }; - SourceFileObject.createSourceFileObject = function (filename, scriptSnapshot, languageVersion, version, isOpen, setParentNodes) { - var newSourceFile = ts.createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, setParentNodes); - newSourceFile.version = version; - newSourceFile.isOpen = isOpen; - newSourceFile.scriptSnapshot = scriptSnapshot; - return newSourceFile; - }; return SourceFileObject; })(NodeObject); - var TextSpan = (function () { - function TextSpan(start, length) { - ts.Debug.assert(start >= 0, "start"); - ts.Debug.assert(length >= 0, "length"); - this._start = start; - this._length = length; - } - TextSpan.prototype.toJSON = function (key) { - return { start: this._start, length: this._length }; - }; - TextSpan.prototype.start = function () { - return this._start; - }; - TextSpan.prototype.length = function () { - return this._length; - }; - TextSpan.prototype.end = function () { - return this._start + this._length; - }; - TextSpan.prototype.isEmpty = function () { - return this._length === 0; - }; - TextSpan.prototype.containsPosition = function (position) { - return position >= this._start && position < this.end(); - }; - TextSpan.prototype.containsTextSpan = function (span) { - return span._start >= this._start && span.end() <= this.end(); - }; - TextSpan.prototype.overlapsWith = function (span) { - var overlapStart = Math.max(this._start, span._start); - var overlapEnd = Math.min(this.end(), span.end()); - return overlapStart < overlapEnd; - }; - TextSpan.prototype.overlap = function (span) { - var overlapStart = Math.max(this._start, span._start); - var overlapEnd = Math.min(this.end(), span.end()); - if (overlapStart < overlapEnd) { - return TextSpan.fromBounds(overlapStart, overlapEnd); - } - return undefined; - }; - TextSpan.prototype.intersectsWithTextSpan = function (span) { - return span._start <= this.end() && span.end() >= this._start; - }; - TextSpan.prototype.intersectsWith = function (start, length) { - var end = start + length; - return start <= this.end() && end >= this._start; - }; - TextSpan.prototype.intersectsWithPosition = function (position) { - return position <= this.end() && position >= this._start; - }; - TextSpan.prototype.intersection = function (span) { - var intersectStart = Math.max(this._start, span._start); - var intersectEnd = Math.min(this.end(), span.end()); - if (intersectStart <= intersectEnd) { - return TextSpan.fromBounds(intersectStart, intersectEnd); - } - return undefined; - }; - TextSpan.fromBounds = function (start, end) { - ts.Debug.assert(start >= 0); - ts.Debug.assert(end - start >= 0); - return new TextSpan(start, end - start); - }; - return TextSpan; - })(); - ts.TextSpan = TextSpan; - var TextChangeRange = (function () { - function TextChangeRange(span, newLength) { - ts.Debug.assert(newLength >= 0, "newLength"); - this._span = span; - this._newLength = newLength; - } - TextChangeRange.prototype.span = function () { - return this._span; - }; - TextChangeRange.prototype.newLength = function () { - return this._newLength; - }; - TextChangeRange.prototype.newSpan = function () { - return new TextSpan(this.span().start(), this.newLength()); - }; - TextChangeRange.prototype.isUnchanged = function () { - return this.span().isEmpty() && this.newLength() === 0; - }; - TextChangeRange.collapseChangesAcrossMultipleVersions = function (changes) { - if (changes.length === 0) { - return TextChangeRange.unchanged; - } - if (changes.length === 1) { - return changes[0]; - } - var change0 = changes[0]; - var oldStartN = change0.span().start(); - var oldEndN = change0.span().end(); - var newEndN = oldStartN + change0.newLength(); - for (var i = 1; i < changes.length; i++) { - var nextChange = changes[i]; - var oldStart1 = oldStartN; - var oldEnd1 = oldEndN; - var newEnd1 = newEndN; - var oldStart2 = nextChange.span().start(); - var oldEnd2 = nextChange.span().end(); - var newEnd2 = oldStart2 + nextChange.newLength(); - oldStartN = Math.min(oldStart1, oldStart2); - oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); - newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); - } - return new TextChangeRange(TextSpan.fromBounds(oldStartN, oldEndN), newEndN - oldStartN); - }; - TextChangeRange.unchanged = new TextChangeRange(new TextSpan(0, 0), 0); - return TextChangeRange; - })(); - ts.TextChangeRange = TextChangeRange; var TextChange = (function () { function TextChange() { } @@ -22165,6 +23550,19 @@ var ts; SymbolDisplayPartKind[SymbolDisplayPartKind["regularExpressionLiteral"] = 21] = "regularExpressionLiteral"; })(ts.SymbolDisplayPartKind || (ts.SymbolDisplayPartKind = {})); var SymbolDisplayPartKind = ts.SymbolDisplayPartKind; + (function (OutputFileType) { + OutputFileType[OutputFileType["JavaScript"] = 0] = "JavaScript"; + OutputFileType[OutputFileType["SourceMap"] = 1] = "SourceMap"; + OutputFileType[OutputFileType["Declaration"] = 2] = "Declaration"; + })(ts.OutputFileType || (ts.OutputFileType = {})); + var OutputFileType = ts.OutputFileType; + (function (EndOfLineState) { + EndOfLineState[EndOfLineState["Start"] = 0] = "Start"; + EndOfLineState[EndOfLineState["InMultiLineCommentTrivia"] = 1] = "InMultiLineCommentTrivia"; + EndOfLineState[EndOfLineState["InSingleQuoteStringLiteral"] = 2] = "InSingleQuoteStringLiteral"; + EndOfLineState[EndOfLineState["InDoubleQuoteStringLiteral"] = 3] = "InDoubleQuoteStringLiteral"; + })(ts.EndOfLineState || (ts.EndOfLineState = {})); + var EndOfLineState = ts.EndOfLineState; (function (TokenClass) { TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; @@ -22266,7 +23664,7 @@ var ts; if (declaration.kind === 156 /* FunctionExpression */) { return true; } - if (declaration.kind !== 189 /* VariableDeclaration */ && declaration.kind !== 190 /* FunctionDeclaration */) { + if (declaration.kind !== 188 /* VariableDeclaration */ && declaration.kind !== 190 /* FunctionDeclaration */) { return false; } for (var parent = declaration.parent; !ts.isFunctionBlock(parent); parent = parent.parent) { @@ -22363,7 +23761,7 @@ var ts; HostCache.prototype.getChangeRange = function (filename, lastKnownVersion, oldScriptSnapshot) { var currentVersion = this.getVersion(filename); if (lastKnownVersion === currentVersion) { - return TextChangeRange.unchanged; + return ts.unchangedTextChangeRange; } var scriptSnapshot = this.getScriptSnapshot(filename); return scriptSnapshot.getChangeRange(oldScriptSnapshot); @@ -22386,19 +23784,15 @@ var ts; if (this.currentFilename !== filename) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); var start = new Date().getTime(); - sourceFile = createLanguageServiceSourceFile(filename, scriptSnapshot, getDefaultCompilerOptions().target, version, true, true); + sourceFile = createLanguageServiceSourceFile(filename, scriptSnapshot, 2 /* Latest */, version, true, true); this.host.log("SyntaxTreeCache.Initialize: createSourceFile: " + (new Date().getTime() - start)); - var start = new Date().getTime(); - this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } else if (this.currentFileVersion !== version) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); - var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.getScriptSnapshot()); + var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.scriptSnapshot); var start = new Date().getTime(); - sourceFile = !editRange ? createLanguageServiceSourceFile(filename, scriptSnapshot, getDefaultCompilerOptions().target, version, true, true) : this.currentSourceFile.update(scriptSnapshot, version, true, editRange); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, true, editRange); this.host.log("SyntaxTreeCache.Initialize: updateSourceFile: " + (new Date().getTime() - start)); - var start = new Date().getTime(); - this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } if (sourceFile) { this.currentFileVersion = version; @@ -22411,14 +23805,48 @@ var ts; return this.currentSourceFile; }; SyntaxTreeCache.prototype.getCurrentScriptSnapshot = function (filename) { - return this.getCurrentSourceFile(filename).getScriptSnapshot(); + return this.getCurrentSourceFile(filename).scriptSnapshot; }; return SyntaxTreeCache; })(); + function setSourceFileFields(sourceFile, scriptSnapshot, version, isOpen) { + sourceFile.version = version; + sourceFile.isOpen = isOpen; + sourceFile.scriptSnapshot = scriptSnapshot; + } function createLanguageServiceSourceFile(filename, scriptSnapshot, scriptTarget, version, isOpen, setNodeParents) { - return SourceFileObject.createSourceFileObject(filename, scriptSnapshot, scriptTarget, version, isOpen, setNodeParents); + var sourceFile = ts.createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + setSourceFileFields(sourceFile, scriptSnapshot, version, isOpen); + return sourceFile; } ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; + ts.disableIncrementalParsing = false; + function updateLanguageServiceSourceFile(sourceFile, scriptSnapshot, version, isOpen, textChangeRange) { + if (textChangeRange && ts.Debug.shouldAssert(1 /* Normal */)) { + var oldText = sourceFile.scriptSnapshot; + var newText = scriptSnapshot; + ts.Debug.assert((oldText.getLength() - textChangeRange.span.length + textChangeRange.newLength) === newText.getLength()); + if (ts.Debug.shouldAssert(3 /* VeryAggressive */)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span.start); + var newTextPrefix = newText.getText(0, textChangeRange.span.start); + ts.Debug.assert(oldTextPrefix === newTextPrefix); + var oldTextSuffix = oldText.getText(ts.textSpanEnd(textChangeRange.span), oldText.getLength()); + var newTextSuffix = newText.getText(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.getLength()); + ts.Debug.assert(oldTextSuffix === newTextSuffix); + } + } + if (textChangeRange) { + if (version !== sourceFile.version || isOpen != sourceFile.isOpen) { + if (!ts.disableIncrementalParsing) { + var newSourceFile = sourceFile.update(scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange); + setSourceFileFields(newSourceFile, scriptSnapshot, version, isOpen); + return newSourceFile; + } + } + } + return createLanguageServiceSourceFile(sourceFile.filename, scriptSnapshot, sourceFile.languageVersion, version, isOpen, true); + } + ts.updateLanguageServiceSourceFile = updateLanguageServiceSourceFile; function createDocumentRegistry() { var buckets = {}; function getKeyFromCompilationSettings(settings) { @@ -22471,10 +23899,7 @@ var ts; ts.Debug.assert(bucket !== undefined); var entry = ts.lookUp(bucket, filename); ts.Debug.assert(entry !== undefined); - if (entry.sourceFile.isOpen === isOpen && entry.sourceFile.version === version) { - return entry.sourceFile; - } - entry.sourceFile = entry.sourceFile.update(scriptSnapshot, version, isOpen, textChangeRange); + entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, isOpen, textChangeRange); return entry.sourceFile; } function releaseDocument(filename, compilationSettings) { @@ -22555,7 +23980,7 @@ var ts; ts.preProcessFile = preProcessFile; function getTargetLabel(referenceNode, labelName) { while (referenceNode) { - if (referenceNode.kind === 183 /* LabeledStatement */ && referenceNode.label.text === labelName) { + if (referenceNode.kind === 184 /* LabeledStatement */ && referenceNode.label.text === labelName) { return referenceNode.label; } referenceNode = referenceNode.parent; @@ -22563,13 +23988,13 @@ var ts; return undefined; } function isJumpStatementTarget(node) { - return node.kind === 64 /* Identifier */ && (node.parent.kind === 179 /* BreakStatement */ || node.parent.kind === 178 /* ContinueStatement */) && node.parent.label === node; + return node.kind === 64 /* Identifier */ && (node.parent.kind === 180 /* BreakStatement */ || node.parent.kind === 179 /* ContinueStatement */) && node.parent.label === node; } function isLabelOfLabeledStatement(node) { - return node.kind === 64 /* Identifier */ && node.parent.kind === 183 /* LabeledStatement */ && node.parent.label === node; + return node.kind === 64 /* Identifier */ && node.parent.kind === 184 /* LabeledStatement */ && node.parent.label === node; } function isLabeledBy(node, labelName) { - for (var owner = node.parent; owner.kind === 183 /* LabeledStatement */; owner = owner.parent) { + for (var owner = node.parent; owner.kind === 184 /* LabeledStatement */; owner = owner.parent) { if (owner.label.text === labelName) { return true; } @@ -22652,6 +24077,21 @@ var ts; }); } } + var SemanticMeaning; + (function (SemanticMeaning) { + SemanticMeaning[SemanticMeaning["None"] = 0] = "None"; + SemanticMeaning[SemanticMeaning["Value"] = 1] = "Value"; + SemanticMeaning[SemanticMeaning["Type"] = 2] = "Type"; + SemanticMeaning[SemanticMeaning["Namespace"] = 4] = "Namespace"; + SemanticMeaning[SemanticMeaning["All"] = 7] = "All"; + })(SemanticMeaning || (SemanticMeaning = {})); + var BreakContinueSearchType; + (function (BreakContinueSearchType) { + BreakContinueSearchType[BreakContinueSearchType["None"] = 0] = "None"; + BreakContinueSearchType[BreakContinueSearchType["Unlabeled"] = 1] = "Unlabeled"; + BreakContinueSearchType[BreakContinueSearchType["Labeled"] = 2] = "Labeled"; + BreakContinueSearchType[BreakContinueSearchType["All"] = 3] = "All"; + })(BreakContinueSearchType || (BreakContinueSearchType = {})); var keywordCompletions = []; for (var i = 65 /* FirstKeyword */; i <= 120 /* LastKeyword */; i++) { keywordCompletions.push({ @@ -22666,13 +24106,11 @@ var ts; var hostCache; var program; var typeInfoResolver; - var fullTypeCheckChecker_doNotAccessDirectly; var useCaseSensitivefilenames = false; var sourceFilesByName = {}; var documentRegistry = documentRegistry; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var activeCompletionSession; - var writer = undefined; if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } @@ -22682,8 +24120,8 @@ var ts; function getSourceFile(filename) { return ts.lookUp(sourceFilesByName, getCanonicalFileName(filename)); } - function getFullTypeCheckChecker() { - return fullTypeCheckChecker_doNotAccessDirectly || (fullTypeCheckChecker_doNotAccessDirectly = program.getTypeChecker(true)); + function getDiagnosticsProducingTypeChecker() { + return program.getTypeChecker(true); } function getRuleProvider(options) { if (!ruleProvider) { @@ -22706,7 +24144,6 @@ var ts; return host.getDefaultLibFilename(options); }, writeFile: function (filename, data, writeByteOrderMark) { - writer(filename, data, writeByteOrderMark); }, getCurrentDirectory: function () { return host.getCurrentDirectory(); @@ -22765,7 +24202,7 @@ var ts; } var textChangeRange = null; if (sourceFile.isOpen && isOpen) { - textChangeRange = hostCache.getChangeRange(filename, sourceFile.version, sourceFile.getScriptSnapshot()); + textChangeRange = hostCache.getChangeRange(filename, sourceFile.version, sourceFile.scriptSnapshot); } sourceFile = documentRegistry.updateDocument(sourceFile, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); } @@ -22776,12 +24213,10 @@ var ts; } program = ts.createProgram(hostfilenames, compilationSettings, createCompilerHost()); typeInfoResolver = program.getTypeChecker(false); - fullTypeCheckChecker_doNotAccessDirectly = undefined; } function cleanupSemanticCache() { if (program) { typeInfoResolver = program.getTypeChecker(false); - fullTypeCheckChecker_doNotAccessDirectly = undefined; } } function dispose() { @@ -22800,11 +24235,11 @@ var ts; synchronizeHostData(); filename = ts.normalizeSlashes(filename); var compilerOptions = program.getCompilerOptions(); - var checker = getFullTypeCheckChecker(); + var checker = getDiagnosticsProducingTypeChecker(); var targetSourceFile = getSourceFile(filename); var allDiagnostics = checker.getDiagnostics(targetSourceFile); if (compilerOptions.declaration) { - allDiagnostics = allDiagnostics.concat(checker.getDeclarationDiagnostics(targetSourceFile)); + allDiagnostics = allDiagnostics.concat(program.getDeclarationDiagnostics(targetSourceFile)); } return allDiagnostics; } @@ -23018,7 +24453,7 @@ var ts; var containingNodeKind = previousToken.parent.kind; switch (previousToken.kind) { case 23 /* CommaToken */: - return containingNodeKind === 189 /* VariableDeclaration */ || containingNodeKind === 170 /* VariableStatement */ || containingNodeKind === 194 /* EnumDeclaration */ || isFunction(containingNodeKind); + return containingNodeKind === 188 /* VariableDeclaration */ || containingNodeKind === 189 /* VariableDeclarationList */ || containingNodeKind === 171 /* VariableStatement */ || containingNodeKind === 194 /* EnumDeclaration */ || isFunction(containingNodeKind); case 16 /* OpenParenToken */: return containingNodeKind === 203 /* CatchClause */ || isFunction(containingNodeKind); case 14 /* OpenBraceToken */: @@ -23175,7 +24610,7 @@ var ts; else if (symbol.valueDeclaration && ts.isConst(symbol.valueDeclaration)) { return ScriptElementKind.constElement; } - else if (ts.forEach(symbol.declarations, function (declaration) { return ts.isLet(declaration); })) { + else if (ts.forEach(symbol.declarations, ts.isLet)) { return ScriptElementKind.letElement; } return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; @@ -23235,7 +24670,8 @@ var ts; case 192 /* InterfaceDeclaration */: return ScriptElementKind.interfaceElement; case 193 /* TypeAliasDeclaration */: return ScriptElementKind.typeElement; case 194 /* EnumDeclaration */: return ScriptElementKind.enumElement; - case 189 /* VariableDeclaration */: return ts.isConst(node) ? ScriptElementKind.constElement : node.flags & 2048 /* Let */ ? ScriptElementKind.letElement : ScriptElementKind.variableElement; + case 188 /* VariableDeclaration */: + return ts.isConst(node) ? ScriptElementKind.constElement : ts.isLet(node) ? ScriptElementKind.letElement : ScriptElementKind.variableElement; case 190 /* FunctionDeclaration */: return ScriptElementKind.functionElement; case 130 /* GetAccessor */: return ScriptElementKind.memberGetAccessorElement; case 131 /* SetAccessor */: return ScriptElementKind.memberSetAccessorElement; @@ -23386,7 +24822,7 @@ var ts; } if (symbolFlags & 384 /* Enum */) { addNewLineIfDisplayPartsExist(); - if (ts.forEach(symbol.declarations, function (declaration) { return ts.isConstEnumDeclaration(declaration); })) { + if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(69 /* ConstKeyword */)); displayParts.push(ts.spacePart()); } @@ -23561,7 +24997,7 @@ var ts; return { kind: ScriptElementKind.unknown, kindModifiers: ScriptElementKindModifier.none, - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: ts.typeToDisplayParts(typeInfoResolver, type, getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; @@ -23573,16 +25009,70 @@ var ts; return { kind: displayPartsDocumentationsAndKind.symbolKind, kindModifiers: getSymbolModifiers(symbol), - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; } function getDefinitionAtPosition(filename, position) { + synchronizeHostData(); + filename = ts.normalizeSlashes(filename); + var sourceFile = getSourceFile(filename); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + if (isJumpStatementTarget(node)) { + var labelName = node.text; + var label = getTargetLabel(node.parent, node.text); + return label ? [getDefinitionInfo(label, ScriptElementKind.label, labelName, undefined)] : undefined; + } + var comment = ts.forEach(sourceFile.referencedFiles, function (r) { return (r.pos <= position && position < r.end) ? r : undefined; }); + if (comment) { + var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [{ + fileName: referenceFile.filename, + textSpan: ts.createTextSpanFromBounds(0, 0), + kind: ScriptElementKind.scriptElement, + name: comment.filename, + containerName: undefined, + containerKind: undefined + }]; + } + return undefined; + } + var symbol = typeInfoResolver.getSymbolAtLocation(node); + if (!symbol) { + return undefined; + } + var result = []; + if (node.parent.kind === 205 /* ShorthandPropertyAssignment */) { + var shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver, node); + var shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); + var shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); + ts.forEach(shorthandDeclarations, function (declaration) { + result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); + }); + return result; + } + var declarations = symbol.getDeclarations(); + var symbolName = typeInfoResolver.symbolToString(symbol); + var symbolKind = getSymbolKind(symbol, typeInfoResolver, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + ts.forEach(declarations, function (declaration) { + result.push(getDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; function getDefinitionInfo(node, symbolKind, symbolName, containerName) { return { fileName: node.getSourceFile().filename, - textSpan: TextSpan.fromBounds(node.getStart(), node.getEnd()), + textSpan: ts.createTextSpanFromBounds(node.getStart(), node.getEnd()), kind: symbolKind, name: symbolName, containerKind: undefined, @@ -23625,60 +25115,6 @@ var ts; } return false; } - synchronizeHostData(); - filename = ts.normalizeSlashes(filename); - var sourceFile = getSourceFile(filename); - var node = ts.getTouchingPropertyName(sourceFile, position); - if (!node) { - return undefined; - } - if (isJumpStatementTarget(node)) { - var labelName = node.text; - var label = getTargetLabel(node.parent, node.text); - return label ? [getDefinitionInfo(label, ScriptElementKind.label, labelName, undefined)] : undefined; - } - var comment = ts.forEach(sourceFile.referencedFiles, function (r) { return (r.pos <= position && position < r.end) ? r : undefined; }); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [{ - fileName: referenceFile.filename, - textSpan: TextSpan.fromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: comment.filename, - containerName: undefined, - containerKind: undefined - }]; - } - return undefined; - } - var symbol = typeInfoResolver.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var result = []; - if (node.parent.kind === 205 /* ShorthandPropertyAssignment */) { - var shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver); - var shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); - var shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); - ts.forEach(shorthandDeclarations, function (declaration) { - result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); - }); - return result; - } - var declarations = symbol.getDeclarations(); - var symbolName = typeInfoResolver.symbolToString(symbol); - var symbolKind = getSymbolKind(symbol, typeInfoResolver); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(getDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; } function getOccurrencesAtPosition(filename, position) { synchronizeHostData(); @@ -23694,52 +25130,56 @@ var ts; switch (node.kind) { case 83 /* IfKeyword */: case 75 /* ElseKeyword */: - if (hasKind(node.parent, 173 /* IfStatement */)) { + if (hasKind(node.parent, 174 /* IfStatement */)) { return getIfElseOccurrences(node.parent); } break; case 89 /* ReturnKeyword */: - if (hasKind(node.parent, 180 /* ReturnStatement */)) { + if (hasKind(node.parent, 181 /* ReturnStatement */)) { return getReturnOccurrences(node.parent); } break; case 93 /* ThrowKeyword */: - if (hasKind(node.parent, 184 /* ThrowStatement */)) { + if (hasKind(node.parent, 185 /* ThrowStatement */)) { return getThrowOccurrences(node.parent); } break; - case 95 /* TryKeyword */: case 67 /* CatchKeyword */: - case 80 /* FinallyKeyword */: - if (hasKind(parent(parent(node)), 185 /* TryStatement */)) { + if (hasKind(parent(parent(node)), 186 /* TryStatement */)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; + case 95 /* TryKeyword */: + case 80 /* FinallyKeyword */: + if (hasKind(parent(node), 186 /* TryStatement */)) { + return getTryCatchFinallyOccurrences(node.parent); + } + break; case 91 /* SwitchKeyword */: - if (hasKind(node.parent, 182 /* SwitchStatement */)) { + if (hasKind(node.parent, 183 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent); } break; case 66 /* CaseKeyword */: case 72 /* DefaultKeyword */: - if (hasKind(parent(parent(node)), 182 /* SwitchStatement */)) { + if (hasKind(parent(parent(node)), 183 /* SwitchStatement */)) { return getSwitchCaseDefaultOccurrences(node.parent.parent); } break; case 65 /* BreakKeyword */: case 70 /* ContinueKeyword */: - if (hasKind(node.parent, 179 /* BreakStatement */) || hasKind(node.parent, 178 /* ContinueStatement */)) { + if (hasKind(node.parent, 180 /* BreakStatement */) || hasKind(node.parent, 179 /* ContinueStatement */)) { return getBreakOrContinueStatementOccurences(node.parent); } break; case 81 /* ForKeyword */: - if (hasKind(node.parent, 176 /* ForStatement */) || hasKind(node.parent, 177 /* ForInStatement */)) { + if (hasKind(node.parent, 177 /* ForStatement */) || hasKind(node.parent, 178 /* ForInStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; case 99 /* WhileKeyword */: case 74 /* DoKeyword */: - if (hasKind(node.parent, 175 /* WhileStatement */) || hasKind(node.parent, 174 /* DoStatement */)) { + if (hasKind(node.parent, 176 /* WhileStatement */) || hasKind(node.parent, 175 /* DoStatement */)) { return getLoopBreakContinueOccurrences(node.parent); } break; @@ -23754,14 +25194,14 @@ var ts; return getGetAndSetOccurrences(node.parent); } default: - if (ts.isModifier(node.kind) && node.parent && (ts.isDeclaration(node.parent) || node.parent.kind === 170 /* VariableStatement */)) { + if (ts.isModifier(node.kind) && node.parent && (ts.isDeclaration(node.parent) || node.parent.kind === 171 /* VariableStatement */)) { return getModifierOccurrences(node.kind, node.parent); } } return undefined; function getIfElseOccurrences(ifStatement) { var keywords = []; - while (hasKind(ifStatement.parent, 173 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { + while (hasKind(ifStatement.parent, 174 /* IfStatement */) && ifStatement.parent.elseStatement === ifStatement) { ifStatement = ifStatement.parent; } while (ifStatement) { @@ -23772,7 +25212,7 @@ var ts; break; } } - if (!hasKind(ifStatement.elseStatement, 173 /* IfStatement */)) { + if (!hasKind(ifStatement.elseStatement, 174 /* IfStatement */)) { break; } ifStatement = ifStatement.elseStatement; @@ -23792,7 +25232,7 @@ var ts; if (shouldHighlightNextKeyword) { result.push({ fileName: filename, - textSpan: TextSpan.fromBounds(elseKeyword.getStart(), ifKeyword.end), + textSpan: ts.createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), isWriteAccess: false }); i++; @@ -23805,7 +25245,7 @@ var ts; } function getReturnOccurrences(returnStatement) { var func = ts.getContainingFunction(returnStatement); - if (!(func && hasKind(func.body, 169 /* Block */))) { + if (!(func && hasKind(func.body, 170 /* Block */))) { return undefined; } var keywords = []; @@ -23838,10 +25278,10 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 184 /* ThrowStatement */) { + if (node.kind === 185 /* ThrowStatement */) { statementAccumulator.push(node); } - else if (node.kind === 185 /* TryStatement */) { + else if (node.kind === 186 /* TryStatement */) { var tryStatement = node; if (tryStatement.catchClause) { aggregate(tryStatement.catchClause); @@ -23866,7 +25306,7 @@ var ts; if (ts.isFunctionBlock(parent) || parent.kind === 207 /* SourceFile */) { return parent; } - if (parent.kind === 185 /* TryStatement */) { + if (parent.kind === 186 /* TryStatement */) { var tryStatement = parent; if (tryStatement.tryBlock === child && tryStatement.catchClause) { return child; @@ -23883,14 +25323,15 @@ var ts; pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), 67 /* CatchKeyword */); } if (tryStatement.finallyBlock) { - pushKeywordIf(keywords, tryStatement.finallyBlock.getFirstToken(), 80 /* FinallyKeyword */); + var finallyKeyword = ts.findChildOfKind(tryStatement, 80 /* FinallyKeyword */, sourceFile); + pushKeywordIf(keywords, finallyKeyword, 80 /* FinallyKeyword */); } return ts.map(keywords, getReferenceEntryFromNode); } function getLoopBreakContinueOccurrences(loopNode) { var keywords = []; if (pushKeywordIf(keywords, loopNode.getFirstToken(), 81 /* ForKeyword */, 99 /* WhileKeyword */, 74 /* DoKeyword */)) { - if (loopNode.kind === 174 /* DoStatement */) { + if (loopNode.kind === 175 /* DoStatement */) { var loopTokens = loopNode.getChildren(); for (var i = loopTokens.length - 1; i >= 0; i--) { if (pushKeywordIf(keywords, loopTokens[i], 99 /* WhileKeyword */)) { @@ -23925,12 +25366,12 @@ var ts; var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { switch (owner.kind) { - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 174 /* DoStatement */: - case 175 /* WhileStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 175 /* DoStatement */: + case 176 /* WhileStatement */: return getLoopBreakContinueOccurrences(owner); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return getSwitchCaseDefaultOccurrences(owner); } } @@ -23941,7 +25382,7 @@ var ts; aggregate(node); return statementAccumulator; function aggregate(node) { - if (node.kind === 179 /* BreakStatement */ || node.kind === 178 /* ContinueStatement */) { + if (node.kind === 180 /* BreakStatement */ || node.kind === 179 /* ContinueStatement */) { statementAccumulator.push(node); } else if (!ts.isAnyFunction(node)) { @@ -23957,14 +25398,14 @@ var ts; function getBreakOrContinueOwner(statement) { for (var node = statement.parent; node; node = node.parent) { switch (node.kind) { - case 182 /* SwitchStatement */: - if (statement.kind === 178 /* ContinueStatement */) { + case 183 /* SwitchStatement */: + if (statement.kind === 179 /* ContinueStatement */) { continue; } - case 176 /* ForStatement */: - case 177 /* ForInStatement */: - case 175 /* WhileStatement */: - case 174 /* DoStatement */: + case 177 /* ForStatement */: + case 178 /* ForInStatement */: + case 176 /* WhileStatement */: + case 175 /* DoStatement */: if (!statement.label || isLabeledBy(node, statement.label.text)) { return node; } @@ -24272,7 +25713,7 @@ var ts; if ((findInStrings && isInString(position)) || (findInComments && isInComment(position))) { result.push({ fileName: sourceFile.filename, - textSpan: new TextSpan(position, searchText.length), + textSpan: ts.createTextSpan(position, searchText.length), isWriteAccess: false }); } @@ -24549,7 +25990,7 @@ var ts; } return { fileName: node.getSourceFile().filename, - textSpan: TextSpan.fromBounds(start, end), + textSpan: ts.createTextSpanFromBounds(start, end), isWriteAccess: isWriteAccess(node) }; } @@ -24590,7 +26031,7 @@ var ts; kindModifiers: ts.getNodeModifiers(declaration), matchKind: MatchKind[matchKind], fileName: filename, - textSpan: TextSpan.fromBounds(declaration.getStart(), declaration.getEnd()), + textSpan: ts.createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()), containerName: container && container.name ? container.name.text : "", containerKind: container && container.name ? getNodeKind(container) : "" }); @@ -24637,16 +26078,16 @@ var ts; filename = ts.normalizeSlashes(filename); var sourceFile = getSourceFile(filename); var outputFiles = []; - function getEmitOutputWriter(filename, data, writeByteOrderMark) { + function writeFile(filename, data, writeByteOrderMark) { outputFiles.push({ name: filename, writeByteOrderMark: writeByteOrderMark, text: data }); } - writer = getEmitOutputWriter; - var emitOutput = getFullTypeCheckChecker().emitFiles(sourceFile); - writer = undefined; + var emitHost = ts.createEmitHostFromProgram(program); + emitHost.writeFile = writeFile; + var emitOutput = ts.emitFiles(getDiagnosticsProducingTypeChecker().getEmitResolver(), emitHost, sourceFile); return { outputFiles: outputFiles, emitOutputStatus: emitOutput.emitResultStatus @@ -24655,7 +26096,7 @@ var ts; function getMeaningFromDeclaration(node) { switch (node.kind) { case 124 /* Parameter */: - case 189 /* VariableDeclaration */: + case 188 /* VariableDeclaration */: case 146 /* BindingElement */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: @@ -24794,7 +26235,7 @@ var ts; break; } } - return TextSpan.fromBounds(nodeForStartPos.getStart(), node.getEnd()); + return ts.createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); } function getBreakpointStatementAtPosition(filename, position) { filename = ts.normalizeSlashes(filename); @@ -24843,14 +26284,14 @@ var ts; } } function processNode(node) { - if (node && span.intersectsWith(node.getStart(), node.getWidth())) { + if (node && ts.textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { if (node.kind === 64 /* Identifier */ && node.getWidth() > 0) { var symbol = typeInfoResolver.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, getMeaningFromLocation(node)); if (type) { result.push({ - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: ts.createTextSpan(node.getStart(), node.getWidth()), classificationType: type }); } @@ -24863,48 +26304,109 @@ var ts; function getSyntacticClassifications(fileName, span) { fileName = ts.normalizeSlashes(fileName); var sourceFile = getCurrentSourceFile(fileName); + var triviaScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); + var mergeConflictScanner = ts.createScanner(2 /* Latest */, false, sourceFile.text); var result = []; processElement(sourceFile); return result; - function classifyComment(comment) { - var width = comment.end - comment.pos; - if (span.intersectsWith(comment.pos, width)) { + function classifyLeadingTrivia(token) { + var tokenStart = ts.skipTrivia(sourceFile.text, token.pos, false); + if (tokenStart === token.pos) { + return; + } + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + if (ts.textSpanIntersectsWith(span, start, width)) { + if (!ts.isTrivia(kind)) { + return; + } + if (ts.isComment(kind)) { + result.push({ + textSpan: ts.createTextSpan(start, width), + classificationType: ClassificationTypeNames.comment + }); + continue; + } + if (kind === 6 /* ConflictMarkerTrivia */) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + result.push({ + textSpan: ts.createTextSpan(start, width), + classificationType: ClassificationTypeNames.comment + }); + continue; + } + ts.Debug.assert(ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + } + } + } + } + function classifyDisabledMergeCode(text, start, end) { + for (var i = start; i < end; i++) { + if (ts.isLineBreak(text.charCodeAt(i))) { + break; + } + } + result.push({ + textSpan: ts.createTextSpanFromBounds(start, i), + classificationType: ClassificationTypeNames.comment + }); + mergeConflictScanner.setTextPos(i); + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + var type = classifyTokenType(tokenKind); + if (type) { result.push({ - textSpan: new TextSpan(comment.pos, width), - classificationType: ClassificationTypeNames.comment + textSpan: ts.createTextSpanFromBounds(start, end), + classificationType: type }); } } function classifyToken(token) { - ts.forEach(ts.getLeadingCommentRanges(sourceFile.text, token.getFullStart()), classifyComment); + classifyLeadingTrivia(token); if (token.getWidth() > 0) { - var type = classifyTokenType(token); + var type = classifyTokenType(token.kind, token); if (type) { result.push({ - textSpan: new TextSpan(token.getStart(), token.getWidth()), + textSpan: ts.createTextSpan(token.getStart(), token.getWidth()), classificationType: type }); } } - ts.forEach(ts.getTrailingCommentRanges(sourceFile.text, token.getEnd()), classifyComment); } - function classifyTokenType(token) { - var tokenKind = token.kind; + function classifyTokenType(tokenKind, token) { if (ts.isKeyword(tokenKind)) { return ClassificationTypeNames.keyword; } if (tokenKind === 24 /* LessThanToken */ || tokenKind === 25 /* GreaterThanToken */) { - if (ts.getTypeArgumentOrTypeParameterList(token.parent)) { + if (token && ts.getTypeArgumentOrTypeParameterList(token.parent)) { return ClassificationTypeNames.punctuation; } } - if (ts.isPunctuation(token.kind)) { - if (token.parent.kind === 163 /* BinaryExpression */ || token.parent.kind === 189 /* VariableDeclaration */ || token.parent.kind === 161 /* PrefixUnaryExpression */ || token.parent.kind === 162 /* PostfixUnaryExpression */ || token.parent.kind === 164 /* ConditionalExpression */) { - return ClassificationTypeNames.operator; - } - else { - return ClassificationTypeNames.punctuation; + if (ts.isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === 52 /* EqualsToken */) { + if (token.parent.kind === 188 /* VariableDeclaration */ || token.parent.kind === 126 /* PropertyDeclaration */ || token.parent.kind === 124 /* Parameter */) { + return ClassificationTypeNames.operator; + } + } + if (token.parent.kind === 163 /* BinaryExpression */ || token.parent.kind === 161 /* PrefixUnaryExpression */ || token.parent.kind === 162 /* PostfixUnaryExpression */ || token.parent.kind === 164 /* ConditionalExpression */) { + return ClassificationTypeNames.operator; + } } + return ClassificationTypeNames.punctuation; } else if (tokenKind === 7 /* NumericLiteral */) { return ClassificationTypeNames.numericLiteral; @@ -24919,39 +26421,40 @@ var ts; return ClassificationTypeNames.stringLiteral; } else if (tokenKind === 64 /* Identifier */) { - switch (token.parent.kind) { - case 191 /* ClassDeclaration */: - if (token.parent.name === token) { - return ClassificationTypeNames.className; - } - return; - case 123 /* TypeParameter */: - if (token.parent.name === token) { - return ClassificationTypeNames.typeParameterName; - } - return; - case 192 /* InterfaceDeclaration */: - if (token.parent.name === token) { - return ClassificationTypeNames.interfaceName; - } - return; - case 194 /* EnumDeclaration */: - if (token.parent.name === token) { - return ClassificationTypeNames.enumName; - } - return; - case 195 /* ModuleDeclaration */: - if (token.parent.name === token) { - return ClassificationTypeNames.moduleName; - } - return; - default: - return ClassificationTypeNames.text; + if (token) { + switch (token.parent.kind) { + case 191 /* ClassDeclaration */: + if (token.parent.name === token) { + return ClassificationTypeNames.className; + } + return; + case 123 /* TypeParameter */: + if (token.parent.name === token) { + return ClassificationTypeNames.typeParameterName; + } + return; + case 192 /* InterfaceDeclaration */: + if (token.parent.name === token) { + return ClassificationTypeNames.interfaceName; + } + return; + case 194 /* EnumDeclaration */: + if (token.parent.name === token) { + return ClassificationTypeNames.enumName; + } + return; + case 195 /* ModuleDeclaration */: + if (token.parent.name === token) { + return ClassificationTypeNames.moduleName; + } + return; + } } + return ClassificationTypeNames.text; } } function processElement(element) { - if (span.intersectsWith(element.getFullStart(), element.getFullWidth())) { + if (ts.textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { var children = element.getChildren(); for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; @@ -24983,9 +26486,9 @@ var ts; 33; var current = childNodes[i]; if (current.kind === matchKind) { - var range1 = new TextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); - var range2 = new TextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); - if (range1.start() < range2.start()) { + var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); + var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); + if (range1.start < range2.start) { result.push(range1, range2); } else { @@ -25112,9 +26615,9 @@ var ts; if (node && node.kind === 64 /* Identifier */) { var symbol = typeInfoResolver.getSymbolAtLocation(node); if (symbol && symbol.getDeclarations() && symbol.getDeclarations().length > 0) { - var kind = getSymbolKind(symbol, typeInfoResolver); + var kind = getSymbolKind(symbol, typeInfoResolver, node); if (kind) { - return getRenameInfo(symbol.name, typeInfoResolver.getFullyQualifiedName(symbol), kind, getSymbolModifiers(symbol), new TextSpan(node.getStart(), node.getWidth())); + return getRenameInfo(symbol.name, typeInfoResolver.getFullyQualifiedName(symbol), kind, getSymbolModifiers(symbol), ts.createTextSpan(node.getStart(), node.getWidth())); } } } @@ -25428,7 +26931,7 @@ var ts; } return spanInNode(tokenAtLocation); function textSpan(startNode, endNode) { - return ts.TextSpan.fromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + return ts.createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node, otherwiseOnNode) { if (node && lineOfPosition === sourceFile.getLineAndCharacterFromPosition(node.getStart()).line) { @@ -25445,10 +26948,10 @@ var ts; function spanInNode(node) { if (node) { if (ts.isExpression(node)) { - if (node.parent.kind === 174 /* DoStatement */) { + if (node.parent.kind === 175 /* DoStatement */) { return spanInPreviousNode(node); } - if (node.parent.kind === 176 /* ForStatement */) { + if (node.parent.kind === 177 /* ForStatement */) { return textSpan(node); } if (node.parent.kind === 163 /* BinaryExpression */ && node.parent.operator === 23 /* CommaToken */) { @@ -25459,9 +26962,9 @@ var ts; } } switch (node.kind) { - case 170 /* VariableStatement */: - return spanInVariableDeclaration(node.declarations[0]); - case 189 /* VariableDeclaration */: + case 171 /* VariableStatement */: + return spanInVariableDeclaration(node.declarationList.declarations[0]); + case 188 /* VariableDeclaration */: case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: return spanInVariableDeclaration(node); @@ -25476,45 +26979,43 @@ var ts; case 156 /* FunctionExpression */: case 157 /* ArrowFunction */: return spanInFunctionDeclaration(node); - case 169 /* Block */: + case 170 /* Block */: if (ts.isFunctionBlock(node)) { return spanInFunctionBlock(node); } - case 186 /* TryBlock */: - case 187 /* FinallyBlock */: case 196 /* ModuleBlock */: return spanInBlock(node); case 203 /* CatchClause */: return spanInBlock(node.block); - case 172 /* ExpressionStatement */: + case 173 /* ExpressionStatement */: return textSpan(node.expression); - case 180 /* ReturnStatement */: + case 181 /* ReturnStatement */: return textSpan(node.getChildAt(0), node.expression); - case 175 /* WhileStatement */: + case 176 /* WhileStatement */: return textSpan(node, ts.findNextToken(node.expression, node)); - case 174 /* DoStatement */: + case 175 /* DoStatement */: return spanInNode(node.statement); - case 188 /* DebuggerStatement */: + case 187 /* DebuggerStatement */: return textSpan(node.getChildAt(0)); - case 173 /* IfStatement */: + case 174 /* IfStatement */: return textSpan(node, ts.findNextToken(node.expression, node)); - case 183 /* LabeledStatement */: + case 184 /* LabeledStatement */: return spanInNode(node.statement); - case 179 /* BreakStatement */: - case 178 /* ContinueStatement */: + case 180 /* BreakStatement */: + case 179 /* ContinueStatement */: return textSpan(node.getChildAt(0), node.label); - case 176 /* ForStatement */: + case 177 /* ForStatement */: return spanInForStatement(node); - case 177 /* ForInStatement */: + case 178 /* ForInStatement */: return textSpan(node, ts.findNextToken(node.expression, node)); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return textSpan(node, ts.findNextToken(node.expression, node)); case 200 /* CaseClause */: case 201 /* DefaultClause */: return spanInNode(node.statements[0]); - case 185 /* TryStatement */: + case 186 /* TryStatement */: return spanInBlock(node.tryBlock); - case 184 /* ThrowStatement */: + case 185 /* ThrowStatement */: return textSpan(node, node.expression); case 198 /* ExportAssignment */: return textSpan(node, node.exportName); @@ -25530,7 +27031,7 @@ var ts; case 151 /* CallExpression */: case 152 /* NewExpression */: return textSpan(node); - case 181 /* WithStatement */: + case 182 /* WithStatement */: return spanInNode(node.statement); case 192 /* InterfaceDeclaration */: case 193 /* TypeAliasDeclaration */: @@ -25573,12 +27074,12 @@ var ts; } } function spanInVariableDeclaration(variableDeclaration) { - if (variableDeclaration.parent.kind === 177 /* ForInStatement */) { - return spanInNode(variableDeclaration.parent); + if (variableDeclaration.parent.parent.kind === 178 /* ForInStatement */) { + return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.kind === 170 /* VariableStatement */; - var isDeclarationOfForStatement = variableDeclaration.parent.kind === 176 /* ForStatement */ && ts.contains(variableDeclaration.parent.declarations, variableDeclaration); - var declarations = isParentVariableStatement ? variableDeclaration.parent.declarations : isDeclarationOfForStatement ? variableDeclaration.parent.declarations : undefined; + var isParentVariableStatement = variableDeclaration.parent.parent.kind === 171 /* VariableStatement */; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === 177 /* ForStatement */ && ts.contains(variableDeclaration.parent.parent.initializer.declarations, variableDeclaration); + var declarations = isParentVariableStatement ? variableDeclaration.parent.parent.declarationList.declarations : isDeclarationOfForStatement ? variableDeclaration.parent.parent.initializer.declarations : undefined; if (variableDeclaration.initializer || (variableDeclaration.flags & 1 /* Export */)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { @@ -25641,21 +27142,26 @@ var ts; if (ts.getModuleInstanceState(block.parent) !== 1 /* Instantiated */) { return undefined; } - case 175 /* WhileStatement */: - case 173 /* IfStatement */: - case 177 /* ForInStatement */: + case 176 /* WhileStatement */: + case 174 /* IfStatement */: + case 178 /* ForInStatement */: return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]); - case 176 /* ForStatement */: + case 177 /* ForStatement */: return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]); } return spanInNode(block.statements[0]); } function spanInForStatement(forStatement) { - if (forStatement.declarations) { - return spanInNode(forStatement.declarations[0]); - } if (forStatement.initializer) { - return spanInNode(forStatement.initializer); + if (forStatement.initializer.kind === 189 /* VariableDeclarationList */) { + var variableDeclarationList = forStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + return spanInNode(forStatement.initializer); + } } if (forStatement.condition) { return textSpan(forStatement.condition); @@ -25672,7 +27178,7 @@ var ts; case 191 /* ClassDeclaration */: var classDeclaration = node.parent; return spanInNodeIfStartsOnSameLine(ts.findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile)); - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: return spanInNodeIfStartsOnSameLine(node.parent, node.parent.clauses[0]); } return spanInNode(node.parent); @@ -25686,16 +27192,14 @@ var ts; case 194 /* EnumDeclaration */: case 191 /* ClassDeclaration */: return textSpan(node); - case 169 /* Block */: + case 170 /* Block */: if (ts.isFunctionBlock(node.parent)) { return textSpan(node); } - case 186 /* TryBlock */: case 203 /* CatchClause */: - case 187 /* FinallyBlock */: return spanInNode(node.parent.statements[node.parent.statements.length - 1]); ; - case 182 /* SwitchStatement */: + case 183 /* SwitchStatement */: var switchStatement = node.parent; var lastClause = switchStatement.clauses[switchStatement.clauses.length - 1]; if (lastClause) { @@ -25707,7 +27211,7 @@ var ts; } } function spanInOpenParenToken(node) { - if (node.parent.kind === 174 /* DoStatement */) { + if (node.parent.kind === 175 /* DoStatement */) { return spanInPreviousNode(node); } return spanInNode(node.parent); @@ -25722,9 +27226,9 @@ var ts; case 130 /* GetAccessor */: case 131 /* SetAccessor */: case 129 /* Constructor */: - case 175 /* WhileStatement */: - case 174 /* DoStatement */: - case 176 /* ForStatement */: + case 176 /* WhileStatement */: + case 175 /* DoStatement */: + case 177 /* ForStatement */: return spanInPreviousNode(node); default: return spanInNode(node.parent); @@ -25744,7 +27248,7 @@ var ts; return spanInNode(node.parent); } function spanInWhileKeyword(node) { - if (node.parent.kind === 174 /* DoStatement */) { + if (node.parent.kind === 175 /* DoStatement */) { return textSpan(node, ts.findNextToken(node.parent.expression, node.parent)); } return spanInNode(node.parent); @@ -25784,7 +27288,7 @@ var ts; return null; } var decoded = JSON.parse(encoded); - return new ts.TextChangeRange(new ts.TextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + return ts.createTextChangeRange(ts.createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); }; return ScriptSnapshotShimAdapter; })(); @@ -25932,14 +27436,14 @@ var ts; LanguageServiceShimObject.prototype.getSyntacticClassifications = function (fileName, start, length) { var _this = this; return this.forwardJSONCall("getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSyntacticClassifications(fileName, new ts.TextSpan(start, length)); + var classifications = _this.languageService.getSyntacticClassifications(fileName, ts.createTextSpan(start, length)); return classifications; }); }; LanguageServiceShimObject.prototype.getSemanticClassifications = function (fileName, start, length) { var _this = this; return this.forwardJSONCall("getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", function () { - var classifications = _this.languageService.getSemanticClassifications(fileName, new ts.TextSpan(start, length)); + var classifications = _this.languageService.getSemanticClassifications(fileName, ts.createTextSpan(start, length)); return classifications; }); }; diff --git a/bin/typescriptServices_internal.d.ts b/bin/typescriptServices_internal.d.ts index 260c1b1c67..7a19a0906a 100644 --- a/bin/typescriptServices_internal.d.ts +++ b/bin/typescriptServices_internal.d.ts @@ -26,7 +26,7 @@ declare module ts { } interface StringSet extends Map { } - function forEach(array: T[], callback: (element: T) => U): U; + function forEach(array: T[], callback: (element: T, index: number) => U): U; function contains(array: T[], value: T): boolean; function indexOf(array: T[], value: T): number; function countWhere(array: T[], predicate: (x: T) => boolean): number; @@ -149,7 +149,8 @@ declare module ts { function getSourceFileOfNode(node: Node): SourceFile; function nodePosToString(node: Node): string; function getStartPosOfNode(node: Node): number; - function isMissingNode(node: Node): boolean; + function nodeIsMissing(node: Node): boolean; + function nodeIsPresent(node: Node): boolean; function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number; function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string; function getTextOfNodeFromSourceText(sourceText: string, node: Node): string; @@ -163,6 +164,7 @@ declare module ts { function isExternalModule(file: SourceFile): boolean; function isDeclarationFile(file: SourceFile): boolean; function isConstEnumDeclaration(node: Node): boolean; + function getCombinedNodeFlags(node: Node): NodeFlags; function isConst(node: Node): boolean; function isLet(node: Node): boolean; function isPrologueDirective(node: Node): boolean; @@ -196,12 +198,38 @@ declare module ts { function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray; function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray; function getHeritageClause(clauses: NodeArray, kind: SyntaxKind): HeritageClause; - function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference): SourceFile; + function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile; function getAncestor(node: Node, kind: SyntaxKind): Node; function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult; function isKeyword(token: SyntaxKind): boolean; function isTrivia(token: SyntaxKind): boolean; function isModifier(token: SyntaxKind): boolean; + function createEmitHostFromProgram(program: Program): EmitHost; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + var unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; } declare module ts { interface ListItemInfo { diff --git a/bin/typescript_internal.d.ts b/bin/typescript_internal.d.ts index 37ab4b4da6..6a40dd36d1 100644 --- a/bin/typescript_internal.d.ts +++ b/bin/typescript_internal.d.ts @@ -26,7 +26,7 @@ declare module "typescript" { } interface StringSet extends Map { } - function forEach(array: T[], callback: (element: T) => U): U; + function forEach(array: T[], callback: (element: T, index: number) => U): U; function contains(array: T[], value: T): boolean; function indexOf(array: T[], value: T): number; function countWhere(array: T[], predicate: (x: T) => boolean): number; @@ -149,7 +149,8 @@ declare module "typescript" { function getSourceFileOfNode(node: Node): SourceFile; function nodePosToString(node: Node): string; function getStartPosOfNode(node: Node): number; - function isMissingNode(node: Node): boolean; + function nodeIsMissing(node: Node): boolean; + function nodeIsPresent(node: Node): boolean; function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number; function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string; function getTextOfNodeFromSourceText(sourceText: string, node: Node): string; @@ -163,6 +164,7 @@ declare module "typescript" { function isExternalModule(file: SourceFile): boolean; function isDeclarationFile(file: SourceFile): boolean; function isConstEnumDeclaration(node: Node): boolean; + function getCombinedNodeFlags(node: Node): NodeFlags; function isConst(node: Node): boolean; function isLet(node: Node): boolean; function isPrologueDirective(node: Node): boolean; @@ -196,12 +198,38 @@ declare module "typescript" { function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray; function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray; function getHeritageClause(clauses: NodeArray, kind: SyntaxKind): HeritageClause; - function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference): SourceFile; + function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile; function getAncestor(node: Node, kind: SyntaxKind): Node; function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult; function isKeyword(token: SyntaxKind): boolean; function isTrivia(token: SyntaxKind): boolean; function isModifier(token: SyntaxKind): boolean; + function createEmitHostFromProgram(program: Program): EmitHost; + function textSpanEnd(span: TextSpan): number; + function textSpanIsEmpty(span: TextSpan): boolean; + function textSpanContainsPosition(span: TextSpan, position: number): boolean; + function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; + function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; + function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; + function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; + function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; + function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; + function createTextSpan(start: number, length: number): TextSpan; + function createTextSpanFromBounds(start: number, end: number): TextSpan; + function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; + function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; + function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; + var unchangedTextChangeRange: TextChangeRange; + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; } declare module "typescript" { interface ListItemInfo { diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 4f8141fd86..201913a50b 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -1,10 +1,6 @@ -/// -/// -/// /// module ts { - export const enum ModuleInstanceState { NonInstantiated = 0, Instantiated = 1, @@ -206,7 +202,8 @@ module ts { if (symbolKind & SymbolFlags.Namespace) { exportKind |= SymbolFlags.ExportNamespace; } - if (node.flags & NodeFlags.Export || (node.kind !== SyntaxKind.ImportDeclaration && isAmbientContext(container))) { + + if (getCombinedNodeFlags(node) & NodeFlags.Export || (node.kind !== SyntaxKind.ImportDeclaration && isAmbientContext(container))) { if (exportKind) { var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes); @@ -234,10 +231,8 @@ module ts { parent = node; if (symbolKind & SymbolFlags.IsContainer) { container = node; - Debug.assert(container.nextContainer === undefined); if (lastContainer) { - Debug.assert(lastContainer.nextContainer === undefined); lastContainer.nextContainer = container; } @@ -391,7 +386,7 @@ module ts { if (isBindingPattern((node).name)) { bindChildren(node, 0, /*isBlockScopeContainer*/ false); } - else if (node.flags & NodeFlags.BlockScoped) { + else if (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) { bindBlockScopedVariableDeclaration(node); } else { @@ -483,9 +478,7 @@ module ts { break; } case SyntaxKind.Block: - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.SwitchStatement: diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a7726b786b..21633d97a3 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1,22 +1,11 @@ -/// -/// -/// -/// /// -/// -/// module ts { var nextSymbolId = 1; var nextNodeId = 1; - var nextMergeId = 1; - - /// fullTypeCheck denotes if this instance of the typechecker will be used to get semantic diagnostics. - /// If fullTypeCheck === true, then the typechecker should do every possible check to produce all errors - /// If fullTypeCheck === false, the typechecker can take shortcuts and skip checks that only produce errors. - /// NOTE: checks that somehow affect decisions being made during typechecking should be executed in both cases. - export function createTypeChecker(program: Program, fullTypeCheck: boolean): TypeChecker { + var nextMergeId = 1; + export function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker { var Symbol = objectAllocator.getSymbolConstructor(); var Type = objectAllocator.getTypeConstructor(); var Signature = objectAllocator.getSignatureConstructor(); @@ -26,19 +15,17 @@ module ts { var emptyArray: any[] = []; var emptySymbols: SymbolTable = {}; - var compilerOptions = program.getCompilerOptions(); + var compilerOptions = host.getCompilerOptions(); + var emitResolver = createResolver(); var checker: TypeChecker = { - getProgram: () => program, - getNodeCount: () => sum(program.getSourceFiles(), "nodeCount"), - getIdentifierCount: () => sum(program.getSourceFiles(), "identifierCount"), - getSymbolCount: () => sum(program.getSourceFiles(), "symbolCount"), + getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"), + getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"), + getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount"), getTypeCount: () => typeCount, isUndefinedSymbol: symbol => symbol === undefinedSymbol, isArgumentsSymbol: symbol => symbol === argumentsSymbol, - emitFiles: invokeEmitter, getDiagnostics, - getDeclarationDiagnostics, getGlobalDiagnostics, getTypeOfSymbolAtLocation, getDeclaredTypeOfSymbol, @@ -64,8 +51,7 @@ module ts { getSignatureFromDeclaration, isImplementationOfOverload, getAliasedSymbol: resolveImport, - hasEarlyErrors, - isEmitBlocked, + getEmitResolver: () => emitResolver, }; var undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); @@ -285,7 +271,7 @@ module ts { return true; } - var sourceFiles = program.getSourceFiles(); + var sourceFiles = host.getSourceFiles(); return sourceFiles.indexOf(file1) <= sourceFiles.indexOf(file2); } @@ -407,7 +393,7 @@ module ts { } if (result.flags & SymbolFlags.BlockScopedVariable) { // Block-scoped variables cannot be used before their definition - var declaration = forEach(result.declarations, d => d.flags & NodeFlags.BlockScoped ? d : undefined); + var declaration = forEach(result.declarations, d => getCombinedNodeFlags(d) & NodeFlags.BlockScoped ? d : undefined); Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); if (!isDefinedBefore(declaration, errorLocation)) { error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name)); @@ -532,7 +518,7 @@ module ts { } while (true) { var filename = normalizePath(combinePaths(searchPath, moduleName)); - var sourceFile = program.getSourceFile(filename + ".ts") || program.getSourceFile(filename + ".d.ts"); + var sourceFile = host.getSourceFile(filename + ".ts") || host.getSourceFile(filename + ".d.ts"); if (sourceFile || isRelative) break; var parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) break; @@ -657,7 +643,7 @@ module ts { var members = node.members; for (var i = 0; i < members.length; i++) { var member = members[i]; - if (member.kind === SyntaxKind.Constructor && (member).body) { + if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; } } @@ -771,7 +757,7 @@ module ts { // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table) // and if symbolfrom symbolTable or alias resolution matches the symbol, // check the symbol can be qualified, it is only then this symbol is accessible - return !forEach(symbolFromSymbolTable.declarations, declaration => hasExternalModuleSymbol(declaration)) && + return !forEach(symbolFromSymbolTable.declarations, hasExternalModuleSymbol) && canQualifySymbol(symbolFromSymbolTable, meaning); } } @@ -875,7 +861,7 @@ module ts { // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - var symbolExternalModule = forEach(initialSymbol.declarations, declaration => getExternalModuleContainer(declaration)); + var symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { @@ -1095,7 +1081,7 @@ module ts { } else { // If we didn't find accessible symbol chain for this symbol, break if this is external module - if (!parentSymbol && ts.forEach(symbol.declarations, declaration => hasExternalModuleSymbol(declaration))) { + if (!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) { return; } @@ -1564,7 +1550,7 @@ module ts { case SyntaxKind.ImportDeclaration: var parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(node.flags & NodeFlags.Export) && + if (!(getCombinedNodeFlags(node) & NodeFlags.Export) && !(node.kind !== SyntaxKind.ImportDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) { return isGlobalSourceFile(parent) || isUsedInExportAssignment(node); } @@ -1589,7 +1575,6 @@ module ts { case SyntaxKind.IndexSignature: case SyntaxKind.Parameter: case SyntaxKind.ModuleBlock: - case SyntaxKind.TypeParameter: case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: case SyntaxKind.TypeLiteral: @@ -1599,7 +1584,9 @@ module ts { case SyntaxKind.UnionType: case SyntaxKind.ParenthesizedType: return isDeclarationVisible(node.parent); - + + // Type parameters are always visible + case SyntaxKind.TypeParameter: // Source file is always visible case SyntaxKind.SourceFile: return true; @@ -1627,7 +1614,10 @@ module ts { function getDeclarationContainer(node: Node): Node { node = getRootDeclaration(node); - return node.kind === SyntaxKind.VariableDeclaration ? node.parent.parent : node.parent; + + // Parent chain: + // VaribleDeclaration -> VariableDeclarationList -> VariableStatement -> 'Declaration Container' + return node.kind === SyntaxKind.VariableDeclaration ? node.parent.parent.parent : node.parent; } function getTypeOfPrototypeProperty(prototype: Symbol): Type { @@ -1701,7 +1691,7 @@ module ts { // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration: VariableLikeDeclaration): Type { // A variable declared in a for..in statement is always of type any - if (declaration.parent.kind === SyntaxKind.ForInStatement) { + if (declaration.parent.parent.kind === SyntaxKind.ForInStatement) { return anyType; } if (isBindingPattern(declaration.parent)) { @@ -2635,7 +2625,7 @@ module ts { returnType = getAnnotatedAccessorType(setter); } - if (!returnType && !(declaration).body) { + if (!returnType && nodeIsMissing((declaration).body)) { returnType = anyType; } } @@ -3353,7 +3343,7 @@ module ts { } function isContextSensitiveFunctionLikeDeclaration(node: FunctionLikeDeclaration) { - return !node.typeParameters && !forEach(node.parameters, p => p.type); + return !node.typeParameters && node.parameters.length && !forEach(node.parameters, p => p.type); } function getTypeWithoutConstructors(type: Type): Type { @@ -3433,7 +3423,7 @@ module ts { if (containingMessageChain) { errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } - addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, host.getCompilerHost().getNewLine())); } return result !== Ternary.False; @@ -3662,9 +3652,7 @@ module ts { var maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up var destinationCache = result === Ternary.True || depth === 0 ? relation : maybeStack[depth - 1]; - for (var p in maybeCache) { - destinationCache[p] = maybeCache[p]; - } + copyMap(/*source*/maybeCache, /*target*/destinationCache); } else { // A false result goes straight into global cache (when something is false under assumptions it @@ -4027,7 +4015,7 @@ module ts { result &= related; } } - else if (source.typeParameters || source.typeParameters) { + else if (source.typeParameters || target.typeParameters) { return Ternary.False; } // Spec 1.0 Section 3.8.3 & 3.8.4: @@ -4133,7 +4121,7 @@ module ts { return anyType; } if (type.flags & TypeFlags.Union) { - return getUnionType(map((type).types, t => getWidenedType(t))); + return getUnionType(map((type).types, getWidenedType)); } if (isTypeOfObjectLiteral(type)) { return getWidenedTypeOfObjectLiteral(type); @@ -4206,7 +4194,7 @@ module ts { } function reportErrorsFromWidening(declaration: Declaration, type: Type) { - if (fullTypeCheck && compilerOptions.noImplicitAny && type.flags & TypeFlags.Unwidened) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & TypeFlags.Unwidened) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); @@ -4551,9 +4539,7 @@ module ts { case SyntaxKind.LabeledStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.TryStatement: - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: return forEachChild(node, isAssignedIn); } return false; @@ -5070,17 +5056,25 @@ module ts { return undefined; } - // In a typed function call, an argument expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(node: Expression): Type { - var callExpression = node.parent; - var argIndex = indexOf(callExpression.arguments, node); + // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. + function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression): Type { + var args = getEffectiveCallArguments(callTarget); + var argIndex = indexOf(args, arg); if (argIndex >= 0) { - var signature = getResolvedSignature(callExpression); + var signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; } + function getContextualTypeForSubstitutionExpression(template: TemplateExpression, substitutionExpression: Expression) { + if (template.parent.kind === SyntaxKind.TaggedTemplateExpression) { + return getContextualTypeForArgument(template.parent, substitutionExpression); + } + + return undefined; + } + function getContextualTypeForBinaryOperand(node: Expression): Type { var binaryExpression = node.parent; var operator = binaryExpression.operator; @@ -5142,7 +5136,7 @@ module ts { // Return true if the given contextual type is a tuple-like type function contextualTypeIsTupleLikeType(type: Type): boolean { - return !!(type.flags & TypeFlags.Union ? forEach((type).types, t => isTupleLikeType(t)) : isTupleLikeType(type)); + return !!(type.flags & TypeFlags.Union ? forEach((type).types, isTupleLikeType) : isTupleLikeType(type)); } // Return true if the given contextual type provides an index signature of the given kind @@ -5218,7 +5212,7 @@ module ts { return getContextualTypeForReturnExpression(node); case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - return getContextualTypeForArgument(node); + return getContextualTypeForArgument(parent, node); case SyntaxKind.TypeAssertionExpression: return getTypeFromTypeNode((parent).type); case SyntaxKind.BinaryExpression: @@ -5229,6 +5223,9 @@ module ts { return getContextualTypeForElementExpression(node); case SyntaxKind.ConditionalExpression: return getContextualTypeForConditionalOperand(node); + case SyntaxKind.TemplateSpan: + Debug.assert(parent.parent.kind === SyntaxKind.TemplateExpression); + return getContextualTypeForSubstitutionExpression(parent.parent, node); } return undefined; } @@ -5287,7 +5284,7 @@ module ts { signatureList = [signature]; } else if (!compareSignatures(signatureList[0], signature, /*compareReturnTypes*/ false, compareTypes)) { - // Signatures arent identical, do not use + // Signatures aren't identical, do not use return undefined; } else { @@ -5481,7 +5478,7 @@ module ts { } function getDeclarationFlagsFromSymbol(s: Symbol) { - return s.valueDeclaration ? s.valueDeclaration.flags : s.flags & SymbolFlags.Prototype ? NodeFlags.Public | NodeFlags.Static : 0; + return s.valueDeclaration ? getCombinedNodeFlags(s.valueDeclaration) : s.flags & SymbolFlags.Prototype ? NodeFlags.Public | NodeFlags.Static : 0; } function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol) { @@ -5889,7 +5886,7 @@ module ts { } /** - * Returns the effective arguments for an expression that works like a function invokation. + * Returns the effective arguments for an expression that works like a function invocation. * * If 'node' is a CallExpression or a NewExpression, then its argument list is returned. * If 'node' is a TaggedTemplateExpression, a new argument list is constructed from the substitution @@ -6038,7 +6035,7 @@ module ts { // Pick the first candidate that matches the arity. This way we can get a contextual type for cases like: // declare function f(a: { xa: number; xb: number; }); // f({ | - if (!fullTypeCheck) { + if (!produceDiagnostics) { for (var i = 0, n = candidates.length; i < n; i++) { if (hasCorrectArity(node, args, candidates[i])) { return candidates[i]; @@ -6343,7 +6340,7 @@ module ts { function checkTypeAssertion(node: TypeAssertion): Type { var exprType = checkExpression(node.expression); var targetType = getTypeFromTypeNode(node.type); - if (fullTypeCheck && targetType !== unknownType) { + if (produceDiagnostics && targetType !== unknownType) { var widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); @@ -6429,7 +6426,7 @@ module ts { // must have at least one return statement somewhere in its body. // An exception to this rule is if the function implementation consists of a single 'throw' statement. function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func: FunctionLikeDeclaration, returnType: Type): void { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } @@ -6439,7 +6436,7 @@ module ts { } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (!func.body || func.body.kind !== SyntaxKind.Block) { + if (nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block) { return; } @@ -6501,7 +6498,7 @@ module ts { } } - if (fullTypeCheck && node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) { + if (produceDiagnostics && node.kind !== SyntaxKind.MethodDeclaration && node.kind !== SyntaxKind.MethodSignature) { checkCollisionWithCapturedSuperVariable(node, (node).name); checkCollisionWithCapturedThisVariable(node,(node).name); } @@ -6950,7 +6947,7 @@ module ts { } function checkAssignmentOperator(valueType: Type): void { - if (fullTypeCheck && operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { + if (produceDiagnostics && operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { // TypeScript 1.0 spec (April 2014): 4.17 // An assignment of the form // VarExpr = ValueExpr @@ -7162,7 +7159,7 @@ module ts { } checkSourceElement(node.constraint); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeParameterHasIllegalReferencesInConstraint(node); checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0); } @@ -7184,7 +7181,7 @@ module ts { var func = getContainingFunction(node); if (node.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)) { func = getContainingFunction(node); - if (!(func.kind === SyntaxKind.Constructor && func.body)) { + if (!(func.kind === SyntaxKind.Constructor && nodeIsPresent(func.body))) { error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } @@ -7212,7 +7209,7 @@ module ts { if (node.type) { checkSourceElement(node.type); } - if (fullTypeCheck) { + if (produceDiagnostics) { checkCollisionWithArgumentsInGeneratedCode(node); if (compilerOptions.noImplicitAny && !node.type) { switch (node.kind) { @@ -7303,11 +7300,11 @@ module ts { } // exit early in the case of signature - super checks are not relevant to them - if (!node.body) { + if (nodeIsMissing(node.body)) { return; } - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } @@ -7375,12 +7372,12 @@ module ts { } function checkAccessorDeclaration(node: AccessorDeclaration) { - // Grammar checking accessors - checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); + if (produceDiagnostics) { + // Grammar checking accessors + checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); - if (fullTypeCheck) { if (node.kind === SyntaxKind.GetAccessor) { - if (!isInAmbientContext(node) && node.body && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { + if (!isInAmbientContext(node) && nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { error(node.name, Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } @@ -7424,7 +7421,7 @@ module ts { for (var i = 0; i < len; i++) { checkSourceElement(node.typeArguments[i]); var constraint = getConstraintOfTypeParameter((type).target.typeParameters[i]); - if (fullTypeCheck && constraint) { + if (produceDiagnostics && constraint) { var typeArgument = (type).typeArguments[i]; checkTypeAssignableTo(typeArgument, constraint, node, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } @@ -7438,7 +7435,7 @@ module ts { function checkTypeLiteral(node: TypeLiteralNode) { forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); @@ -7468,7 +7465,7 @@ module ts { } function checkSpecializedSignatureDeclaration(signatureDeclarationNode: SignatureDeclaration): void { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } var signature = getSignatureFromDeclaration(signatureDeclarationNode); @@ -7478,7 +7475,7 @@ module ts { // TypeScript 1.0 spec (April 2014): 3.7.2.2 // Specialized signatures are not permitted in conjunction with a function body - if ((signatureDeclarationNode).body) { + if (nodeIsPresent((signatureDeclarationNode).body)) { error(signatureDeclarationNode, Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type); return; } @@ -7511,7 +7508,7 @@ module ts { } function getEffectiveDeclarationFlags(n: Node, flagsToCheck: NodeFlags) { - var flags = n.flags; + var flags = getCombinedNodeFlags(n); if (n.parent.kind !== SyntaxKind.InterfaceDeclaration && isInAmbientContext(n)) { if (!(flags & NodeFlags.Ambient)) { // It is nested in an ambient context, which means it is automatically exported @@ -7524,7 +7521,7 @@ module ts { } function checkFunctionOrConstructorSymbol(symbol: Symbol): void { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } @@ -7611,7 +7608,7 @@ module ts { error(errorNode, diagnostic); return; } - else if ((subsequentNode).body) { + else if (nodeIsPresent((subsequentNode).body)) { error(errorNode, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name)); return; } @@ -7653,7 +7650,7 @@ module ts { someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node); - if (node.body && bodyDeclaration) { + if (nodeIsPresent(node.body) && bodyDeclaration) { if (isConstructor) { multipleConstructorImplementation = true; } @@ -7665,7 +7662,7 @@ module ts { reportImplementationExpectedError(previousDeclaration); } - if (node.body) { + if (nodeIsPresent(node.body)) { if (!bodyDeclaration) { bodyDeclaration = node; } @@ -7734,7 +7731,7 @@ module ts { } function checkExportsOnMergedDeclarations(node: Node): void { - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } @@ -7808,12 +7805,12 @@ module ts { } function checkFunctionDeclaration(node: FunctionDeclaration): void { - // Grammar Checking, check signature of function declaration as checkFunctionLikeDeclaration call checkGarmmarFunctionLikeDeclaration - checkFunctionLikeDeclaration(node); - //Grammar check other component of the functionDeclaration - checkGrammarFunctionName(node.name) || checkGrammarForGenerator(node); + if (produceDiagnostics) { + checkFunctionLikeDeclaration(node) || + checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || + checkGrammarFunctionName(node.name) || + checkGrammarForGenerator(node); - if (fullTypeCheck) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -7852,7 +7849,7 @@ module ts { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method // in an ambient context - if (compilerOptions.noImplicitAny && !node.body && !node.type && !isPrivateWithinAmbient(node)) { + if (compilerOptions.noImplicitAny && nodeIsMissing(node.body) && !node.type && !isPrivateWithinAmbient(node)) { reportImplicitAnyError(node, anyType); } } @@ -7871,7 +7868,7 @@ module ts { function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) { // no rest parameters \ declaration context \ overload - no codegen impact - if (!hasRestParameters(node) || isInAmbientContext(node) || !(node).body) { + if (!hasRestParameters(node) || isInAmbientContext(node) || nodeIsMissing((node).body)) { return; } @@ -7903,7 +7900,7 @@ module ts { } var root = getRootDeclaration(node); - if (root.kind === SyntaxKind.Parameter && !(root.parent).body) { + if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent).body)) { // just an overload - no codegen impact return false; } @@ -7996,7 +7993,7 @@ module ts { // const x = 0; // var x = 0; // } - if (node.initializer && (node.flags & NodeFlags.BlockScoped) === 0) { + if (node.initializer && (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) === 0) { var symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { var localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); @@ -8063,7 +8060,7 @@ module ts { forEach((node.name).elements, checkSourceElement); } // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body - if (node.initializer && getRootDeclaration(node).kind === SyntaxKind.Parameter && !getContainingFunction(node).body) { + if (node.initializer && getRootDeclaration(node).kind === SyntaxKind.Parameter && nodeIsMissing(getContainingFunction(node).body)) { error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation); return; } @@ -8117,9 +8114,27 @@ module ts { function checkVariableStatement(node: VariableStatement) { // Grammar checking - checkGrammarModifiers(node) || checkGrammarVariableDeclarations(node, node.declarations) || checkGrammarForDisallowedLetOrConstStatement(node); + checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || checkGrammarModifiers(node) || checkGrammarVariableDeclarationList(node.declarationList) || checkGrammarForDisallowedLetOrConstStatement(node); - forEach(node.declarations, checkSourceElement); + forEach(node.declarationList.declarations, checkSourceElement); + } + + function checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node: Node) { + if (node.modifiers) { + if (inBlockOrObjectLiteralExpression(node)) { + return grammarErrorOnFirstToken(node, Diagnostics.Modifiers_cannot_appear_here); + } + } + } + + function inBlockOrObjectLiteralExpression(node: Node) { + while (node) { + if (node.kind === SyntaxKind.Block || node.kind === SyntaxKind.ObjectLiteralExpression) { + return true; + } + + node = node.parent; + } } function checkExpressionStatement(node: ExpressionStatement) { @@ -8156,10 +8171,21 @@ module ts { function checkForStatement(node: ForStatement) { // Grammar checking - checkGrammarForStatementInAmbientContext(node) || checkGrammarVariableDeclarations(node, node.declarations); + if (!checkGrammarForStatementInAmbientContext(node)) { + if (node.initializer && node.initializer.kind == SyntaxKind.VariableDeclarationList) { + checkGrammarVariableDeclarationList(node.initializer); + } + } + + if (node.initializer) { + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { + forEach((node.initializer).declarations, checkVariableDeclaration) + } + else { + checkExpression(node.initializer) + } + } - if (node.declarations) forEach(node.declarations, checkVariableDeclaration); - if (node.initializer) checkExpression(node.initializer); if (node.condition) checkExpression(node.condition); if (node.iterator) checkExpression(node.iterator); checkSourceElement(node.statement); @@ -8168,10 +8194,12 @@ module ts { function checkForInStatement(node: ForInStatement) { // Grammar checking if (!checkGrammarForStatementInAmbientContext(node)) { - var declarations = node.declarations; - if (!checkGrammarVariableDeclarations(node, declarations)) { - if (declarations && declarations.length > 1) { - grammarErrorOnFirstToken(declarations[1], Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { + var variableList = node.initializer; + if (!checkGrammarVariableDeclarationList(variableList)) { + if (variableList.declarations.length > 1) { + grammarErrorOnFirstToken(variableList.declarations[1], Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement); + } } } } @@ -8181,28 +8209,29 @@ module ts { // for (var VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; checkVariableDeclaration(decl); if (decl.type) { error(decl, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation); } } } - - // In a 'for-in' statement of the form - // for (Var in Expr) Statement - // Var must be an expression classified as a reference of type Any or the String primitive type, - // and Expr must be an expression of type Any, an object type, or a type parameter type. - if (node.variable) { - var exprType = checkExpression(node.variable); + else { + // In a 'for-in' statement of the form + // for (Var in Expr) Statement + // Var must be an expression classified as a reference of type Any or the String primitive type, + // and Expr must be an expression of type Any, an object type, or a type parameter type. + var varExpr = node.initializer; + var exprType = checkExpression(varExpr); if (exprType !== anyType && exprType !== stringType) { - error(node.variable, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); + error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any); } else { // run check only former check succeeded to avoid cascading errors - checkReferenceExpression(node.variable, Diagnostics.Invalid_left_hand_side_in_for_in_statement, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + checkReferenceExpression(varExpr, Diagnostics.Invalid_left_hand_side_in_for_in_statement, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); } } @@ -8293,7 +8322,7 @@ module ts { } } - if (fullTypeCheck && clause.kind === SyntaxKind.CaseClause) { + if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) { var caseClause = clause; // TypeScript 1.0 spec (April 2014):5.9 // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. @@ -8453,7 +8482,7 @@ module ts { var node = typeParameterDeclarations[i]; checkTypeParameter(node); - if (fullTypeCheck) { + if (produceDiagnostics) { for (var j = 0; j < i; j++) { if (typeParameterDeclarations[j].symbol === node.symbol) { error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name)); @@ -8482,7 +8511,7 @@ module ts { checkTypeReference(baseTypeNode); } if (type.baseTypes.length) { - if (fullTypeCheck) { + if (produceDiagnostics) { var baseType = type.baseTypes[0]; checkTypeAssignableTo(type, baseType, node.name, Diagnostics.Class_0_incorrectly_extends_base_class_1); var staticBaseType = getTypeOfSymbol(baseType.symbol); @@ -8503,7 +8532,7 @@ module ts { if (implementedTypeNodes) { forEach(implementedTypeNodes, typeRefNode => { checkTypeReference(typeRefNode); - if (fullTypeCheck) { + if (produceDiagnostics) { var t = getTypeFromTypeReferenceNode(typeRefNode); if (t !== unknownType) { var declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; @@ -8519,7 +8548,7 @@ module ts { } forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -8661,7 +8690,7 @@ module ts { var errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_properties_0_of_types_1_and_2_are_not_identical, prop.name, typeName1, typeName2); errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); - addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, program.getCompilerHost().getNewLine())); + addDiagnostic(createDiagnosticForNodeFromMessageChain(typeNode, errorInfo, host.getCompilerHost().getNewLine())); } } } @@ -8675,7 +8704,7 @@ module ts { checkGrammarModifiers(node) || checkGrammarInterfaceDeclaration(node); checkTypeParameters(node.typeParameters); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); @@ -8702,7 +8731,7 @@ module ts { forEach(getInterfaceBaseTypeNodes(node), checkTypeReference); forEach(node.members, checkSourceElement); - if (fullTypeCheck) { + if (produceDiagnostics) { checkTypeForDuplicateIndexSignatures(node); } } @@ -8874,13 +8903,13 @@ module ts { } function checkEnumDeclaration(node: EnumDeclaration) { - // Grammar checking - checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); - - if (!fullTypeCheck) { + if (!produceDiagnostics) { return; } + // Grammar checking + checkGrammarModifiers(node) || checkGrammarEnumDeclaration(node); + checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0); checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); @@ -8936,7 +8965,7 @@ module ts { var declarations = symbol.declarations; for (var i = 0; i < declarations.length; i++) { var declaration = declarations[i]; - if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && (declaration).body)) && !isInAmbientContext(declaration)) { + if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && !isInAmbientContext(declaration)) { return declaration; } } @@ -8944,33 +8973,38 @@ module ts { } function checkModuleDeclaration(node: ModuleDeclaration) { - // Grammar checking - if (!checkGrammarModifiers(node)) { - if (!isInAmbientContext(node) && node.name.kind === SyntaxKind.StringLiteral) { - grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); - } - else if (node.name.kind === SyntaxKind.Identifier && node.body.kind === SyntaxKind.ModuleBlock) { - var statements = (node.body).statements; - for (var i = 0, n = statements.length; i < n; i++) { - var statement = statements[i]; + if (produceDiagnostics) { + // Grammar checking + if (!checkGrammarModifiers(node)) { + if (!isInAmbientContext(node) && node.name.kind === SyntaxKind.StringLiteral) { + grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names); + } + else if (node.name.kind === SyntaxKind.Identifier && node.body.kind === SyntaxKind.ModuleBlock) { + var statements = (node.body).statements; + for (var i = 0, n = statements.length; i < n; i++) { + var statement = statements[i]; - if (statement.kind === SyntaxKind.ExportAssignment) { - // Export assignments are not allowed in an internal module - grammarErrorOnNode(statement, Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); - } - else if (isExternalModuleImportDeclaration(statement)) { - grammarErrorOnNode(getExternalModuleImportDeclarationExpression(statement), Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + if (statement.kind === SyntaxKind.ExportAssignment) { + // Export assignments are not allowed in an internal module + grammarErrorOnNode(statement, Diagnostics.An_export_assignment_cannot_be_used_in_an_internal_module); + } + else if (isExternalModuleImportDeclaration(statement)) { + grammarErrorOnNode(getExternalModuleImportDeclarationExpression(statement), Diagnostics.Import_declarations_in_an_internal_module_cannot_reference_an_external_module); + } } } } - } - if (fullTypeCheck) { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); - if (symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length > 1 && !isInAmbientContext(node)) { + + // The following checks only apply on a non-ambient instantiated module declaration. + if (symbol.flags & SymbolFlags.ValueModule + && symbol.declarations.length > 1 + && !isInAmbientContext(node) + && isInstantiatedModule(node, compilerOptions.preserveConstEnums)) { var classOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (classOrFunc) { if (getSourceFileOfNode(node) !== getSourceFileOfNode(classOrFunc)) { @@ -8981,6 +9015,8 @@ module ts { } } } + + // Checks for ambient external modules. if (node.name.kind === SyntaxKind.StringLiteral) { if (!isGlobalSourceFile(node.parent)) { error(node.name, Diagnostics.Ambient_external_modules_cannot_be_nested_in_other_modules); @@ -9228,6 +9264,8 @@ module ts { case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: case SyntaxKind.TaggedTemplateExpression: + case SyntaxKind.TemplateExpression: + case SyntaxKind.TemplateSpan: case SyntaxKind.TypeAssertionExpression: case SyntaxKind.ParenthesizedExpression: case SyntaxKind.TypeOfExpression: @@ -9256,10 +9294,9 @@ module ts { case SyntaxKind.LabeledStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.TryStatement: - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: case SyntaxKind.VariableDeclaration: + case SyntaxKind.VariableDeclarationList: case SyntaxKind.ClassDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.EnumMember: @@ -9306,7 +9343,7 @@ module ts { } function getSortedDiagnostics(): Diagnostic[]{ - Debug.assert(fullTypeCheck, "diagnostics are available only in the full typecheck mode"); + Debug.assert(produceDiagnostics, "diagnostics are available only in the full typecheck mode"); if (diagnosticsModified) { diagnostics.sort(compareDiagnostics); @@ -9316,23 +9353,25 @@ module ts { return diagnostics; } - function getDiagnostics(sourceFile?: SourceFile): Diagnostic[]{ + function getDiagnostics(sourceFile?: SourceFile): Diagnostic[] { + throwIfNonDiagnosticsProducing(); if (sourceFile) { checkSourceFile(sourceFile); return filter(getSortedDiagnostics(), d => d.file === sourceFile); } - forEach(program.getSourceFiles(), checkSourceFile); + forEach(host.getSourceFiles(), checkSourceFile); return getSortedDiagnostics(); } - function getDeclarationDiagnostics(targetSourceFile: SourceFile): Diagnostic[] { - var resolver = createResolver(); - checkSourceFile(targetSourceFile); - return ts.getDeclarationDiagnostics(program, resolver, targetSourceFile); + function getGlobalDiagnostics(): Diagnostic[]{ + throwIfNonDiagnosticsProducing(); + return filter(getSortedDiagnostics(), d => !d.file); } - function getGlobalDiagnostics(): Diagnostic[] { - return filter(getSortedDiagnostics(), d => !d.file); + function throwIfNonDiagnosticsProducing() { + if (!produceDiagnostics) { + throw new Error("Trying to get diagnostics from a type checker that does not produce them."); + } } // Language service support @@ -9770,8 +9809,20 @@ module ts { function isUniqueLocalName(name: string, container: Node): boolean { for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && hasProperty(node.locals, name) && node.locals[name].flags & (SymbolFlags.Value | SymbolFlags.ExportValue)) { - return false; + if (node.locals && hasProperty(node.locals, name)) { + var symbolWithRelevantName = node.locals[name]; + if (symbolWithRelevantName.flags & (SymbolFlags.Value | SymbolFlags.ExportValue)) { + return false; + } + + // An import can be emitted too, if it is referenced as a value. + // Make sure the name in question does not collide with an import. + if (symbolWithRelevantName.flags & SymbolFlags.Import) { + var importDeclarationWithRelevantName = getDeclarationOfKind(symbolWithRelevantName, SyntaxKind.ImportDeclaration); + if (isReferencedImportDeclaration(importDeclarationWithRelevantName)) { + return false; + } + } } } return true; @@ -9837,16 +9888,6 @@ module ts { return getDiagnostics(sourceFile).length > 0 || getGlobalDiagnostics().length > 0; } - function isEmitBlocked(sourceFile?: SourceFile): boolean { - return program.getDiagnostics(sourceFile).length !== 0 || - hasEarlyErrors(sourceFile) || - (compilerOptions.noEmitOnError && getDiagnostics(sourceFile).length !== 0); - } - - function hasEarlyErrors(sourceFile?: SourceFile): boolean { - return forEach(getDiagnostics(sourceFile), d => d.isEarly); - } - function isImportResolvedToValue(symbol: Symbol): boolean { var target = resolveImport(symbol); // const enums and modules that contain only const enums are not considered values from the emit perespective @@ -9871,7 +9912,7 @@ module ts { } function isImplementationOfOverload(node: FunctionLikeDeclaration) { - if (node.body) { + if (nodeIsPresent(node.body)) { var symbol = getSymbolOfNode(node); var signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -9934,7 +9975,6 @@ module ts { function createResolver(): EmitResolver { return { - getProgram: () => program, getLocalNameOfContainer, getExpressionNamePrefix, getExportAssignmentName, @@ -9943,7 +9983,6 @@ module ts { getEnumMemberValue, isTopLevelValueImportWithEntityName, hasSemanticErrors, - isEmitBlocked, isDeclarationVisible, isImplementationOfOverload, writeTypeOfDeclaration, @@ -9955,19 +9994,14 @@ module ts { }; } - function invokeEmitter(targetSourceFile?: SourceFile) { - var resolver = createResolver(); - return emitFiles(resolver, targetSourceFile); - } - function initializeTypeChecker() { // Bind all source files and propagate errors - forEach(program.getSourceFiles(), file => { + forEach(host.getSourceFiles(), file => { bindSourceFile(file); forEach(file.semanticDiagnostics, addDiagnostic); }); // Initialize global symbol table - forEach(program.getSourceFiles(), file => { + forEach(host.getSourceFiles(), file => { if (!isExternalModule(file)) { extendSymbolTable(globals, file.locals); } @@ -10504,11 +10538,21 @@ module ts { } function checkGrammarMethod(node: MethodDeclaration) { - if (checkGrammarFunctionLikeDeclaration(node) || + if (checkGrammarDisallowedModifiersInBlockOrObjectLiteralExpression(node) || + checkGrammarFunctionLikeDeclaration(node) || checkGrammarForGenerator(node)) { return true; } + if (node.parent.kind === SyntaxKind.ObjectLiteralExpression) { + if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional)) { + return true; + } + else if (node.body === undefined) { + return grammarErrorAtPos(getSourceFile(node), node.end - 1, ";".length, Diagnostics._0_expected, "{"); + } + } + if (node.parent.kind === SyntaxKind.ClassDeclaration) { if (checkGrammarForInvalidQuestionMark(node, node.questionToken, Diagnostics.A_class_member_cannot_be_declared_optional)) { return true; @@ -10642,24 +10686,22 @@ module ts { return checkGrammarEvalOrArgumentsInStrictMode(node, node.name); } - function checkGrammarVariableDeclarations(container: Node, declarations: NodeArray): boolean { - if (declarations) { - if (checkGrammarForDisallowedTrailingComma(declarations)) { - return true; - } + function checkGrammarVariableDeclarationList(declarationList: VariableDeclarationList): boolean { + var declarations = declarationList.declarations; + if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { + return true; + } - if (!declarations.length) { - return grammarErrorAtPos(getSourceFileOfNode(container), declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); - } + if (!declarationList.declarations.length) { + return grammarErrorAtPos(getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, Diagnostics.Variable_declaration_list_cannot_be_empty); + } - var decl = declarations[0]; - if (compilerOptions.target < ScriptTarget.ES6) { - if (isLet(decl)) { - return grammarErrorOnFirstToken(decl, Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } - else if (isConst(decl)) { - return grammarErrorOnFirstToken(decl, Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); - } + if (compilerOptions.target < ScriptTarget.ES6) { + if (isLet(declarationList)) { + return grammarErrorOnFirstToken(declarationList, Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); + } + else if (isConst(declarationList)) { + return grammarErrorOnFirstToken(declarationList, Diagnostics.const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } } } @@ -10682,10 +10724,10 @@ module ts { function checkGrammarForDisallowedLetOrConstStatement(node: VariableStatement) { if (!allowLetAndConstDeclarations(node.parent)) { - if (isLet(node)) { + if (isLet(node.declarationList)) { return grammarErrorOnNode(node, Diagnostics.let_declarations_can_only_be_declared_inside_a_block); } - else if (isConst(node)) { + else if (isConst(node.declarationList)) { return grammarErrorOnNode(node, Diagnostics.const_declarations_can_only_be_declared_inside_a_block); } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index fabc897a35..9fe59b1ba2 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -54,6 +54,11 @@ module ts { paramType: Diagnostics.KIND, error: Diagnostics.Argument_for_module_option_must_be_commonjs_or_amd }, + { + name: "noEmit", + type: "boolean", + description: Diagnostics.Do_not_emit_outputs, + }, { name: "noEmitOnError", type: "boolean", diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 6e0c307034..2e5a471bb2 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -23,10 +23,10 @@ module ts { export interface StringSet extends Map { } - export function forEach(array: T[], callback: (element: T) => U): U { + export function forEach(array: T[], callback: (element: T, index: number) => U): U { if (array) { for (var i = 0, len = array.length; i < len; i++) { - var result = callback(array[i]); + var result = callback(array[i], i); if (result) { return result; } @@ -208,6 +208,12 @@ module ts { return result; } + export function copyMap(source: Map, target: Map): void { + for (var p in source) { + target[p] = source[p]; + } + } + /** * Creates a map from the elements of an array. * diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index c35a443db4..99d8d0b72f 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -143,8 +143,9 @@ module ts { A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer.", isEarly: true }, Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts.", isEarly: true }, An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts.", isEarly: true }, - Merge_conflict_marker_encountered: { code: 1184, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." }, - A_rest_element_cannot_have_an_initializer: { code: 1185, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." }, + Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." }, + Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." }, + A_rest_element_cannot_have_an_initializer: { code: 1186, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." }, Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." }, @@ -379,6 +380,8 @@ module ts { Could_not_write_file_0_Colon_1: { code: 5033, category: DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" }, Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, + Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option noEmit cannot be specified with option out or outDir." }, + Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option noEmit cannot be specified with option declaration." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: DiagnosticCategory.Message, key: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -388,6 +391,7 @@ module ts { Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: DiagnosticCategory.Message, key: "Do not erase const enum declarations in generated code." }, Do_not_emit_outputs_if_any_type_checking_errors_were_reported: { code: 6008, category: DiagnosticCategory.Message, key: "Do not emit outputs if any type checking errors were reported." }, Do_not_emit_comments_to_output: { code: 6009, category: DiagnosticCategory.Message, key: "Do not emit comments to output." }, + Do_not_emit_outputs: { code: 6010, category: DiagnosticCategory.Message, key: "Do not emit outputs." }, Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" }, Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs' or 'amd'" }, Print_this_message: { code: 6017, category: DiagnosticCategory.Message, key: "Print this message." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 466977dee9..5bec530172 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -661,14 +661,18 @@ "code": 1184, "isEarly": true }, - "Merge conflict marker encountered.": { + "Modifiers cannot appear here.": { "category": "Error", "code": 1184 }, - "A rest element cannot have an initializer.": { + "Merge conflict marker encountered.": { "category": "Error", "code": 1185 }, + "A rest element cannot have an initializer.": { + "category": "Error", + "code": 1186 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1612,6 +1616,14 @@ "category": "Error", "code": 5039 }, + "Option noEmit cannot be specified with option out or outDir.": { + "category": "Error", + "code": 5040 + }, + "Option noEmit cannot be specified with option declaration.": { + "category": "Error", + "code": 5041 + }, "Concatenate and emit output to single file.": { "category": "Message", "code": 6001 @@ -1648,6 +1660,10 @@ "category": "Message", "code": 6009 }, + "Do not emit outputs.": { + "category": "Message", + "code": 6010 + }, "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)": { "category": "Message", "code": 6015 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index bb3de86bc7..d82e577971 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,8 +1,4 @@ -/// -/// -/// -/// -/// +/// module ts { interface EmitTextWriter { @@ -268,7 +264,7 @@ module ts { function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration { return forEach(node.members, member => { - if (member.kind === SyntaxKind.Constructor && (member).body) { + if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; } }); @@ -316,17 +312,16 @@ module ts { }; } - function getSourceFilePathInNewDir(sourceFile: SourceFile, program: Program, newDirPath: string) { - var compilerHost = program.getCompilerHost(); - var sourceFilePath = getNormalizedAbsolutePath(sourceFile.filename, compilerHost.getCurrentDirectory()); - sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), ""); + function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string) { + var sourceFilePath = getNormalizedAbsolutePath(sourceFile.filename, host.getCurrentDirectory()); + sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), ""); return combinePaths(newDirPath, sourceFilePath); } - function getOwnEmitOutputFilePath(sourceFile: SourceFile, program: Program, extension: string){ - var compilerOptions = program.getCompilerOptions(); + function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string){ + var compilerOptions = host.getCompilerOptions(); if (compilerOptions.outDir) { - var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, program, compilerOptions.outDir)); + var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); } else { var emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.filename); @@ -335,16 +330,15 @@ module ts { return emitOutputFilePathWithoutExtension + extension; } - function writeFile(compilerHost: CompilerHost, diagnostics: Diagnostic[], filename: string, data: string, writeByteOrderMark: boolean) { - compilerHost.writeFile(filename, data, writeByteOrderMark, hostErrorMessage => { + function writeFile(host: EmitHost, diagnostics: Diagnostic[], filename: string, data: string, writeByteOrderMark: boolean) { + host.writeFile(filename, data, writeByteOrderMark, hostErrorMessage => { diagnostics.push(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage)); }); } - function emitDeclarations(program: Program, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { - var newLine = program.getCompilerHost().getNewLine(); - var compilerOptions = program.getCompilerOptions(); - var compilerHost = program.getCompilerHost(); + function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { + var newLine = host.getNewLine(); + var compilerOptions = host.getCompilerOptions(); var write: (s: string) => void; var writeLine: () => void; @@ -1014,20 +1008,20 @@ module ts { } function emitVariableStatement(node: VariableStatement) { - var hasDeclarationWithEmit = forEach(node.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration)); + var hasDeclarationWithEmit = forEach(node.declarationList.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration)); if (hasDeclarationWithEmit) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (isLet(node)) { + if (isLet(node.declarationList)) { write("let "); } - else if (isConst(node)) { + else if (isConst(node.declarationList)) { write("const "); } else { write("var "); } - emitCommaList(node.declarations, emitVariableDeclaration); + emitCommaList(node.declarationList.declarations, emitVariableDeclaration); write(";"); writeLine(); } @@ -1400,14 +1394,14 @@ module ts { var declFileName = referencedFile.flags & NodeFlags.DeclarationFile ? referencedFile.filename // Declaration file, use declaration file name : shouldEmitToOwnFile(referencedFile, compilerOptions) - ? getOwnEmitOutputFilePath(referencedFile, program, ".d.ts") // Own output file so get the .d.ts file - : removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file + ? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file + : removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file declFileName = getRelativePathToDirectoryOrUrl( getDirectoryPath(normalizeSlashes(jsFilePath)), declFileName, - compilerHost.getCurrentDirectory(), - compilerHost.getCanonicalFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); referencePathsOutput += "/// " + newLine; @@ -1418,7 +1412,7 @@ module ts { if (!compilerOptions.noResolve) { var addedGlobalFileReference = false; forEach(root.referencedFiles, fileReference => { - var referencedFile = tryResolveScriptReference(program, root, fileReference); + var referencedFile = tryResolveScriptReference(host, root, fileReference); // All the references that are not going to be part of same file if (referencedFile && ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference @@ -1438,12 +1432,12 @@ module ts { else { // Emit references corresponding to this file var emittedReferencedFiles: SourceFile[] = []; - forEach(program.getSourceFiles(), sourceFile => { + forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { // Check what references need to be added if (!compilerOptions.noResolve) { forEach(sourceFile.referencedFiles, fileReference => { - var referencedFile = tryResolveScriptReference(program, sourceFile, fileReference); + var referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); // If the reference file is a declaration file or an external module, emit that reference if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && @@ -1467,22 +1461,21 @@ module ts { referencePathsOutput, } } - - export function getDeclarationDiagnostics(program: Program, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { + + export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { var diagnostics: Diagnostic[] = []; - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); - emitDeclarations(program, resolver, diagnostics, jsFilePath, targetSourceFile); + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); return diagnostics; } // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compilerOnSave feature - export function emitFiles(resolver: EmitResolver, targetSourceFile?: SourceFile): EmitResult { - var program = resolver.getProgram(); - var compilerHost = program.getCompilerHost(); - var compilerOptions = program.getCompilerOptions(); + export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile?: SourceFile): EmitResult { + // var program = resolver.getProgram(); + var compilerOptions = host.getCompilerOptions(); var sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined; var diagnostics: Diagnostic[] = []; - var newLine = program.getCompilerHost().getNewLine(); + var newLine = host.getNewLine(); function emitJavaScript(jsFilePath: string, root?: SourceFile) { var writer = createTextWriter(newLine); @@ -1704,12 +1697,12 @@ module ts { // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? program.getCommonSourceDirectory() : sourceMapDir; + var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.filename, - compilerHost.getCurrentDirectory(), - compilerHost.getCanonicalFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true)); sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; @@ -1805,7 +1798,7 @@ module ts { function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) { // Write source map file encodeLastRecordedSourceMapSpan(); - writeFile(compilerHost, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents( + writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents( 3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, @@ -1844,17 +1837,17 @@ module ts { if (root) { // emitting single module file // For modules or multiple emit files the mapRoot will have directory structure like the sources // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(root, program, sourceMapDir)); + sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(root, host, sourceMapDir)); } if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) { // The relative paths are relative to the common directory - sourceMapDir = combinePaths(program.getCommonSourceDirectory(), sourceMapDir); + sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir); sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl( getDirectoryPath(normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap - compilerHost.getCurrentDirectory(), - compilerHost.getCanonicalFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); } else { @@ -1890,7 +1883,7 @@ module ts { } function writeJavaScriptFile(emitOutput: string, writeByteOrderMark: boolean) { - writeFile(compilerHost, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); + writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); } // Create a temporary variable with a unique unused name. The forLoopVariable parameter signals that the @@ -2064,9 +2057,15 @@ module ts { write("("); } - emitLiteral(node.head); + var headEmitted = false; + if (shouldEmitTemplateHead()) { + emitLiteral(node.head); + headEmitted = true; + } + + for (var i = 0; i < node.templateSpans.length; i++) { + var templateSpan = node.templateSpans[i]; - forEach(node.templateSpans, templateSpan => { // Check if the expression has operands and binds its operands less closely than binary '+'. // If it does, we need to wrap the expression in parentheses. Otherwise, something like // `abc${ 1 << 2 }` @@ -2078,7 +2077,14 @@ module ts { // "abc" + (1 << 2) + "" var needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression && comparePrecedenceToBinaryPlus(templateSpan.expression) !== Comparison.GreaterThan; - write(" + "); + + if (i > 0 || headEmitted) { + // If this is the first span and the head was not emitted, then this templateSpan's + // expression will be the first to be emitted. Don't emit the preceding ' + ' in that + // case. + write(" + "); + } + emitParenthesized(templateSpan.expression, needsParens); // Only emit if the literal is non-empty. // The binary '+' operator is left-associative, so the first string concatenation @@ -2088,12 +2094,34 @@ module ts { write(" + ") emitLiteral(templateSpan.literal); } - }); + } if (emitOuterParens) { write(")"); } + function shouldEmitTemplateHead() { + // If this expression has an empty head literal and the first template span has a non-empty + // literal, then emitting the empty head literal is not necessary. + // `${ foo } and ${ bar }` + // can be emitted as + // foo + " and " + bar + // This is because it is only required that one of the first two operands in the emit + // output must be a string literal, so that the other operand and all following operands + // are forced into strings. + // + // If the first template span has an empty literal, then the head must still be emitted. + // `${ foo }${ bar }` + // must still be emitted as + // "" + foo + bar + + // There is always atleast one templateSpan in this code path, since + // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() + Debug.assert(node.templateSpans.length !== 0); + + return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; + } + function templateNeedsParens(template: TemplateExpression, parent: Expression) { switch (parent.kind) { case SyntaxKind.CallExpression: @@ -2113,7 +2141,8 @@ module ts { * or equal precedence to the binary '+' operator */ function comparePrecedenceToBinaryPlus(expression: Expression): Comparison { - // All binary expressions have lower precedence than '+' apart from '*', '/', and '%'. + // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' + // which have greater precedence and '-' which has equal precedence. // All unary operators have a higher precedence apart from yield. // Arrow functions and conditionals have a lower precedence, // although we convert the former into regular function expressions in ES5 mode, @@ -2130,6 +2159,7 @@ module ts { case SyntaxKind.PercentToken: return Comparison.GreaterThan; case SyntaxKind.PlusToken: + case SyntaxKind.MinusToken: return Comparison.EqualTo; default: return Comparison.LessThan; @@ -2681,20 +2711,22 @@ module ts { var endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); - if (node.declarations) { - if (node.declarations[0] && isLet(node.declarations[0])) { + if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { + var variableDeclarationList = node.initializer; + var declarations = variableDeclarationList.declarations; + if (declarations[0] && isLet(declarations[0])) { emitToken(SyntaxKind.LetKeyword, endPos); } - else if (node.declarations[0] && isConst(node.declarations[0])) { + else if (declarations[0] && isConst(declarations[0])) { emitToken(SyntaxKind.ConstKeyword, endPos); } else { emitToken(SyntaxKind.VarKeyword, endPos); } write(" "); - emitCommaList(node.declarations); + emitCommaList(variableDeclarationList.declarations); } - if (node.initializer) { + else if (node.initializer) { emit(node.initializer); } write(";"); @@ -2709,9 +2741,10 @@ module ts { var endPos = emitToken(SyntaxKind.ForKeyword, node.pos); write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); - if (node.declarations) { - if (node.declarations.length >= 1) { - var decl = node.declarations[0]; + if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { + var variableDeclarationList = node.initializer; + if (variableDeclarationList.declarations.length >= 1) { + var decl = variableDeclarationList.declarations[0]; if (isLet(decl)) { emitToken(SyntaxKind.LetKeyword, endPos); } @@ -2723,7 +2756,7 @@ module ts { } } else { - emit(node.variable); + emit(node.initializer); } write(" in "); emit(node.expression); @@ -2840,7 +2873,7 @@ module ts { function emitModuleMemberName(node: Declaration) { emitStart(node.name); - if (node.flags & NodeFlags.Export) { + if (getCombinedNodeFlags(node) & NodeFlags.Export) { var container = getContainingModule(node); write(container ? resolver.getLocalNameOfContainer(container) : "exports"); write("."); @@ -2853,7 +2886,7 @@ module ts { var emitCount = 0; // An exported declaration is actually emitted as an assignment (to a property on the module object), so // temporary variables in an exported declaration need to have real declarations elsewhere - var isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(root.flags & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter; + var isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(getCombinedNodeFlags(root) & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter; if (root.kind === SyntaxKind.BinaryExpression) { emitAssignmentExpression(root); } @@ -3086,17 +3119,17 @@ module ts { function emitVariableStatement(node: VariableStatement) { emitLeadingComments(node); if (!(node.flags & NodeFlags.Export)) { - if (isLet(node)) { + if (isLet(node.declarationList)) { write("let "); } - else if (isConst(node)) { + else if (isConst(node.declarationList)) { write("const "); } else { write("var "); } } - emitCommaList(node.declarations); + emitCommaList(node.declarationList.declarations); write(";"); emitTrailingComments(node); } @@ -3204,7 +3237,7 @@ module ts { } function emitFunctionDeclaration(node: FunctionLikeDeclaration) { - if (!node.body) { + if (nodeIsMissing(node.body)) { return emitPinnedOrTripleSlashComments(node); } @@ -3677,8 +3710,8 @@ module ts { } function emitModuleDeclaration(node: ModuleDeclaration) { - var shouldEmit = getModuleInstanceState(node) === ModuleInstanceState.Instantiated || - (getModuleInstanceState(node) === ModuleInstanceState.ConstEnumOnly && compilerOptions.preserveConstEnums); + // Emit only if this module is non-ambient. + var shouldEmit = isInstantiatedModule(node, compilerOptions.preserveConstEnums); if (!shouldEmit) { return emitPinnedOrTripleSlashComments(node); @@ -3922,6 +3955,7 @@ module ts { if (!node) { return; } + if (node.flags & NodeFlags.Ambient) { return emitPinnedOrTripleSlashComments(node); } @@ -4014,8 +4048,6 @@ module ts { case SyntaxKind.OmittedExpression: return; case SyntaxKind.Block: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return emitBlock(node); case SyntaxKind.VariableStatement: @@ -4213,7 +4245,7 @@ module ts { emit(root); } else { - forEach(program.getSourceFiles(), sourceFile => { + forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { emit(sourceFile); } @@ -4225,7 +4257,7 @@ module ts { } function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile) { - var emitDeclarationResult = emitDeclarations(program, resolver, diagnostics, jsFilePath, sourceFile); + var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); // TODO(shkamat): Should we not write any declaration file if any of them can produce error, // or should we just not write this file like we are doing now if (!emitDeclarationResult.reportedDeclarationError) { @@ -4240,7 +4272,7 @@ module ts { } }); declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos); - writeFile(compilerHost, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); + writeFile(host, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM); } } @@ -4250,11 +4282,11 @@ module ts { if (targetSourceFile === undefined) { // No targetSourceFile is specified (e.g. calling emitter from batch compiler) hasSemanticErrors = resolver.hasSemanticErrors(); - isEmitBlocked = resolver.isEmitBlocked(); + isEmitBlocked = host.isEmitBlocked(); - forEach(program.getSourceFiles(), sourceFile => { + forEach(host.getSourceFiles(), sourceFile => { if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = getOwnEmitOutputFilePath(sourceFile, program, ".js"); + var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js"); emitFile(jsFilePath, sourceFile); } }); @@ -4268,18 +4300,18 @@ module ts { if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { // If shouldEmitToOwnFile returns true or targetSourceFile is an external module file, then emit targetSourceFile in its own output file hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); - isEmitBlocked = resolver.isEmitBlocked(targetSourceFile); + isEmitBlocked = host.isEmitBlocked(targetSourceFile); - var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js"); + var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); emitFile(jsFilePath, targetSourceFile); } else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) { // Otherwise, if --out is specified and targetSourceFile is not a declaration file, // Emit all, non-external-module file, into one single output file - forEach(program.getSourceFiles(), sourceFile => { + forEach(host.getSourceFiles(), sourceFile => { if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); - isEmitBlocked = isEmitBlocked || resolver.isEmitBlocked(sourceFile); + isEmitBlocked = isEmitBlocked || host.isEmitBlocked(sourceFile); } }); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index b3d4cb5614..00cd54b94e 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1,5 +1,3 @@ -/// -/// /// /// @@ -154,8 +152,6 @@ module ts { case SyntaxKind.SpreadElementExpression: return child((node).expression); case SyntaxKind.Block: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return children((node).statements); case SyntaxKind.SourceFile: @@ -163,7 +159,9 @@ module ts { child((node).endOfFileToken); case SyntaxKind.VariableStatement: return children(node.modifiers) || - children((node).declarations); + child((node).declarationList); + case SyntaxKind.VariableDeclarationList: + return children((node).declarations); case SyntaxKind.ExpressionStatement: return child((node).expression); case SyntaxKind.IfStatement: @@ -177,14 +175,12 @@ module ts { return child((node).expression) || child((node).statement); case SyntaxKind.ForStatement: - return children((node).declarations) || - child((node).initializer) || + return child((node).initializer) || child((node).condition) || child((node).iterator) || child((node).statement); case SyntaxKind.ForInStatement: - return children((node).declarations) || - child((node).variable) || + return child((node).initializer) || child((node).expression) || child((node).statement); case SyntaxKind.ContinueStatement: @@ -263,79 +259,6 @@ module ts { } } - // TODO (drosen, mhegazy): Move to a more appropriate file. - export function createCompilerHost(options: CompilerOptions): CompilerHost { - var currentDirectory: string; - var existingDirectories: Map = {}; - - function getCanonicalFileName(fileName: string): string { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } - - // returned by CScript sys environment - var unsupportedFileEncodingErrorCode = -2147024809; - - function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { - try { - var text = sys.readFile(filename, options.charset); - } - catch (e) { - if (onError) { - onError(e.number === unsupportedFileEncodingErrorCode ? - createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText : - e.message); - } - text = ""; - } - - return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; - } - - function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { - function directoryExists(directoryPath: string): boolean { - if (hasProperty(existingDirectories, directoryPath)) { - return true; - } - if (sys.directoryExists(directoryPath)) { - existingDirectories[directoryPath] = true; - return true; - } - return false; - } - - function ensureDirectoriesExist(directoryPath: string) { - if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { - var parentDirectory = getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - sys.createDirectory(directoryPath); - } - } - - try { - ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); - sys.writeFile(fileName, data, writeByteOrderMark); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } - - return { - getSourceFile, - getDefaultLibFilename: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"), - writeFile, - getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()), - useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, - getCanonicalFileName, - getNewLine: () => sys.newLine - }; - } - - const enum ParsingContext { SourceElements, // Elements in source file ModuleElements, // Elements in module declaration @@ -435,15 +358,147 @@ module ts { function isUseStrictPrologueDirective(sourceFile: SourceFile, node: Node): boolean { Debug.assert(isPrologueDirective(node)); var nodeText = getSourceTextOfNodeFromSourceFile(sourceFile,(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'"; } + interface IncrementalElement extends TextRange { + parent?: Node; + intersectsChange: boolean + length?: number; + _children: Node[]; + } + + interface IncrementalNode extends Node, IncrementalElement { + } + + interface IncrementalNodeArray extends NodeArray, IncrementalElement { + length: number + } + + // Allows finding nodes in the source file at a certain position in an efficient manner. + // The implementation takes advantage of the calling pattern it knows the parser will + // make in order to optimize finding nodes as quickly as possible. + interface SyntaxCursor { + currentNode(position: number): IncrementalNode; + } + + const enum InvalidPosition { + Value = -1 + } + + function createSyntaxCursor(sourceFile: SourceFile): SyntaxCursor { + var currentArray: NodeArray = sourceFile.statements; + var currentArrayIndex = 0; + + Debug.assert(currentArrayIndex < currentArray.length); + var current = currentArray[currentArrayIndex]; + var lastQueriedPosition = InvalidPosition.Value; + + return { + currentNode(position: number) { + // Only compute the current node if the position is different than the last time + // we were asked. The parser commonly asks for the node at the same position + // twice. Once to know if can read an appropriate list element at a certain point, + // and then to actually read and consume the node. + if (position !== lastQueriedPosition) { + // Much of the time the parser will need the very next node in the array that + // we just returned a node from.So just simply check for that case and move + // forward in the array instead of searching for the node again. + if (current && current.end === position && currentArrayIndex < currentArray.length) { + currentArrayIndex++; + current = currentArray[currentArrayIndex]; + } + + // If we don't have a node, or the node we have isn't in the right position, + // then try to find a viable node at the position requested. + if (!current || current.pos !== position) { + findHighestListElementThatStartsAtPosition(position); + } + } + + // Cache this query so that we don't do any extra work if the parser calls back + // into us. Note: this is very common as the parser will make pairs of calls like + // 'isListElement -> parseListElement'. If we were unable to find a node when + // called with 'isListElement', we don't want to redo the work when parseListElement + // is called immediately after. + lastQueriedPosition = position; + + // Either we don'd have a node, or we have a node at the position being asked for. + Debug.assert(!current || current.pos === position); + return current; + } + }; + + // Finds the highest element in the tree we can find that starts at the provided position. + // The element must be a direct child of some node list in the tree. This way after we + // return it, we can easily return its next sibling in the list. + function findHighestListElementThatStartsAtPosition(position: number) { + // Clear out any cached state about the last node we found. + currentArray = undefined; + currentArrayIndex = InvalidPosition.Value; + current = undefined; + + // Recurse into the source file to find the highest node at this position. + forEachChild(sourceFile, visitNode, visitArray); + + function visitNode(node: Node) { + if (position >= node.pos && position < node.end) { + // Position was within this node. Keep searching deeper to find the node. + forEachChild(node, visitNode, visitArray); + + // don't procede any futher in the search. + return true; + } + + // position wasn't in this node, have to keep searching. + return false; + } + + function visitArray(array: NodeArray) { + if (position >= array.pos && position < array.end) { + // position was in this array. Search through this array to see if we find a + // viable element. + for (var i = 0, n = array.length; i < n; i++) { + var child = array[i]; + if (child) { + if (child.pos === position) { + // Found the right node. We're done. + currentArray = array; + currentArrayIndex = i; + current = child; + return true; + } + else { + if (child.pos < position && position < child.end) { + // Position in somewhere within this child. Search in it and + // stop searching in this array. + forEachChild(child, visitNode, visitArray); + return true; + } + } + } + } + } + + // position wasn't in this array, have to keep searching. + return false; + } + } + } + export function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile { var parsingContext: ParsingContext; - var identifiers: Map = {}; + var identifiers: Map; var identifierCount = 0; var nodeCount = 0; var lineStarts: number[]; + var syntacticDiagnostics: Diagnostic[]; + var scanner: Scanner; + var token: SyntaxKind; + var syntaxCursor: SyntaxCursor; // Flags that dictate what parsing context we're in. For example: // Whether or not we are in strict parsing mode. All that changes in strict parsing mode is @@ -491,7 +546,7 @@ module ts { // Note: it should not be necessary to save/restore these flags during speculative/lookahead // parsing. These context flags are naturally stored and restored through normal recursive // descent parsing and unwinding. - var contextFlags: ParserContextFlags = 0; + var contextFlags: ParserContextFlags; // Whether or not we've had a parse error since creating the last AST node. If we have // encountered an error, it will be stored on the next AST node we create. Parse errors @@ -520,47 +575,406 @@ module ts { // // Note: any errors at the end of the file that do not precede a regular node, should get // attached to the EOF token. - var parseErrorBeforeNextFinishedNode = false; + var parseErrorBeforeNextFinishedNode: boolean; - var sourceFile = createNode(SyntaxKind.SourceFile, 0); - if (fileExtensionIs(filename, ".d.ts")) { - sourceFile.flags = NodeFlags.DeclarationFile; - } - sourceFile.end = sourceText.length; - sourceFile.filename = normalizePath(filename); - sourceFile.text = sourceText; + var sourceFile: SourceFile; - sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; - sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; - sourceFile.getLineStarts = getLineStarts; - sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; + return parseSourceFile(sourceText, setParentNodes); - sourceFile.referenceDiagnostics = []; - sourceFile.parseDiagnostics = []; - sourceFile.semanticDiagnostics = []; + function parseSourceFile(text: string, setParentNodes: boolean): SourceFile { + // Set our initial state before parsing. + sourceText = text; + parsingContext = 0; + identifiers = {}; + lineStarts = undefined; + syntacticDiagnostics = undefined; + contextFlags = 0; + parseErrorBeforeNextFinishedNode = false; - processReferenceComments(); + sourceFile = createNode(SyntaxKind.SourceFile, 0); + sourceFile.referenceDiagnostics = []; + sourceFile.parseDiagnostics = []; + sourceFile.semanticDiagnostics = []; - // Create and prime the scanner before parsing the source elements. - var scanner = createScanner(languageVersion, /*skipTrivia*/ true, sourceText, scanError); - var token = nextToken(); + // Create and prime the scanner before parsing the source elements. + scanner = createScanner(languageVersion, /*skipTrivia*/ true, sourceText, scanError); + token = nextToken(); - sourceFile.statements = parseList(ParsingContext.SourceElements, /*checkForStrictMode*/ true, parseSourceElement); - Debug.assert(token === SyntaxKind.EndOfFileToken); - sourceFile.endOfFileToken = parseTokenNode(); + sourceFile.flags = fileExtensionIs(filename, ".d.ts") ? NodeFlags.DeclarationFile : 0; + sourceFile.end = sourceText.length; + sourceFile.filename = normalizePath(filename); + sourceFile.text = sourceText; - sourceFile.externalModuleIndicator = getExternalModuleIndicator(); + sourceFile.getLineAndCharacterFromPosition = getLineAndCharacterFromSourcePosition; + sourceFile.getPositionFromLineAndCharacter = getPositionFromSourceLineAndCharacter; + sourceFile.getLineStarts = getLineStarts; + sourceFile.getSyntacticDiagnostics = getSyntacticDiagnostics; + sourceFile.update = update; - sourceFile.nodeCount = nodeCount; - sourceFile.identifierCount = identifierCount; - sourceFile.languageVersion = languageVersion; - sourceFile.identifiers = identifiers; + processReferenceComments(sourceFile); - if (setParentNodes) { - fixupParentReferences(sourceFile); + sourceFile.statements = parseList(ParsingContext.SourceElements, /*checkForStrictMode*/ true, parseSourceElement); + Debug.assert(token === SyntaxKind.EndOfFileToken); + sourceFile.endOfFileToken = parseTokenNode(); + + setExternalModuleIndicator(sourceFile); + + sourceFile.nodeCount = nodeCount; + sourceFile.identifierCount = identifierCount; + sourceFile.languageVersion = languageVersion; + sourceFile.identifiers = identifiers; + + if (setParentNodes) { + fixupParentReferences(sourceFile); + } + + return sourceFile; } - return sourceFile; + function update(newText: string, textChangeRange: TextChangeRange) { + if (textChangeRangeIsUnchanged(textChangeRange)) { + // if the text didn't change, then we can just return our current source file as-is. + return sourceFile; + } + + if (sourceFile.statements.length === 0) { + // If we don't have any statements in the current source file, then there's no real + // way to incrementally parse. So just do a full parse instead. + return parseSourceFile(newText, /*setNodeParents*/ true); + } + + syntaxCursor = createSyntaxCursor(sourceFile); + + // Make the actual change larger so that we know to reparse anything whose lookahead + // might have intersected the change. + var changeRange = extendToAffectedRange(textChangeRange); + + // The is the amount the nodes after the edit range need to be adjusted. It can be + // positive (if the edit added characters), negative (if the edit deleted characters) + // or zero (if this was a pure overwrite with nothing added/removed). + var delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + + // If we added or removed characters during the edit, then we need to go and adjust all + // the nodes after the edit. Those nodes may move forward down (if we inserted chars) + // or they may move backward (if we deleted chars). + // + // Doing this helps us out in two ways. First, it means that any nodes/tokens we want + // to reuse are already at the appropriate position in the new text. That way when we + // reuse them, we don't have to figure out if they need to be adjusted. Second, it makes + // it very easy to determine if we can reuse a node. If the node's position is at where + // we are in the text, then we can reuse it. Otherwise we can't. If hte node's position + // is ahead of us, then we'll need to rescan tokens. If the node's position is behind + // us, then we'll need to skip it or crumble it as appropriate + // + // We will also adjust the positions of nodes that intersect the change range as well. + // By doing this, we ensure that all the positions in the old tree are consistent, not + // just the positions of nodes entirely before/after the change range. By being + // consistent, we can then easily map from positions to nodes in the old tree easily. + // + // Also, mark any syntax elements that intersect the changed span. We know, up front, + // that we cannot reuse these elements. + updateTokenPositionsAndMarkElements(sourceFile, + changeRange.span.start, textSpanEnd(changeRange.span), textSpanEnd(textChangeRangeNewSpan(changeRange)), delta); + + // Now that we've set up our internal incremental state just proceed and parse the + // source file in the normal fashion. When possible the parser will retrieve and + // reuse nodes from the old tree. + // + // Note: passing in 'true' for setNodeParents is very important. When incrementally + // parsing, we will be reusing nodes from the old tree, and placing it into new + // parents. If we don't set the parents now, we'll end up with an observably + // inconsistent tree. Setting the parents on the new tree should be very fast. We + // will immediately bail out of walking any subtrees when we can see that their parents + // are already correct. + var result = parseSourceFile(newText, /*setNodeParents*/ true); + + // Clear out the syntax cursor so it doesn't keep anything alive longer than it should. + syntaxCursor = undefined; + + return result; + } + + function updateTokenPositionsAndMarkElements(node: IncrementalNode, changeStart: number, changeRangeOldEnd: number, changeRangeNewEnd: number, delta: number): void { + visitNode(node); + + function visitNode(child: IncrementalNode) { + if (child.pos > changeRangeOldEnd) { + // Node is entirely past the change range. We need to move both its pos and + // end, forward or backward appropriately. + moveElementEntirelyPastChangeRange(child, delta); + return; + } + + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = child.end; + if (fullEnd >= changeStart) { + child.intersectsChange = true; + + // Adjust the pos or end (or both) of the intersecting element accordingly. + adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + forEachChild(child, visitNode, visitArray); + return; + } + + // Otherwise, the node is entirely before the change range. No need to do anything with it. + } + + function visitArray(array: IncrementalNodeArray) { + if (array.pos > changeRangeOldEnd) { + // Array is entirely after the change range. We need to move it, and move any of + // its children. + moveElementEntirelyPastChangeRange(array, delta); + } + else { + // Check if the element intersects the change range. If it does, then it is not + // reusable. Also, we'll need to recurse to see what constituent portions we may + // be able to use. + var fullEnd = array.end; + if (fullEnd >= changeStart) { + array.intersectsChange = true; + + // Adjust the pos or end (or both) of the intersecting array accordingly. + adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + // else { + // Otherwise, the array is entirely before the change range. No need to do anything with it. + // } + } + } + } + + function adjustIntersectingElement(element: IncrementalElement, changeStart: number, changeRangeOldEnd: number, changeRangeNewEnd: number, delta: number) { + Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range"); + Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range"); + + // We have an element that intersects the change range in some way. It may have its + // start, or its end (or both) in the changed range. We want to adjust any part + // that intersects such that the final tree is in a consistent state. i.e. all + // chlidren have spans within the span of their parent, and all siblings are ordered + // properly. + + // We may need to update both the 'pos' and the 'end' of the element. + + // If the 'pos' is before the start of the change, then we don't need to touch it. + // If it isn't, then the 'pos' must be inside the change. How we update it will + // depend if delta is positive or negative. If delta is positive then we have + // something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that started in the change range to still be + // starting at the same position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that started in the 'X' range will keep its position. + // However any element htat started after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that started in the 'Y' range will + // be adjusted to have their start at the end of the 'Z' range. + // + // The element will keep its position if possible. Or Move backward to the new-end + // if it's in the 'Y' range. + element.pos = Math.min(element.pos, changeRangeNewEnd); + + // If the 'end' is after the change range, then we always adjust it by the delta + // amount. However, if the end is in the change range, then how we adjust it + // will depend on if delta is positive or negative. If delta is positive then we + // have something like: + // + // -------------------AAA----------------- + // -------------------BBBCCCCCCC----------------- + // + // In this case, we consider any node that ended inside the change range to keep its + // end position. + // + // however, if the delta is negative, then we instead have something like this: + // + // -------------------XXXYYYYYYY----------------- + // -------------------ZZZ----------------- + // + // In this case, any element that ended in the 'X' range will keep its position. + // However any element htat ended after that will have their pos adjusted to be + // at the end of the new range. i.e. any node that ended in the 'Y' range will + // be adjusted to have their end at the end of the 'Z' range. + if (element.end >= changeRangeOldEnd) { + // Element ends after the change range. Always adjust the end pos. + element.end += delta; + } + else { + // Element ends in the change range. The element will keep its position if + // possible. Or Move backward to the new-end if it's in the 'Y' range. + element.end = Math.min(element.end, changeRangeNewEnd); + } + + Debug.assert(element.pos <= element.end); + if (element.parent) { + Debug.assert(element.pos >= element.parent.pos); + Debug.assert(element.end <= element.parent.end); + } + } + + function moveElementEntirelyPastChangeRange(element: IncrementalElement, delta: number) { + if (element.length) { + visitArray(element); + } + else { + visitNode(element); + } + + function visitNode(node: IncrementalNode) { + // Ditch any existing LS children we may have created. This way we can avoid + // moving them forward. + node._children = undefined; + node.pos += delta; + node.end += delta; + + forEachChild(node, visitNode, visitArray); + } + + function visitArray(array: IncrementalNodeArray) { + array.pos += delta; + array.end += delta; + + for (var i = 0, n = array.length; i < n; i++) { + visitNode(array[i]); + } + } + } + + function extendToAffectedRange(changeRange: TextChangeRange): TextChangeRange { + // Consider the following code: + // void foo() { /; } + // + // If the text changes with an insertion of / just before the semicolon then we end up with: + // void foo() { //; } + // + // If we were to just use the changeRange a is, then we would not rescan the { token + // (as it does not intersect the actual original change range). Because an edit may + // change the token touching it, we actually need to look back *at least* one token so + // that the prior token sees that change. + var maxLookahead = 1; + + var start = changeRange.span.start; + + // the first iteration aligns us with the change start. subsequent iteration move us to + // the left by maxLookahead tokens. We only need to do this as long as we're not at the + // start of the tree. + for (var i = 0; start > 0 && i <= maxLookahead; i++) { + var nearestNode = findNearestNodeStartingBeforeOrAtPosition(start); + var position = nearestNode.pos; + + start = Math.max(0, position - 1); + } + + var finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + var finalLength = changeRange.newLength + (changeRange.span.start - start); + + return createTextChangeRange(finalSpan, finalLength); + } + + function findNearestNodeStartingBeforeOrAtPosition(position: number): Node { + var bestResult: Node = sourceFile; + var lastNodeEntirelyBeforePosition: Node; + + forEachChild(sourceFile, visit); + + if (lastNodeEntirelyBeforePosition) { + var lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { + bestResult = lastChildOfLastEntireNodeBeforePosition; + } + } + + return bestResult; + + function getLastChild(node: Node): Node { + while (true) { + var lastChild = getLastChildWorker(node); + if (lastChild) { + node = lastChild; + } + else { + return node; + } + } + } + + function getLastChildWorker(node: Node): Node { + var last:Node = undefined; + forEachChild(node, child => { + if (nodeIsPresent(child)) { + last = child; + } + }); + return last; + } + + function visit(child: Node) { + if (nodeIsMissing(child)) { + // Missing nodes are effectively invisible to us. We never even consider them + // When trying to find the nearest node before us. + return; + } + + // If the child intersects this position, then this node is currently the nearest + // node that starts before the position. + if (child.pos <= position) { + if (child.pos >= bestResult.pos) { + // This node starts before the position, and is closer to the position than + // the previous best node we found. It is now the new best node. + bestResult = child; + } + + // Now, the node may overlap the position, or it may end entirely before the + // position. If it overlaps with the position, then either it, or one of its + // children must be the nearest node before the position. So we can just + // recurse into this child to see if we can find something better. + if (position < child.end) { + // The nearest node is either this child, or one of the children inside + // of it. We've already marked this child as the best so far. Recurse + // in case one of the children is better. + forEachChild(child, visit); + + // Once we look at the children of this node, then there's no need to + // continue any further. + return true; + } + else { + Debug.assert(child.end <= position); + // The child ends entirely before this position. Say you have the following + // (where $ is the position) + // + // ? $ : <...> <...> + // + // We would want to find the nearest preceding node in "complex expr 2". + // To support that, we keep track of this node, and once we're done searching + // for a best node, we recurse down this node to see if we can find a good + // result in it. + // + // This approach allows us to quickly skip over nodes that are entirely + // before the position, while still allowing us to find any nodes in the + // last one that might be what we want. + lastNodeEntirelyBeforePosition = child; + } + } + else { + Debug.assert(child.pos > position); + // We're now at a node that is entirely past the position we're searching for. + // This node (and all following nodes) could never contribute to the result, + // so just skip them by returning 'true' here. + return true; + } + } + } function setContextFlag(val: Boolean, flag: ParserContextFlags) { if (val) { @@ -682,9 +1096,9 @@ module ts { parseErrorBeforeNextFinishedNode = true; } - function scanError(message: DiagnosticMessage) { + function scanError(message: DiagnosticMessage, length?: number) { var pos = scanner.getTextPos(); - parseErrorAtPosition(pos, 0, message); + parseErrorAtPosition(pos, length || 0, message); } function getNodePos(): number { @@ -777,7 +1191,7 @@ module ts { return inStrictModeContext() ? token > SyntaxKind.LastFutureReservedWord : token > SyntaxKind.LastReservedWord; } - function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage, arg0?: any): boolean { + function parseExpected(kind: SyntaxKind, diagnosticMessage?: DiagnosticMessage): boolean { if (token === kind) { nextToken(); return true; @@ -785,7 +1199,7 @@ module ts { // Report specific message if provided with one. Otherwise, report generic fallback message. if (diagnosticMessage) { - parseErrorAtCurrentToken(diagnosticMessage, arg0); + parseErrorAtCurrentToken(diagnosticMessage); } else { parseErrorAtCurrentToken(Diagnostics._0_expected, tokenToString(kind)); @@ -820,7 +1234,7 @@ module ts { return token === SyntaxKind.CloseBraceToken || token === SyntaxKind.EndOfFileToken || scanner.hasPrecedingLineBreak(); } - function parseSemicolon(diagnosticMessage?: DiagnosticMessage): boolean { + function parseSemicolon(): boolean { if (canParseSemicolon()) { if (token === SyntaxKind.SemicolonToken) { // consume the semicolon if it was explicitly provided. @@ -830,7 +1244,7 @@ module ts { return true; } else { - return parseExpected(SyntaxKind.SemicolonToken, diagnosticMessage); + return parseExpected(SyntaxKind.SemicolonToken); } } @@ -978,14 +1392,19 @@ module ts { } // True if positioned at the start of a list element - function isListElement(kind: ParsingContext, inErrorRecovery: boolean): boolean { - switch (kind) { + function isListElement(parsingContext: ParsingContext, inErrorRecovery: boolean): boolean { + var node = currentNode(parsingContext); + if (node) { + return true; + } + + switch (parsingContext) { case ParsingContext.SourceElements: case ParsingContext.ModuleElements: return isSourceElement(inErrorRecovery); case ParsingContext.BlockStatements: case ParsingContext.SwitchClauseStatements: - return isStatement(inErrorRecovery); + return isStartOfStatement(inErrorRecovery); case ParsingContext.SwitchClauses: return token === SyntaxKind.CaseKeyword || token === SyntaxKind.DefaultKeyword; case ParsingContext.TypeMembers: @@ -1134,7 +1553,7 @@ module ts { while (!isListTerminator(kind)) { if (isListElement(kind, /* inErrorRecovery */ false)) { - var element = parseElement(); + var element = parseListElement(kind, parseElement); result.push(element); // test elements only if we are not already in strict mode @@ -1164,6 +1583,297 @@ module ts { return result; } + function parseListElement(kind: ParsingContext, parseElement: () => T): T { + var node = currentNode(kind); + if (node) { + return consumeNode(node); + } + + return parseElement(); + } + + function currentNode(parsingContext: ParsingContext): Node { + // If there is an outstanding parse error that we've encountered, but not attached to + // some node, then we cannot get a node from the old source tree. This is because we + // want to mark the next node we encounter as being unusable. + // + // Note: This may be too conservative. Perhaps we could reuse hte node and set the bit + // on it (or its leftmost child) as having the error. For now though, being conservative + // is nice and likely won't ever affect perf. + if (parseErrorBeforeNextFinishedNode) { + return undefined; + } + + if (!syntaxCursor) { + // if we don't have a cursor, we could never return a node from the old tree. + return undefined; + } + + var node = syntaxCursor.currentNode(scanner.getStartPos()); + + // Can't reuse a missing node. + if (nodeIsMissing(node)) { + return undefined; + } + + // Can't reuse a node that intersected the change range. + if (node.intersectsChange) { + return undefined; + } + + // Can't reuse a node that contains a parse error. This is necessary so that we + // produce the same set of errors again. + if (containsParseError(node)) { + return undefined; + } + + // We can only reuse a node if it was parsed under the same strict mode that we're + // currently in. i.e. if we originally parsed a node in non-strict mode, but then + // the user added 'using strict' at the top of the file, then we can't use that node + // again as the presense of strict mode may cause us to parse the tokens in the file + // differetly. + // + // Note: we *can* reuse tokens when the strict mode changes. That's because tokens + // are unaffected by strict mode. It's just the parser will decide what to do with it + // differently depending on what mode it is in. + // + // This also applies to all our other context flags as well. + var nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; + if (nodeContextFlags !== contextFlags) { + return undefined; + } + + // Ok, we have a node that looks like it could be reused. Now verify that it is valid + // in the currest list parsing context that we're currently at. + if (!canReuseNode(node, parsingContext)) { + return undefined; + } + + return node; + } + + function consumeNode(node: Node) { + // Move the scanner so it is after the node we just consumed. + scanner.setTextPos(node.end); + nextToken(); + return node; + } + + function canReuseNode(node: Node, parsingContext: ParsingContext): boolean { + switch (parsingContext) { + case ParsingContext.ModuleElements: + return isReusableModuleElement(node); + + case ParsingContext.ClassMembers: + return isReusableClassMember(node); + + case ParsingContext.SwitchClauses: + return isReusableSwitchClause(node); + + case ParsingContext.BlockStatements: + case ParsingContext.SwitchClauseStatements: + return isReusableStatement(node); + + case ParsingContext.EnumMembers: + return isReusableEnumMember(node); + + case ParsingContext.TypeMembers: + return isReusableTypeMember(node); + + case ParsingContext.VariableDeclarations: + return isReusableVariableDeclaration(node); + + case ParsingContext.Parameters: + return isReusableParameter(node); + + // Any other lists we do not care about reusing nodes in. But feel free to add if + // you can do so safely. Danger areas involve nodes that may involve speculative + // parsing. If speculative parsing is involved with the node, then the range the + // parser reached while looking ahead might be in the edited range (see the example + // in canReuseVariableDeclaratorNode for a good case of this). + case ParsingContext.HeritageClauses: + // This would probably be safe to reuse. There is no speculative parsing with + // heritage clauses. + + case ParsingContext.TypeReferences: + // This would probably be safe to reuse. There is no speculative parsing with + // type names in a heritage clause. There can be generic names in the type + // name list. But because it is a type context, we never use speculative + // parsing on the type argument list. + + case ParsingContext.TypeParameters: + // This would probably be safe to reuse. There is no speculative parsing with + // type parameters. Note that that's because type *parameters* only occur in + // unambiguous *type* contexts. While type *arguments* occur in very ambiguous + // *expression* contexts. + + case ParsingContext.TupleElementTypes: + // This would probably be safe to reuse. There is no speculative parsing with + // tuple types. + + // Technically, type argument list types are probably safe to reuse. While + // speculative parsing is involved with them (since type argument lists are only + // produced from speculative parsing a < as a type argument list), we only have + // the types because speculative parsing succeeded. Thus, the lookahead never + // went past the end of the list and rewound. + case ParsingContext.TypeArguments: + + // Note: these are almost certainly not safe to ever reuse. Expressions commonly + // need a large amount of lookahead, and we should not reuse them as they may + // have actually intersected the edit. + case ParsingContext.ArgumentExpressions: + + // This is not safe to reuse for the same reason as the 'AssignmentExpression' + // cases. i.e. a property assignment may end with an expression, and thus might + // have lookahead far beyond it's old node. + case ParsingContext.ObjectLiteralMembers: + } + + return false; + } + + function isReusableModuleElement(node: Node) { + if (node) { + switch (node.kind) { + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportAssignment: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.EnumDeclaration: + + // Keep in sync with isStatement: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.VariableStatement: + case SyntaxKind.Block: + case SyntaxKind.IfStatement: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.SwitchStatement: + case SyntaxKind.BreakStatement: + case SyntaxKind.ContinueStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.WithStatement: + case SyntaxKind.EmptyStatement: + case SyntaxKind.TryStatement: + case SyntaxKind.LabeledStatement: + case SyntaxKind.DoStatement: + case SyntaxKind.DebuggerStatement: + return true; + } + } + + return false; + } + + function isReusableClassMember(node: Node) { + if (node) { + switch (node.kind) { + case SyntaxKind.Constructor: + case SyntaxKind.IndexSignature: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.PropertyDeclaration: + return true; + } + } + + return false; + } + + function isReusableSwitchClause(node: Node) { + if (node) { + switch (node.kind) { + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + return true; + } + } + + return false; + } + + function isReusableStatement(node: Node) { + if (node) { + switch (node.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.VariableStatement: + case SyntaxKind.Block: + case SyntaxKind.IfStatement: + case SyntaxKind.ExpressionStatement: + case SyntaxKind.ThrowStatement: + case SyntaxKind.ReturnStatement: + case SyntaxKind.SwitchStatement: + case SyntaxKind.BreakStatement: + case SyntaxKind.ContinueStatement: + case SyntaxKind.ForInStatement: + case SyntaxKind.ForStatement: + case SyntaxKind.WhileStatement: + case SyntaxKind.WithStatement: + case SyntaxKind.EmptyStatement: + case SyntaxKind.TryStatement: + case SyntaxKind.LabeledStatement: + case SyntaxKind.DoStatement: + case SyntaxKind.DebuggerStatement: + return true; + } + } + + return false; + } + + function isReusableEnumMember(node: Node) { + return node.kind === SyntaxKind.EnumMember; + } + + function isReusableTypeMember(node: Node) { + if (node) { + switch (node.kind) { + case SyntaxKind.ConstructSignature: + case SyntaxKind.MethodSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.PropertySignature: + case SyntaxKind.CallSignature: + return true; + } + } + + return false; + } + + function isReusableVariableDeclaration(node: Node) { + if (node.kind !== SyntaxKind.VariableDeclaration) { + return false; + } + + // Very subtle incremental parsing bug. Consider the following code: + // + // var v = new List < A, B + // + // This is actually legal code. It's a list of variable declarators "v = new List() + // + // then we have a problem. "v = new Listnode; + return variableDeclarator.initializer === undefined; + } + + function isReusableParameter(node: Node) { + // TODO: this most likely needs the same initializer check that + // isReusableVariableDeclaration has. + return node.kind === SyntaxKind.Parameter; + } + // Returns true if we should abort parsing. function abortParsingListOrMoveToNextToken(kind: ParsingContext) { parseErrorAtCurrentToken(parsingContextErrors(kind)); @@ -1185,7 +1895,7 @@ module ts { var commaStart = -1; // Meaning the previous token was not a comma while (true) { if (isListElement(kind, /* inErrorRecovery */ false)) { - result.push(parseElement()); + result.push(parseListElement(kind, parseElement)); commaStart = scanner.getTokenPos(); if (parseOptional(SyntaxKind.CommaToken)) { continue; @@ -1626,7 +2336,8 @@ module ts { return token === SyntaxKind.ColonToken || token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBracketToken; } - function parseIndexSignatureDeclaration(fullStart: number, modifiers: ModifiersArray): IndexSignatureDeclaration { + function parseIndexSignatureDeclaration(modifiers: ModifiersArray): IndexSignatureDeclaration { + var fullStart = modifiers ? modifiers.pos : scanner.getStartPos(); var node = createNode(SyntaxKind.IndexSignature, fullStart); setModifiers(node, modifiers); node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); @@ -1668,10 +2379,25 @@ module ts { case SyntaxKind.OpenBracketToken: // Both for indexers and computed properties return true; default: + if (isModifier(token)) { + var result = lookAhead(isStartOfIndexSignatureDeclaration); + if (result) { + return result; + } + } + return isLiteralPropertyName() && lookAhead(isTypeMemberWithLiteralPropertyName); } } + function isStartOfIndexSignatureDeclaration() { + while (isModifier(token)) { + nextToken(); + } + + return isIndexSignature(); + } + function isTypeMemberWithLiteralPropertyName() { nextToken(); return token === SyntaxKind.OpenParenToken || @@ -1688,7 +2414,9 @@ module ts { return parseSignatureMember(SyntaxKind.CallSignature); case SyntaxKind.OpenBracketToken: // Indexer or computed property - return isIndexSignature() ? parseIndexSignatureDeclaration(scanner.getStartPos(), /*modifiers:*/ undefined) : parsePropertyOrMethodSignature(); + return isIndexSignature() + ? parseIndexSignatureDeclaration(/*modifiers:*/ undefined) + : parsePropertyOrMethodSignature(); case SyntaxKind.NewKeyword: if (lookAhead(isStartOfConstructSignature)) { return parseSignatureMember(SyntaxKind.ConstructSignature); @@ -1698,12 +2426,32 @@ module ts { case SyntaxKind.NumericLiteral: return parsePropertyOrMethodSignature(); default: + // Index declaration as allowed as a type member. But as per the grammar, + // they also allow modifiers. So we have to check for an index declaration + // that might be following modifiers. This ensures that things work properly + // when incrementally parsing as the parser will produce the Index declaration + // if it has the same text regardless of whether it is inside a class or an + // object type. + if (isModifier(token)) { + var result = tryParse(parseIndexSignatureWithModifiers); + if (result) { + return result; + } + } + if (isIdentifierOrKeyword()) { return parsePropertyOrMethodSignature(); } } } + function parseIndexSignatureWithModifiers() { + var modifiers = parseModifiers(); + return isIndexSignature() + ? parseIndexSignatureDeclaration(modifiers) + : undefined; + } + function isStartOfConstructSignature() { nextToken(); return token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken; @@ -2286,7 +3034,7 @@ module ts { return parseFunctionBlock(/*allowYield:*/ false, /* ignoreMissingOpenBrace */ false); } - if (isStatement(/* inErrorRecovery */ true) && !isStartOfExpressionStatement() && token !== SyntaxKind.FunctionKeyword) { + if (isStartOfStatement(/*inErrorRecovery:*/ true) && !isStartOfExpressionStatement() && token !== SyntaxKind.FunctionKeyword) { // Check if we got a plain statement (i.e. no expression-statements, no functions expressions/declarations) // // Here we try to recover from a potential error situation in the case where the @@ -2732,16 +3480,16 @@ module ts { function parsePrimaryExpression(): PrimaryExpression { switch (token) { + case SyntaxKind.NumericLiteral: + case SyntaxKind.StringLiteral: + case SyntaxKind.NoSubstitutionTemplateLiteral: + return parseLiteralNode(); case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return parseTokenNode(); - case SyntaxKind.NumericLiteral: - case SyntaxKind.StringLiteral: - case SyntaxKind.NoSubstitutionTemplateLiteral: - return parseLiteralNode(); case SyntaxKind.OpenParenToken: return parseParenthesizedExpression(); case SyntaxKind.OpenBracketToken: @@ -2803,25 +3551,36 @@ module ts { return finishNode(node); } + function tryParseAccessorDeclaration(fullStart: number, modifiers: ModifiersArray): AccessorDeclaration { + if (parseContextualModifier(SyntaxKind.GetKeyword)) { + return parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, modifiers); + } + else if (parseContextualModifier(SyntaxKind.SetKeyword)) { + return parseAccessorDeclaration(SyntaxKind.SetAccessor, fullStart, modifiers); + } + + return undefined; + } + function parseObjectLiteralElement(): ObjectLiteralElement { var fullStart = scanner.getStartPos(); - var initialToken = token; + var modifiers = parseModifiers(); - if (parseContextualModifier(SyntaxKind.GetKeyword) || parseContextualModifier(SyntaxKind.SetKeyword)) { - var kind = initialToken === SyntaxKind.GetKeyword ? SyntaxKind.GetAccessor : SyntaxKind.SetAccessor; - return parseAccessorDeclaration(kind, fullStart, /*modifiers*/undefined); + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } var asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); var tokenIsIdentifier = isIdentifier(); var nameToken = token; var propertyName = parsePropertyName(); - if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { - return parseMethodDeclaration(fullStart, /*modifiers:*/ undefined, asteriskToken, propertyName, /*questionToken:*/ undefined, /*requireBlock:*/ true); - } // Disallowing of optional property assignments happens in the grammar checker. var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, propertyName, questionToken); + } // Parse to check if it is short-hand property assignment or normal property assignment if ((token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBraceToken) && tokenIsIdentifier) { @@ -2883,9 +3642,9 @@ module ts { } // STATEMENTS - function parseBlock(kind: SyntaxKind, ignoreMissingOpenBrace: boolean, checkForStrictMode: boolean): Block { - var node = createNode(kind); - if (parseExpected(SyntaxKind.OpenBraceToken) || ignoreMissingOpenBrace) { + function parseBlock(ignoreMissingOpenBrace: boolean, checkForStrictMode: boolean, diagnosticMessage?: DiagnosticMessage): Block { + var node = createNode(SyntaxKind.Block); + if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(ParsingContext.BlockStatements, checkForStrictMode, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); } @@ -2895,11 +3654,11 @@ module ts { return finishNode(node); } - function parseFunctionBlock(allowYield: boolean, ignoreMissingOpenBrace: boolean): Block { + function parseFunctionBlock(allowYield: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { var savedYieldContext = inYieldContext(); setYieldContext(allowYield); - var block = parseBlock(SyntaxKind.Block, ignoreMissingOpenBrace, /*checkForStrictMode*/ true); + var block = parseBlock(ignoreMissingOpenBrace, /*checkForStrictMode*/ true, diagnosticMessage); setYieldContext(savedYieldContext); @@ -2954,42 +3713,27 @@ module ts { var pos = getNodePos(); parseExpected(SyntaxKind.ForKeyword); parseExpected(SyntaxKind.OpenParenToken); + + var initializer: VariableDeclarationList | Expression = undefined; if (token !== SyntaxKind.SemicolonToken) { - if (parseOptional(SyntaxKind.VarKeyword)) { - var declarations = disallowInAnd(parseVariableDeclarationList); - } - else if (parseOptional(SyntaxKind.LetKeyword)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), NodeFlags.Let); - } - else if (parseOptional(SyntaxKind.ConstKeyword)) { - var declarations = setFlag(disallowInAnd(parseVariableDeclarationList), NodeFlags.Const); + if (token === SyntaxKind.VarKeyword || token === SyntaxKind.LetKeyword || token === SyntaxKind.ConstKeyword) { + initializer = parseVariableDeclarationList(/*disallowIn:*/ true); } else { - var varOrInit = disallowInAnd(parseExpression); + initializer = disallowInAnd(parseExpression); } } var forOrForInStatement: IterationStatement; if (parseOptional(SyntaxKind.InKeyword)) { var forInStatement = createNode(SyntaxKind.ForInStatement, pos); - if (declarations) { - forInStatement.declarations = declarations; - } - else { - forInStatement.variable = varOrInit; - } + forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); forOrForInStatement = forInStatement; } else { var forStatement = createNode(SyntaxKind.ForStatement, pos); - if (declarations) { - forStatement.declarations = declarations; - } - if (varOrInit) { - forStatement.initializer = varOrInit; - } - + forStatement.initializer = initializer; parseExpected(SyntaxKind.SemicolonToken); if (token !== SyntaxKind.SemicolonToken && token !== SyntaxKind.CloseParenToken) { forStatement.condition = allowInAnd(parseExpression); @@ -3093,25 +3837,19 @@ module ts { // TODO: Review for error recovery function parseTryStatement(): TryStatement { var node = createNode(SyntaxKind.TryStatement); - node.tryBlock = parseTokenAndBlock(SyntaxKind.TryKeyword); + + parseExpected(SyntaxKind.TryKeyword); + node.tryBlock = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode*/ false); node.catchClause = token === SyntaxKind.CatchKeyword ? parseCatchClause() : undefined; // If we don't have a catch clause, then we must have a finally clause. Try to parse // one out no matter what. - node.finallyBlock = !node.catchClause || token === SyntaxKind.FinallyKeyword - ? parseTokenAndBlock(SyntaxKind.FinallyKeyword) - : undefined; - return finishNode(node); - } + if (!node.catchClause || token === SyntaxKind.FinallyKeyword) { + parseExpected(SyntaxKind.FinallyKeyword); + node.finallyBlock = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode*/ false); + } - function parseTokenAndBlock(token: SyntaxKind): Block { - var pos = getNodePos(); - parseExpected(token); - var result = parseBlock( - token === SyntaxKind.TryKeyword ? SyntaxKind.TryBlock : SyntaxKind.FinallyBlock, - /* ignoreMissingOpenBrace */ false, /*checkForStrictMode*/ false); - result.pos = pos; - return result; + return finishNode(node); } function parseCatchClause(): CatchClause { @@ -3121,7 +3859,7 @@ module ts { result.name = parseIdentifier(); result.type = parseTypeAnnotation(); parseExpected(SyntaxKind.CloseParenToken); - result.block = parseBlock(SyntaxKind.Block, /* ignoreMissingOpenBrace */ false, /*checkForStrictMode*/ false); + result.block = parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode:*/ false); return finishNode(result); } @@ -3153,7 +3891,19 @@ module ts { } } - function isStatement(inErrorRecovery: boolean): boolean { + function isStartOfStatement(inErrorRecovery: boolean): boolean { + // Functions and variable statements are allowed as a statement. But as per the grammar, + // they also allow modifiers. So we have to check for those statements that might be + // following modifiers.This ensures that things work properly when incrementally parsing + // as the parser will produce the same FunctionDeclaraiton or VariableStatement if it has + // the same text regardless of whether it is inside a block or not. + if (isModifier(token)) { + var result = lookAhead(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return true; + } + } + switch (token) { case SyntaxKind.SemicolonToken: // If we're in error recovery, then we don't want to treat ';' as an empty statement. @@ -3228,7 +3978,7 @@ module ts { function parseStatement(): Statement { switch (token) { case SyntaxKind.OpenBraceToken: - return parseBlock(SyntaxKind.Block, /* ignoreMissingOpenBrace */ false, /*checkForStrictMode*/ false); + return parseBlock(/*ignoreMissingOpenBrace:*/ false, /*checkForStrictMode:*/ false); case SyntaxKind.VarKeyword: case SyntaxKind.ConstKeyword: // const here should always be parsed as const declaration because of check in 'isStatement' @@ -3271,19 +4021,58 @@ module ts { } // Else parse it like identifier - fall through default: + // Functions and variable statements are allowed as a statement. But as per + // the grammar, they also allow modifiers. So we have to check for those + // statements that might be following modifiers. This ensures that things + // work properly when incrementally parsing as the parser will produce the + // same FunctionDeclaraiton or VariableStatement if it has the same text + // regardless of whether it is inside a block or not. + if (isModifier(token)) { + var result = tryParse(parseVariableStatementOrFunctionDeclarationWithModifiers); + if (result) { + return result; + } + } + return parseExpressionOrLabeledStatement(); } } - function parseFunctionBlockOrSemicolon(isGenerator: boolean): Block { - if (token === SyntaxKind.OpenBraceToken) { - return parseFunctionBlock(isGenerator, /*ignoreMissingOpenBrace:*/ false); + function parseVariableStatementOrFunctionDeclarationWithModifiers(): FunctionDeclaration | VariableStatement { + var start = scanner.getStartPos(); + var modifiers = parseModifiers(); + switch (token) { + case SyntaxKind.ConstKeyword: + var nextTokenIsEnum = lookAhead(nextTokenIsEnumKeyword) + if (nextTokenIsEnum) { + return undefined; + } + return parseVariableStatement(start, modifiers); + + case SyntaxKind.LetKeyword: + if (!isLetDeclaration()) { + return undefined; + } + return parseVariableStatement(start, modifiers); + + case SyntaxKind.VarKeyword: + return parseVariableStatement(start, modifiers); + case SyntaxKind.FunctionKeyword: + return parseFunctionDeclaration(start, modifiers); } - parseSemicolon(Diagnostics.or_expected); return undefined; } + function parseFunctionBlockOrSemicolon(isGenerator: boolean, diagnosticMessage?: DiagnosticMessage): Block { + if (token !== SyntaxKind.OpenBraceToken && canParseSemicolon()) { + parseSemicolon(); + return; + } + + return parseFunctionBlock(isGenerator, /*ignoreMissingOpenBrace:*/ false, diagnosticMessage); + } + // DECLARATIONS function parseArrayBindingElement(): BindingElement { @@ -3351,39 +4140,37 @@ module ts { return finishNode(node); } - function setFlag(nodes: NodeArray, flag: NodeFlags): NodeArray { - for (var i = 0; i < nodes.length; i++) { - var node = nodes[i]; - node.flags |= flag; - if (node.name && isBindingPattern(node.name)) { - setFlag((node.name).elements, flag); - } - } - return nodes; - } + function parseVariableDeclarationList(disallowIn: boolean): VariableDeclarationList { + var node = createNode(SyntaxKind.VariableDeclarationList); - function parseVariableDeclarationList(): NodeArray { - return parseDelimitedList(ParsingContext.VariableDeclarations, parseVariableDeclaration); + switch (token) { + case SyntaxKind.VarKeyword: + break; + case SyntaxKind.LetKeyword: + node.flags |= NodeFlags.Let; + break; + case SyntaxKind.ConstKeyword: + node.flags |= NodeFlags.Const; + break; + default: + Debug.fail(); + } + + nextToken(); + var savedDisallowIn = inDisallowInContext(); + setDisallowInContext(disallowIn); + + node.declarations = parseDelimitedList(ParsingContext.VariableDeclarations, parseVariableDeclaration); + + setDisallowInContext(savedDisallowIn); + + return finishNode(node); } function parseVariableStatement(fullStart: number, modifiers: ModifiersArray): VariableStatement { var node = createNode(SyntaxKind.VariableStatement, fullStart); setModifiers(node, modifiers); - - if (token === SyntaxKind.LetKeyword) { - node.flags |= NodeFlags.Let; - } - else if (token === SyntaxKind.ConstKeyword) { - node.flags |= NodeFlags.Const; - } - else { - Debug.assert(token === SyntaxKind.VarKeyword); - } - - nextToken(); - node.declarations = allowInAnd(parseVariableDeclarationList); - setFlag(node.declarations, node.flags); - + node.declarationList = parseVariableDeclarationList(/*disallowIn:*/ false); parseSemicolon(); return finishNode(node); } @@ -3395,7 +4182,7 @@ module ts { node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = parseIdentifier(); fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ !!node.asteriskToken, /*requireCompleteParameterList:*/ false, node); - node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken); + node.body = parseFunctionBlockOrSemicolon(!!node.asteriskToken, Diagnostics.or_expected); return finishNode(node); } @@ -3404,18 +4191,18 @@ module ts { setModifiers(node, modifiers); parseExpected(SyntaxKind.ConstructorKeyword); fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ false, /*requireCompleteParameterList:*/ false, node); - node.body = parseFunctionBlockOrSemicolon(/*isGenerator:*/ false); + node.body = parseFunctionBlockOrSemicolon(/*isGenerator:*/ false, Diagnostics.or_expected); return finishNode(node); } - function parseMethodDeclaration(fullStart: number, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, requireBlock: boolean): MethodDeclaration { + function parseMethodDeclaration(fullStart: number, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { var method = createNode(SyntaxKind.MethodDeclaration, fullStart); setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; fillSignature(SyntaxKind.ColonToken, /*yieldAndGeneratorParameterContext:*/ !!asteriskToken, /*requireCompleteParameterList:*/ false, method); - method.body = requireBlock ? parseFunctionBlock(!!asteriskToken, /*ignoreMissingOpenBrace:*/ false) : parseFunctionBlockOrSemicolon(!!asteriskToken); + method.body = parseFunctionBlockOrSemicolon(!!asteriskToken, diagnosticMessage); return finishNode(method); } @@ -3427,7 +4214,7 @@ module ts { // report an error in the grammar checker. var questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { - return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, /*requireBlock:*/ false); + return parseMethodDeclaration(fullStart, modifiers, asteriskToken, name, questionToken, Diagnostics.or_expected); } else { var property = createNode(SyntaxKind.PropertyDeclaration, fullStart); @@ -3536,22 +4323,28 @@ module ts { function parseClassElement(): ClassElement { var fullStart = getNodePos(); var modifiers = parseModifiers(); - if (parseContextualModifier(SyntaxKind.GetKeyword)) { - return parseAccessorDeclaration(SyntaxKind.GetAccessor, fullStart, modifiers); - } - if (parseContextualModifier(SyntaxKind.SetKeyword)) { - return parseAccessorDeclaration(SyntaxKind.SetAccessor, fullStart, modifiers); + + var accessor = tryParseAccessorDeclaration(fullStart, modifiers); + if (accessor) { + return accessor; } + if (token === SyntaxKind.ConstructorKeyword) { return parseConstructorDeclaration(fullStart, modifiers); } + if (isIndexSignature()) { - return parseIndexSignatureDeclaration(fullStart, modifiers); + return parseIndexSignatureDeclaration(modifiers); } + // It is very important that we check this *after* checking indexers because // the [ token can start an index signature or a computed property name - if (isIdentifierOrKeyword() || token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral || - token === SyntaxKind.AsteriskToken || token === SyntaxKind.OpenBracketToken) { + if (isIdentifierOrKeyword() || + token === SyntaxKind.StringLiteral || + token === SyntaxKind.NumericLiteral || + token === SyntaxKind.AsteriskToken || + token === SyntaxKind.OpenBracketToken) { + return parsePropertyOrMethodDeclaration(fullStart, modifiers); } @@ -3857,7 +4650,7 @@ module ts { } function isSourceElement(inErrorRecovery: boolean): boolean { - return isDeclarationStart() || isStatement(inErrorRecovery); + return isDeclarationStart() || isStartOfStatement(inErrorRecovery); } function parseSourceElement() { @@ -3874,7 +4667,7 @@ module ts { : parseStatement(); } - function processReferenceComments(): void { + function processReferenceComments(sourceFile: SourceFile): void { var triviaScanner = createScanner(languageVersion, /*skipTrivia*/false, sourceText); var referencedFiles: FileReference[] = []; var amdDependencies: string[] = []; @@ -3930,16 +4723,15 @@ module ts { sourceFile.amdModuleName = amdModuleName; } - function getExternalModuleIndicator() { - return forEach(sourceFile.statements, node => + function setExternalModuleIndicator(sourceFile: SourceFile) { + sourceFile.externalModuleIndicator = forEach(sourceFile.statements, node => node.flags & NodeFlags.Export || node.kind === SyntaxKind.ImportDeclaration && (node).moduleReference.kind === SyntaxKind.ExternalModuleReference || node.kind === SyntaxKind.ExportAssignment - ? node - : undefined); + ? node + : undefined); } - var syntacticDiagnostics: Diagnostic[]; function getSyntacticDiagnostics() { if (syntacticDiagnostics === undefined) { // Don't bother doing any grammar checks if there are already parser errors. @@ -3985,280 +4777,4 @@ module ts { export function isAssignmentOperator(token: SyntaxKind): boolean { return token >= SyntaxKind.FirstAssignment && token <= SyntaxKind.LastAssignment; } - - export function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program { - var program: Program; - var files: SourceFile[] = []; - var filesByName: Map = {}; - var errors: Diagnostic[] = []; - var seenNoDefaultLib = options.noLib; - var commonSourceDirectory: string; - - forEach(rootNames, name => processRootFile(name, false)); - if (!seenNoDefaultLib) { - processRootFile(host.getDefaultLibFilename(options), true); - } - verifyCompilerOptions(); - errors.sort(compareDiagnostics); - program = { - getSourceFile: getSourceFile, - getSourceFiles: () => files, - getCompilerOptions: () => options, - getCompilerHost: () => host, - getDiagnostics: getDiagnostics, - getGlobalDiagnostics: getGlobalDiagnostics, - getTypeChecker: fullTypeCheckMode => createTypeChecker(program, fullTypeCheckMode), - getCommonSourceDirectory: () => commonSourceDirectory, - }; - return program; - - function getSourceFile(filename: string) { - filename = host.getCanonicalFileName(filename); - return hasProperty(filesByName, filename) ? filesByName[filename] : undefined; - } - - function getDiagnostics(sourceFile?: SourceFile): Diagnostic[] { - return sourceFile ? filter(errors, e => e.file === sourceFile) : errors; - } - - function getGlobalDiagnostics(): Diagnostic[] { - return filter(errors, e => !e.file); - } - - function hasExtension(filename: string): boolean { - return getBaseFilename(filename).indexOf(".") >= 0; - } - - function processRootFile(filename: string, isDefaultLib: boolean) { - processSourceFile(normalizePath(filename), isDefaultLib); - } - - function processSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { - if (refEnd !== undefined && refPos !== undefined) { - var start = refPos; - var length = refEnd - refPos; - } - var diagnostic: DiagnosticMessage; - if (hasExtension(filename)) { - if (!options.allowNonTsExtensions && !fileExtensionIs(filename, ".ts")) { - diagnostic = Diagnostics.File_0_must_have_extension_ts_or_d_ts; - } - else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { - diagnostic = Diagnostics.File_0_not_found; - } - else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { - diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; - } - } - else { - if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { - diagnostic = Diagnostics.File_0_not_found; - filename += ".ts"; - } - } - - if (diagnostic) { - if (refFile) { - errors.push(createFileDiagnostic(refFile, start, length, diagnostic, filename)); - } - else { - errors.push(createCompilerDiagnostic(diagnostic, filename)); - } - } - } - - // Get source file from normalized filename - function findSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile { - var canonicalName = host.getCanonicalFileName(filename); - if (hasProperty(filesByName, canonicalName)) { - // We've already looked for this file, use cached result - return getSourceFileFromCache(filename, canonicalName, /*useAbsolutePath*/ false); - } - else { - var normalizedAbsolutePath = getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); - var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); - if (hasProperty(filesByName, canonicalAbsolutePath)) { - return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, /*useAbsolutePath*/ true); - } - - // We haven't looked for this file, do so now and cache result - var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, hostErrorMessage => { - if (refFile) { - errors.push(createFileDiagnostic(refFile, refStart, refLength, - Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - else { - errors.push(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); - } - }); - if (file) { - seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; - - // Set the source file for normalized absolute path - filesByName[canonicalAbsolutePath] = file; - - if (!options.noResolve) { - var basePath = getDirectoryPath(filename); - processReferencedFiles(file, basePath); - processImportedModules(file, basePath); - } - if (isDefaultLib) { - files.unshift(file); - } - else { - files.push(file); - } - forEach(file.getSyntacticDiagnostics(), e => { - errors.push(e); - }); - } - } - return file; - - function getSourceFileFromCache(filename: string, canonicalName: string, useAbsolutePath: boolean): SourceFile { - var file = filesByName[canonicalName]; - if (file && host.useCaseSensitiveFileNames()) { - var sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; - if (canonicalName !== sourceFileName) { - errors.push(createFileDiagnostic(refFile, refStart, refLength, - Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); - } - } - return file; - } - } - - function processReferencedFiles(file: SourceFile, basePath: string) { - forEach(file.referencedFiles, ref => { - var referencedFilename = isRootedDiskPath(ref.filename) ? ref.filename : combinePaths(basePath, ref.filename); - processSourceFile(normalizePath(referencedFilename), /* isDefaultLib */ false, file, ref.pos, ref.end); - }); - } - - function processImportedModules(file: SourceFile, basePath: string) { - forEach(file.statements, node => { - if (isExternalModuleImportDeclaration(node) && - getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) { - - var nameLiteral = getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - var searchPath = basePath; - while (true) { - var searchName = normalizePath(combinePaths(searchPath, moduleName)); - if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { - break; - } - - var parentPath = getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - } - } - else if (node.kind === SyntaxKind.ModuleDeclaration && (node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An AmbientExternalModuleDeclaration declares an external module. - // This type of declaration is permitted only in the global module. - // The StringLiteral must specify a top - level external module name. - // Relative external module names are not permitted - forEachChild((node).body, node => { - if (isExternalModuleImportDeclaration(node) && - getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) { - - var nameLiteral = getExternalModuleImportDeclarationExpression(node); - var moduleName = nameLiteral.text; - if (moduleName) { - // TypeScript 1.0 spec (April 2014): 12.1.6 - // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules - // only through top - level external module names. Relative external module names are not permitted. - var searchName = normalizePath(combinePaths(basePath, moduleName)); - var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); - if (!tsFile) { - findModuleSourceFile(searchName + ".d.ts", nameLiteral); - } - } - } - }); - } - }); - - function findModuleSourceFile(filename: string, nameLiteral: LiteralExpression) { - return findSourceFile(filename, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); - } - } - - function verifyCompilerOptions() { - if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { - // Error to specify --mapRoot or --sourceRoot without mapSourceFiles - if (options.mapRoot) { - errors.push(createCompilerDiagnostic(Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - if (options.sourceRoot) { - errors.push(createCompilerDiagnostic(Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); - } - return; - } - - var firstExternalModule = forEach(files, f => isExternalModule(f) ? f : undefined); - if (firstExternalModule && options.module === ModuleKind.None) { - // We cannot use createDiagnosticFromNode because nodes do not have parents yet - var externalModuleErrorSpan = getErrorSpanForNode(firstExternalModule.externalModuleIndicator); - var errorStart = skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); - var errorLength = externalModuleErrorSpan.end - errorStart; - errors.push(createFileDiagnostic(firstExternalModule, errorStart, errorLength, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); - } - - // there has to be common source directory if user specified --outdir || --sourcRoot - // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted - if (options.outDir || // there is --outDir specified - options.sourceRoot || // there is --sourceRoot specified - (options.mapRoot && // there is --mapRoot Specified and there would be multiple js files generated - (!options.out || firstExternalModule !== undefined))) { - - var commonPathComponents: string[]; - forEach(files, sourceFile => { - // Each file contributes into common source file path - if (!(sourceFile.flags & NodeFlags.DeclarationFile) - && !fileExtensionIs(sourceFile.filename, ".js")) { - var sourcePathComponents = getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); - sourcePathComponents.pop(); // FileName is not part of directory - if (commonPathComponents) { - for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { - if (commonPathComponents[i] !== sourcePathComponents[i]) { - if (i === 0) { - errors.push(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); - return; - } - - // New common path found that is 0 -> i-1 - commonPathComponents.length = i; - break; - } - } - - // If the fileComponent path completely matched and less than already found update the length - if (sourcePathComponents.length < commonPathComponents.length) { - commonPathComponents.length = sourcePathComponents.length; - } - } - else { - // first file - commonPathComponents = sourcePathComponents; - } - } - }); - - commonSourceDirectory = getNormalizedPathFromPathComponents(commonPathComponents); - if (commonSourceDirectory) { - // Make sure directory path ends with directory separator so this string can directly - // used to replace with "" to get the relative path of the source file and the relative path doesn't - // start with / making it rooted path - commonSourceDirectory += directorySeparator; - } - } - } - } } diff --git a/src/compiler/program.ts b/src/compiler/program.ts new file mode 100644 index 0000000000..b506a86786 --- /dev/null +++ b/src/compiler/program.ts @@ -0,0 +1,408 @@ +/// +/// + +module ts { + export function createCompilerHost(options: CompilerOptions): CompilerHost { + var currentDirectory: string; + var existingDirectories: Map = {}; + + function getCanonicalFileName(fileName: string): string { + // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. + // otherwise use toLowerCase as a canonical form. + return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + } + + // returned by CScript sys environment + var unsupportedFileEncodingErrorCode = -2147024809; + + function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { + try { + var text = sys.readFile(filename, options.charset); + } + catch (e) { + if (onError) { + onError(e.number === unsupportedFileEncodingErrorCode ? + createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText : + e.message); + } + text = ""; + } + + return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined; + } + + function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { + function directoryExists(directoryPath: string): boolean { + if (hasProperty(existingDirectories, directoryPath)) { + return true; + } + if (sys.directoryExists(directoryPath)) { + existingDirectories[directoryPath] = true; + return true; + } + return false; + } + + function ensureDirectoriesExist(directoryPath: string) { + if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { + var parentDirectory = getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + sys.createDirectory(directoryPath); + } + } + + try { + ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); + sys.writeFile(fileName, data, writeByteOrderMark); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + + return { + getSourceFile, + getDefaultLibFilename: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"), + writeFile, + getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()), + useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames, + getCanonicalFileName, + getNewLine: () => sys.newLine + }; + } + + export function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program { + var program: Program; + var files: SourceFile[] = []; + var filesByName: Map = {}; + var errors: Diagnostic[] = []; + var seenNoDefaultLib = options.noLib; + var commonSourceDirectory: string; + + forEach(rootNames, name => processRootFile(name, false)); + if (!seenNoDefaultLib) { + processRootFile(host.getDefaultLibFilename(options), true); + } + verifyCompilerOptions(); + errors.sort(compareDiagnostics); + + + var diagnosticsProducingTypeChecker: TypeChecker; + var noDiagnosticsTypeChecker: TypeChecker; + var emitHost: EmitHost; + + program = { + getSourceFile: getSourceFile, + getSourceFiles: () => files, + getCompilerOptions: () => options, + getCompilerHost: () => host, + getDiagnostics: getDiagnostics, + getGlobalDiagnostics: getGlobalDiagnostics, + getDeclarationDiagnostics: getDeclarationDiagnostics, + getTypeChecker, + getCommonSourceDirectory: () => commonSourceDirectory, + emitFiles: invokeEmitter, + isEmitBlocked, + getCurrentDirectory: host.getCurrentDirectory, + }; + return program; + + function getEmitHost() { + return emitHost || (emitHost = createEmitHostFromProgram(program)); + } + + function hasEarlyErrors(sourceFile?: SourceFile): boolean { + return forEach(getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile), d => d.isEarly); + } + + function isEmitBlocked(sourceFile?: SourceFile): boolean { + return getDiagnostics(sourceFile).length !== 0 || + hasEarlyErrors(sourceFile) || + (options.noEmitOnError && getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0); + } + + function getDiagnosticsProducingTypeChecker() { + return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true)); + } + + function getTypeChecker(produceDiagnostics: boolean) { + if (produceDiagnostics) { + return getDiagnosticsProducingTypeChecker(); + } + else { + return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, produceDiagnostics)); + } + } + + function getDeclarationDiagnostics(targetSourceFile: SourceFile): Diagnostic[]{ + var typeChecker = getDiagnosticsProducingTypeChecker(); + typeChecker.getDiagnostics(targetSourceFile); + var resolver = typeChecker.getEmitResolver(); + return ts.getDeclarationDiagnostics(getEmitHost(), resolver, targetSourceFile); + } + + function invokeEmitter(targetSourceFile?: SourceFile) { + var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(); + return emitFiles(resolver, getEmitHost(), targetSourceFile); + } function getSourceFile(filename: string) { + filename = host.getCanonicalFileName(filename); + return hasProperty(filesByName, filename) ? filesByName[filename] : undefined; + } + + function getDiagnostics(sourceFile?: SourceFile): Diagnostic[] { + return sourceFile ? filter(errors, e => e.file === sourceFile) : errors; + } + + function getGlobalDiagnostics(): Diagnostic[] { + return filter(errors, e => !e.file); + } + + function hasExtension(filename: string): boolean { + return getBaseFilename(filename).indexOf(".") >= 0; + } + + function processRootFile(filename: string, isDefaultLib: boolean) { + processSourceFile(normalizePath(filename), isDefaultLib); + } + + function processSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) { + if (refEnd !== undefined && refPos !== undefined) { + var start = refPos; + var length = refEnd - refPos; + } + var diagnostic: DiagnosticMessage; + if (hasExtension(filename)) { + if (!options.allowNonTsExtensions && !fileExtensionIs(filename, ".ts")) { + diagnostic = Diagnostics.File_0_must_have_extension_ts_or_d_ts; + } + else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) { + diagnostic = Diagnostics.File_0_not_found; + } + else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) { + diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself; + } + } + else { + if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) { + diagnostic = Diagnostics.File_0_not_found; + filename += ".ts"; + } + } + + if (diagnostic) { + if (refFile) { + errors.push(createFileDiagnostic(refFile, start, length, diagnostic, filename)); + } + else { + errors.push(createCompilerDiagnostic(diagnostic, filename)); + } + } + } + + // Get source file from normalized filename + function findSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile { + var canonicalName = host.getCanonicalFileName(filename); + if (hasProperty(filesByName, canonicalName)) { + // We've already looked for this file, use cached result + return getSourceFileFromCache(filename, canonicalName, /*useAbsolutePath*/ false); + } + else { + var normalizedAbsolutePath = getNormalizedAbsolutePath(filename, host.getCurrentDirectory()); + var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath); + if (hasProperty(filesByName, canonicalAbsolutePath)) { + return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, /*useAbsolutePath*/ true); + } + + // We haven't looked for this file, do so now and cache result + var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, hostErrorMessage => { + if (refFile) { + errors.push(createFileDiagnostic(refFile, refStart, refLength, + Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + else { + errors.push(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage)); + } + }); + if (file) { + seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib; + + // Set the source file for normalized absolute path + filesByName[canonicalAbsolutePath] = file; + + if (!options.noResolve) { + var basePath = getDirectoryPath(filename); + processReferencedFiles(file, basePath); + processImportedModules(file, basePath); + } + if (isDefaultLib) { + files.unshift(file); + } + else { + files.push(file); + } + forEach(file.getSyntacticDiagnostics(), e => { + errors.push(e); + }); + } + } + return file; + + function getSourceFileFromCache(filename: string, canonicalName: string, useAbsolutePath: boolean): SourceFile { + var file = filesByName[canonicalName]; + if (file && host.useCaseSensitiveFileNames()) { + var sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename; + if (canonicalName !== sourceFileName) { + errors.push(createFileDiagnostic(refFile, refStart, refLength, + Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName)); + } + } + return file; + } + } + + function processReferencedFiles(file: SourceFile, basePath: string) { + forEach(file.referencedFiles, ref => { + var referencedFilename = isRootedDiskPath(ref.filename) ? ref.filename : combinePaths(basePath, ref.filename); + processSourceFile(normalizePath(referencedFilename), /* isDefaultLib */ false, file, ref.pos, ref.end); + }); + } + + function processImportedModules(file: SourceFile, basePath: string) { + forEach(file.statements, node => { + if (isExternalModuleImportDeclaration(node) && + getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) { + + var nameLiteral = getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + var searchPath = basePath; + while (true) { + var searchName = normalizePath(combinePaths(searchPath, moduleName)); + if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) { + break; + } + + var parentPath = getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + } + } + else if (node.kind === SyntaxKind.ModuleDeclaration && (node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An AmbientExternalModuleDeclaration declares an external module. + // This type of declaration is permitted only in the global module. + // The StringLiteral must specify a top - level external module name. + // Relative external module names are not permitted + forEachChild((node).body, node => { + if (isExternalModuleImportDeclaration(node) && + getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) { + + var nameLiteral = getExternalModuleImportDeclarationExpression(node); + var moduleName = nameLiteral.text; + if (moduleName) { + // TypeScript 1.0 spec (April 2014): 12.1.6 + // An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules + // only through top - level external module names. Relative external module names are not permitted. + var searchName = normalizePath(combinePaths(basePath, moduleName)); + var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral); + if (!tsFile) { + findModuleSourceFile(searchName + ".d.ts", nameLiteral); + } + } + } + }); + } + }); + + function findModuleSourceFile(filename: string, nameLiteral: LiteralExpression) { + return findSourceFile(filename, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos); + } + } + + function verifyCompilerOptions() { + if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) { + // Error to specify --mapRoot or --sourceRoot without mapSourceFiles + if (options.mapRoot) { + errors.push(createCompilerDiagnostic(Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + if (options.sourceRoot) { + errors.push(createCompilerDiagnostic(Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option)); + } + return; + } + + var firstExternalModule = forEach(files, f => isExternalModule(f) ? f : undefined); + if (firstExternalModule && options.module === ModuleKind.None) { + // We cannot use createDiagnosticFromNode because nodes do not have parents yet + var externalModuleErrorSpan = getErrorSpanForNode(firstExternalModule.externalModuleIndicator); + var errorStart = skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); + var errorLength = externalModuleErrorSpan.end - errorStart; + errors.push(createFileDiagnostic(firstExternalModule, errorStart, errorLength, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided)); + } + + // there has to be common source directory if user specified --outdir || --sourcRoot + // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted + if (options.outDir || // there is --outDir specified + options.sourceRoot || // there is --sourceRoot specified + (options.mapRoot && // there is --mapRoot Specified and there would be multiple js files generated + (!options.out || firstExternalModule !== undefined))) { + + var commonPathComponents: string[]; + forEach(files, sourceFile => { + // Each file contributes into common source file path + if (!(sourceFile.flags & NodeFlags.DeclarationFile) + && !fileExtensionIs(sourceFile.filename, ".js")) { + var sourcePathComponents = getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory()); + sourcePathComponents.pop(); // FileName is not part of directory + if (commonPathComponents) { + for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) { + if (commonPathComponents[i] !== sourcePathComponents[i]) { + if (i === 0) { + errors.push(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files)); + return; + } + + // New common path found that is 0 -> i-1 + commonPathComponents.length = i; + break; + } + } + + // If the fileComponent path completely matched and less than already found update the length + if (sourcePathComponents.length < commonPathComponents.length) { + commonPathComponents.length = sourcePathComponents.length; + } + } + else { + // first file + commonPathComponents = sourcePathComponents; + } + } + }); + + commonSourceDirectory = getNormalizedPathFromPathComponents(commonPathComponents); + if (commonSourceDirectory) { + // Make sure directory path ends with directory separator so this string can directly + // used to replace with "" to get the relative path of the source file and the relative path doesn't + // start with / making it rooted path + commonSourceDirectory += directorySeparator; + } + } + + if (options.noEmit) { + if (options.out || options.outDir) { + errors.push(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_out_or_outDir)); + } + + if (options.declaration) { + errors.push(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration)); + } + } + } + } +} \ No newline at end of file diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index 9853e22d9f..427bc0012d 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -1,15 +1,10 @@ -/// /// /// module ts { export interface ErrorCallback { - (message: DiagnosticMessage): void; - } - - export interface CommentCallback { - (pos: number, end: number): void; + (message: DiagnosticMessage, length: number): void; } export interface Scanner { @@ -392,34 +387,57 @@ module ts { } } + // All conflict markers consist of the same character repeated seven times. If it is + // a <<<<<<< or >>>>>>> marker then it is also followd by a space. + var mergeConflictMarkerLength = "<<<<<<<".length; + function isConflictMarkerTrivia(text: string, pos: number) { + Debug.assert(pos >= 0); + // Conflict markers must be at the start of a line. - if (pos > 0 && isLineBreak(text.charCodeAt(pos - 1))) { + if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { var ch = text.charCodeAt(pos); - // All conflict markers consist of the same character repeated seven times. If it is - // a <<<<<<< or >>>>>>> marker then it is also followd by a space. - var markerLength = "<<<<<<<".length; - - if ((pos + markerLength) < text.length) { - for (var i = 0, n = markerLength; i < n; i++) { + if ((pos + mergeConflictMarkerLength) < text.length) { + for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) { if (text.charCodeAt(pos + i) !== ch) { return false; } } return ch === CharacterCodes.equals || - text.charCodeAt(pos + markerLength) === CharacterCodes.space; + text.charCodeAt(pos + mergeConflictMarkerLength) === CharacterCodes.space; } } return false; } - function scanConflictMarkerTrivia(text: string, pos: number) { + function scanConflictMarkerTrivia(text: string, pos: number, error?: ErrorCallback) { + if (error) { + error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); + } + + var ch = text.charCodeAt(pos); var len = text.length; - while (pos < len && !isLineBreak(text.charCodeAt(pos))) { - pos++; + + if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { + while (pos < len && !isLineBreak(text.charCodeAt(pos))) { + pos++; + } + } + else { + Debug.assert(ch === CharacterCodes.equals); + // Consume everything from the start of the mid-conlict marker to the start of the next + // end-conflict marker. + while (pos < len) { + var ch = text.charCodeAt(pos); + if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) { + break; + } + + pos++; + } } return pos; @@ -529,9 +547,9 @@ module ts { var precedingLineBreak: boolean; var tokenIsUnterminated: boolean; - function error(message: DiagnosticMessage): void { + function error(message: DiagnosticMessage, length?: number): void { if (onError) { - onError(message); + onError(message, length || 0); } } @@ -1058,8 +1076,7 @@ module ts { return pos++, token = SyntaxKind.SemicolonToken; case CharacterCodes.lessThan: if (isConflictMarkerTrivia(text, pos)) { - error(Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -1080,8 +1097,7 @@ module ts { return pos++, token = SyntaxKind.LessThanToken; case CharacterCodes.equals: if (isConflictMarkerTrivia(text, pos)) { - error(Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } @@ -1102,8 +1118,7 @@ module ts { return pos++, token = SyntaxKind.EqualsToken; case CharacterCodes.greaterThan: if (isConflictMarkerTrivia(text, pos)) { - error(Diagnostics.Merge_conflict_marker_encountered); - pos = scanConflictMarkerTrivia(text, pos); + pos = scanConflictMarkerTrivia(text, pos, error); if (skipTrivia) { continue; } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index bc4d48b751..9d03892069 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -1,11 +1,4 @@ -/// -/// -/// -/// -/// -/// -/// -/// +/// /// module ts { @@ -293,12 +286,15 @@ module ts { var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true); var checkStart = new Date().getTime(); errors = checker.getDiagnostics(); - if (checker.isEmitBlocked()) { + if (program.isEmitBlocked()) { exitStatus = EmitReturnStatus.AllOutputGenerationSkipped; } + else if (compilerOptions.noEmit) { + exitStatus = EmitReturnStatus.Succeeded; + } else { var emitStart = new Date().getTime(); - var emitOutput = checker.emitFiles(); + var emitOutput = program.emitFiles(); var emitErrors = emitOutput.diagnostics; exitStatus = emitOutput.emitResultStatus; var reportStart = new Date().getTime(); diff --git a/src/compiler/types.ts b/src/compiler/types.ts index f3c87ceb68..60ed8352b9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1,5 +1,3 @@ -/// - module ts { export interface Map { [index: string]: T; @@ -18,6 +16,8 @@ module ts { MultiLineCommentTrivia, NewLineTrivia, WhitespaceTrivia, + // We detect and provide better error recovery when we encounter a git merge marker. This + // allows us to edit files with git-conflict markers in them in a much more pleasant manner. ConflictMarkerTrivia, // Literals NumericLiteral, @@ -218,10 +218,9 @@ module ts { LabeledStatement, ThrowStatement, TryStatement, - TryBlock, - FinallyBlock, DebuggerStatement, VariableDeclaration, + VariableDeclarationList, FunctionDeclaration, ClassDeclaration, InterfaceDeclaration, @@ -249,7 +248,6 @@ module ts { EnumMember, // Top-level nodes SourceFile, - Program, // Synthesized list SyntaxList, @@ -276,26 +274,24 @@ module ts { LastLiteralToken = NoSubstitutionTemplateLiteral, FirstTemplateToken = NoSubstitutionTemplateLiteral, LastTemplateToken = TemplateTail, - FirstOperator = SemicolonToken, - LastOperator = CaretEqualsToken, FirstBinaryOperator = LessThanToken, LastBinaryOperator = CaretEqualsToken, FirstNode = QualifiedName, } export const enum NodeFlags { - Export = 0x00000001, // Declarations - Ambient = 0x00000002, // Declarations - Public = 0x00000010, // Property/Method - Private = 0x00000020, // Property/Method - Protected = 0x00000040, // Property/Method - Static = 0x00000080, // Property/Method - MultiLine = 0x00000100, // Multi-line array or object literal - Synthetic = 0x00000200, // Synthetic node (for full fidelity) - DeclarationFile = 0x00000400, // Node is a .d.ts file - Let = 0x00000800, // Variable declaration - Const = 0x00001000, // Variable declaration - OctalLiteral = 0x00002000, + Export = 0x00000001, // Declarations + Ambient = 0x00000002, // Declarations + Public = 0x00000010, // Property/Method + Private = 0x00000020, // Property/Method + Protected = 0x00000040, // Property/Method + Static = 0x00000080, // Property/Method + MultiLine = 0x00000100, // Multi-line array or object literal + Synthetic = 0x00000200, // Synthetic node (for full fidelity) + DeclarationFile = 0x00000400, // Node is a .d.ts file + Let = 0x00000800, // Variable declaration + Const = 0x00001000, // Variable declaration + OctalLiteral = 0x00002000, Modifier = Export | Ambient | Public | Private | Protected | Static, AccessibilityModifier = Public | Private | Protected, @@ -396,11 +392,16 @@ module ts { // SyntaxKind.VariableDeclaration export interface VariableDeclaration extends Declaration { + parent?: VariableDeclarationList; name: Identifier | BindingPattern; // Declared variable name type?: TypeNode; // Optional type annotation initializer?: Expression; // Optional initializer } + export interface VariableDeclarationList extends Node { + declarations: NodeArray; + } + // SyntaxKind.Parameter export interface ParameterDeclaration extends Declaration { dotDotDotToken?: Node; // Present on rest parameter @@ -606,7 +607,7 @@ module ts { export interface VoidExpression extends UnaryExpression { expression: UnaryExpression; } - + export interface YieldExpression extends Expression { asteriskToken?: Node; expression: Expression; @@ -709,7 +710,7 @@ module ts { } export interface VariableStatement extends Statement { - declarations: NodeArray; + declarationList: VariableDeclarationList; } export interface ExpressionStatement extends Statement { @@ -735,15 +736,13 @@ module ts { } export interface ForStatement extends IterationStatement { - declarations?: NodeArray; - initializer?: Expression; + initializer?: VariableDeclarationList | Expression; condition?: Expression; iterator?: Expression; } export interface ForInStatement extends IterationStatement { - declarations?: NodeArray; - variable?: Expression; + initializer: VariableDeclarationList | Expression; expression: Expression; } @@ -881,9 +880,22 @@ module ts { filename: string; text: string; + getLineAndCharacterFromPosition(position: number): LineAndCharacter; getPositionFromLineAndCharacter(line: number, character: number): number; getLineStarts(): number[]; + + // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter + // indicates what changed between the 'text' that this SourceFile has and the 'newText'. + // The SourceFile will be created with the compiler attempting to reuse as many nodes from + // this file as possible. + // + // Note: this function mutates nodes from this SourceFile. That means any existing nodes + // from this SourceFile that are being held onto may change as a result (including + // becoming detached from any SourceFile). It is recommended that this SourceFile not + // be used once 'update' is called on it. + update(newText: string, textChangeRange: TextChangeRange): SourceFile; + amdDependencies: string[]; amdModuleName: string; referencedFiles: FileReference[]; @@ -910,15 +922,33 @@ module ts { identifiers: Map; } - export interface Program { - getSourceFile(filename: string): SourceFile; - getSourceFiles(): SourceFile[]; + export interface ScriptReferenceHost { getCompilerOptions(): CompilerOptions; + getSourceFile(filename: string): SourceFile; + getCurrentDirectory(): string; + } + + export interface Program extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; getCompilerHost(): CompilerHost; + getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; - getTypeChecker(fullTypeCheckMode: boolean): TypeChecker; + getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; + + // Gets a type checker that can be used to semantically analyze source fils in the program. + // The 'produceDiagnostics' flag determines if the checker will produce diagnostics while + // analyzing the code. It can be set to 'false' to make many type checking operaitons + // faster. With this flag set, the checker can avoid codepaths only necessary to produce + // diagnostics, but not necessary to answer semantic questions about the code. + // + // If 'produceDiagnostics' is false, then any calls to get diagnostics from the TypeChecker + // will throw an invalid operation exception. + getTypeChecker(produceDiagnostics: boolean): TypeChecker; getCommonSourceDirectory(): string; + + emitFiles(targetSourceFile?: SourceFile): EmitResult; + isEmitBlocked(sourceFile?: SourceFile): boolean; } export interface SourceMapSpan { @@ -944,7 +974,7 @@ module ts { // Return code used by getEmitOutput function to indicate status of the function export enum EmitReturnStatus { - Succeeded = 0, // All outputs generated as requested (.js, .map, .d.ts), no errors reported + Succeeded = 0, // All outputs generated if requested (.js, .map, .d.ts), no errors reported AllOutputGenerationSkipped = 1, // No .js generated because of syntax errors, nothing generated JSGeneratedWithSemanticErrors = 2, // .js and .map generated with semantic errors DeclarationGenerationSkipped = 3, // .d.ts generation skipped because of semantic errors or declaration emitter specific errors; Output .js with semantic errors @@ -958,16 +988,22 @@ module ts { sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps } + export interface TypeCheckerHost { + getCompilerOptions(): CompilerOptions; + getCompilerHost(): CompilerHost; + + getSourceFiles(): SourceFile[]; + getSourceFile(filename: string): SourceFile; + } + export interface TypeChecker { - getProgram(): Program; + getEmitResolver(): EmitResolver; getDiagnostics(sourceFile?: SourceFile): Diagnostic[]; - getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[]; getGlobalDiagnostics(): Diagnostic[]; getNodeCount(): number; getIdentifierCount(): number; getSymbolCount(): number; getTypeCount(): number; - emitFiles(targetSourceFile?: SourceFile): EmitResult; getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; getDeclaredTypeOfSymbol(symbol: Symbol): Type; getPropertiesOfType(type: Type): Symbol[]; @@ -991,7 +1027,7 @@ module ts { isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; isUndefinedSymbol(symbol: Symbol): boolean; isArgumentsSymbol(symbol: Symbol): boolean; - isEmitBlocked(sourceFile?: SourceFile): boolean; + // Returns the constant value of this enum member, or 'undefined' if the enum member has a computed value. getEnumMemberValue(node: EnumMember): number; isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; @@ -1030,7 +1066,7 @@ module ts { } export const enum TypeFormatFlags { - None = 0x00000000, + None = 0x00000000, WriteArrayAsGenericType = 0x00000001, // Write Array instead T[] UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal NoTruncation = 0x00000004, // Don't truncate typeToString result @@ -1041,14 +1077,18 @@ module ts { } export const enum SymbolFormatFlags { - None = 0x00000000, - WriteTypeParametersOrArguments = 0x00000001, // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here - // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p - UseOnlyExternalAliasing = 0x00000002, // Use only external alias information to get the symbol name in the given context - // eg. module m { export class c { } } import x = m.c; - // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + None = 0x00000000, + + // Write symbols's type argument if it is instantiated symbol + // eg. class C { p: T } <-- Show p as C.p here + // var a: C; + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + WriteTypeParametersOrArguments = 0x00000001, + + // Use only external alias information to get the symbol name in the given context + // eg. module m { export class c { } } import x = m.c; + // When this flag is specified m.c will be used to refer to the class instead of alias symbol x + UseOnlyExternalAliasing = 0x00000002, } export const enum SymbolAccessibility { @@ -1069,7 +1109,6 @@ module ts { } export interface EmitResolver { - getProgram(): Program; getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string; getExpressionNamePrefix(node: Identifier): string; getExportAssignmentName(node: SourceFile): string; @@ -1086,51 +1125,50 @@ module ts { isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; - isEmitBlocked(sourceFile?: SourceFile): boolean; isUnknownIdentifier(location: Node, name: string): boolean; } export const enum SymbolFlags { - FunctionScopedVariable = 0x00000001, // Variable (var) or parameter - BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const) - Property = 0x00000004, // Property or enum member - EnumMember = 0x00000008, // Enum member - Function = 0x00000010, // Function - Class = 0x00000020, // Class - Interface = 0x00000040, // Interface - ConstEnum = 0x00000080, // Const enum - RegularEnum = 0x00000100, // Enum - ValueModule = 0x00000200, // Instantiated module - NamespaceModule = 0x00000400, // Uninstantiated module - TypeLiteral = 0x00000800, // Type Literal - ObjectLiteral = 0x00001000, // Object Literal - Method = 0x00002000, // Method - Constructor = 0x00004000, // Constructor - GetAccessor = 0x00008000, // Get accessor - SetAccessor = 0x00010000, // Set accessor - Signature = 0x00020000, // Call, construct, or index signature - TypeParameter = 0x00040000, // Type parameter - TypeAlias = 0x00080000, // Type alias + FunctionScopedVariable = 0x00000001, // Variable (var) or parameter + BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const) + Property = 0x00000004, // Property or enum member + EnumMember = 0x00000008, // Enum member + Function = 0x00000010, // Function + Class = 0x00000020, // Class + Interface = 0x00000040, // Interface + ConstEnum = 0x00000080, // Const enum + RegularEnum = 0x00000100, // Enum + ValueModule = 0x00000200, // Instantiated module + NamespaceModule = 0x00000400, // Uninstantiated module + TypeLiteral = 0x00000800, // Type Literal + ObjectLiteral = 0x00001000, // Object Literal + Method = 0x00002000, // Method + Constructor = 0x00004000, // Constructor + GetAccessor = 0x00008000, // Get accessor + SetAccessor = 0x00010000, // Set accessor + Signature = 0x00020000, // Call, construct, or index signature + TypeParameter = 0x00040000, // Type parameter + TypeAlias = 0x00080000, // Type alias // Export markers (see comment in declareModuleMember in binder) - ExportValue = 0x00100000, // Exported value marker - ExportType = 0x00200000, // Exported type marker - ExportNamespace = 0x00400000, // Exported namespace marker - Import = 0x00800000, // Import - Instantiated = 0x01000000, // Instantiated symbol - Merged = 0x02000000, // Merged symbol (created during program binding) - Transient = 0x04000000, // Transient symbol (created during type check) - Prototype = 0x08000000, // Prototype property (no source representation) - UnionProperty = 0x10000000, // Property in union type - Optional = 0x20000000, // Optional property + ExportValue = 0x00100000, // Exported value marker + ExportType = 0x00200000, // Exported type marker + ExportNamespace = 0x00400000, // Exported namespace marker + Import = 0x00800000, // Import + Instantiated = 0x01000000, // Instantiated symbol + Merged = 0x02000000, // Merged symbol (created during program binding) + Transient = 0x04000000, // Transient symbol (created during type check) + Prototype = 0x08000000, // Prototype property (no source representation) + UnionProperty = 0x10000000, // Property in union type + Optional = 0x20000000, // Optional property - Enum = RegularEnum | ConstEnum, - Variable = FunctionScopedVariable | BlockScopedVariable, - Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, - Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias, + Enum = RegularEnum | ConstEnum, + Variable = FunctionScopedVariable | BlockScopedVariable, + Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor, + Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias, Namespace = ValueModule | NamespaceModule, - Module = ValueModule | NamespaceModule, - Accessor = GetAccessor | SetAccessor, + Module = ValueModule | NamespaceModule, + Accessor = GetAccessor | SetAccessor, // Variables can be redeclared, but can not redeclare a block-scoped declaration with the // same name, or any other value that is not a variable, e.g. ValueModule or Class @@ -1140,34 +1178,34 @@ module ts { // they can not merge with anything in the value space BlockScopedVariableExcludes = Value, - ParameterExcludes = Value, - PropertyExcludes = Value, - EnumMemberExcludes = Value, - FunctionExcludes = Value & ~(Function | ValueModule), - ClassExcludes = (Value | Type) & ~ValueModule, - InterfaceExcludes = Type & ~Interface, - RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules - ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums - ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule), + ParameterExcludes = Value, + PropertyExcludes = Value, + EnumMemberExcludes = Value, + FunctionExcludes = Value & ~(Function | ValueModule), + ClassExcludes = (Value | Type) & ~ValueModule, + InterfaceExcludes = Type & ~Interface, + RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules + ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums + ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule), NamespaceModuleExcludes = 0, - MethodExcludes = Value & ~Method, - GetAccessorExcludes = Value & ~SetAccessor, - SetAccessorExcludes = Value & ~GetAccessor, - TypeParameterExcludes = Type & ~TypeParameter, - TypeAliasExcludes = Type, - ImportExcludes = Import, // Imports collide with all other imports with the same name + MethodExcludes = Value & ~Method, + GetAccessorExcludes = Value & ~SetAccessor, + SetAccessorExcludes = Value & ~GetAccessor, + TypeParameterExcludes = Type & ~TypeParameter, + TypeAliasExcludes = Type, + ImportExcludes = Import, // Imports collide with all other imports with the same name ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Import, ExportHasLocal = Function | Class | Enum | ValueModule, - HasLocals = Function | Module | Method | Constructor | Accessor | Signature, + HasLocals = Function | Module | Method | Constructor | Accessor | Signature, HasExports = Class | Enum | Module, HasMembers = Class | Interface | TypeLiteral | ObjectLiteral, - IsContainer = HasLocals | HasExports | HasMembers, + IsContainer = HasLocals | HasExports | HasMembers, PropertyOrAccessor = Property | Accessor, - Export = ExportNamespace | ExportType | ExportValue, + Export = ExportNamespace | ExportType | ExportValue, } export interface Symbol { @@ -1201,16 +1239,16 @@ module ts { } export const enum NodeCheckFlags { - TypeChecked = 0x00000001, // Node has been type checked - LexicalThis = 0x00000002, // Lexical 'this' reference - CaptureThis = 0x00000004, // Lexical 'this' used in body - EmitExtends = 0x00000008, // Emit __extends - SuperInstance = 0x00000010, // Instance 'super' reference - SuperStatic = 0x00000020, // Static 'super' reference - ContextChecked = 0x00000040, // Contextual types have been assigned + TypeChecked = 0x00000001, // Node has been type checked + LexicalThis = 0x00000002, // Lexical 'this' reference + CaptureThis = 0x00000004, // Lexical 'this' used in body + EmitExtends = 0x00000008, // Emit __extends + SuperInstance = 0x00000010, // Instance 'super' reference + SuperStatic = 0x00000020, // Static 'super' reference + ContextChecked = 0x00000040, // Contextual types have been assigned // Values for enum members have been computed, and any errors have been reported for them. - EnumValuesComputed = 0x00000080, + EnumValuesComputed = 0x00000080, } export interface NodeLinks { @@ -1228,26 +1266,26 @@ module ts { } export const enum TypeFlags { - Any = 0x00000001, - String = 0x00000002, - Number = 0x00000004, - Boolean = 0x00000008, - Void = 0x00000010, - Undefined = 0x00000020, - Null = 0x00000040, - Enum = 0x00000080, // Enum type - StringLiteral = 0x00000100, // String literal type - TypeParameter = 0x00000200, // Type parameter - Class = 0x00000400, // Class - Interface = 0x00000800, // Interface - Reference = 0x00001000, // Generic type reference - Tuple = 0x00002000, // Tuple - Union = 0x00004000, // Union - Anonymous = 0x00008000, // Anonymous - FromSignature = 0x00010000, // Created for signature assignment check - Unwidened = 0x00020000, // Unwidened type (is or contains Undefined or Null type) + Any = 0x00000001, + String = 0x00000002, + Number = 0x00000004, + Boolean = 0x00000008, + Void = 0x00000010, + Undefined = 0x00000020, + Null = 0x00000040, + Enum = 0x00000080, // Enum type + StringLiteral = 0x00000100, // String literal type + TypeParameter = 0x00000200, // Type parameter + Class = 0x00000400, // Class + Interface = 0x00000800, // Interface + Reference = 0x00001000, // Generic type reference + Tuple = 0x00002000, // Tuple + Union = 0x00004000, // Union + Anonymous = 0x00008000, // Anonymous + FromSignature = 0x00010000, // Created for signature assignment check + Unwidened = 0x00020000, // Unwidened type (is or contains Undefined or Null type) - Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null, + Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null, StringLike = String | StringLiteral, NumberLike = Number | Enum, ObjectType = Class | Interface | Reference | Tuple | Anonymous, @@ -1364,7 +1402,7 @@ module ts { inferences: TypeInferences[]; // Inferences made for each type parameter inferredTypes: Type[]; // Inferred type for each type parameter failedTypeParameterIndex?: number; // Index of type parameter for which inference failed - // It is optional because in contextual signature instantiation, nothing fails + // It is optional because in contextual signature instantiation, nothing fails } export interface DiagnosticMessage { @@ -1415,6 +1453,7 @@ module ts { locale?: string; mapRoot?: string; module?: ModuleKind; + noEmit?: boolean; noEmitOnError?: boolean; noErrorTruncation?: boolean; noImplicitAny?: boolean; @@ -1448,7 +1487,6 @@ module ts { character: number; } - export const enum ScriptTarget { ES3 = 0, ES5 = 1, @@ -1499,7 +1537,7 @@ module ts { narrowNoBreakSpace = 0x202F, ideographicSpace = 0x3000, mathematicalSpace = 0x205F, - ogham = 0x1680, + ogham = 0x1680, _ = 0x5F, $ = 0x24, @@ -1620,4 +1658,14 @@ module ts { useCaseSensitiveFileNames(): boolean; getNewLine(): string; } + + export interface TextSpan { + start: number; + length: number; + } + + export interface TextChangeRange { + span: TextSpan; + newLength: number; + } } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 4c57cf2cf0..7494ec9f6c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -23,6 +23,17 @@ module ts { string(): string; } + export interface EmitHost extends ScriptReferenceHost { + getSourceFiles(): SourceFile[]; + isEmitBlocked(sourceFile?: SourceFile): boolean; + + getCommonSourceDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + + writeFile(filename: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; + } + // Pool writers to avoid needing to allocate them for every symbol we write. var stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { @@ -62,22 +73,18 @@ module ts { return node.end - node.pos; } - function hasFlag(val: number, flag: number): boolean { - return (val & flag) !== 0; - } - // Returns true if this node contains a parse error anywhere underneath it. export function containsParseError(node: Node): boolean { aggregateChildData(node); - return hasFlag(node.parserContextFlags, ParserContextFlags.ThisNodeOrAnySubNodesHasError); + return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0 } function aggregateChildData(node: Node): void { - if (!hasFlag(node.parserContextFlags, ParserContextFlags.HasAggregatedChildData)) { + if (!(node.parserContextFlags & ParserContextFlags.HasAggregatedChildData)) { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - var thisNodeOrAnySubNodesHasError = hasFlag(node.parserContextFlags, ParserContextFlags.ThisNodeHasError) || + var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || forEachChild(node, containsParseError); // If so, mark ourselves accordingly. @@ -110,14 +117,34 @@ module ts { return node.pos; } - export function isMissingNode(node: Node) { + // Returns true if this node is missing from the actual source code. 'missing' is different + // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes + // in the tree), it is definitel missing. HOwever, a node may be defined, but still be + // missing. This happens whenever the parser knows it needs to parse something, but can't + // get anything in the source code that it expects at that location. For example: + // + // var a: ; + // + // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source + // code). So the parser will attempt to parse out a type, and will create an actual node. + // However, this node will be 'missing' in the sense that no actual source-code/tokens are + // contained within it. + export function nodeIsMissing(node: Node) { + if (!node) { + return true; + } + return node.pos === node.end && node.kind !== SyntaxKind.EndOfFileToken; } + + export function nodeIsPresent(node: Node) { + return !nodeIsMissing(node); + } export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number { // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't* // want to skip trivia because this will launch us forward to the next token. - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return node.pos; } @@ -125,7 +152,7 @@ module ts { } export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } @@ -134,7 +161,7 @@ module ts { } export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string { - if (isMissingNode(node)) { + if (nodeIsMissing(node)) { return ""; } @@ -216,12 +243,47 @@ module ts { return node.kind === SyntaxKind.EnumDeclaration && isConst(node); } + function walkUpBindingElementsAndPatterns(node: Node): Node { + while (node && (node.kind === SyntaxKind.BindingElement || isBindingPattern(node))) { + node = node.parent; + } + + return node; + } + + // Returns the node flags for this node and all relevant parent nodes. This is done so that + // nodes like variable declarations and binding elements can returned a view of their flags + // that includes the modifiers from their container. i.e. flags like export/declare aren't + // stored on the variable declaration directly, but on the containing variable statement + // (if it has one). Similarly, flags for let/const are store on the variable declaration + // list. By calling this function, all those flags are combined so that the client can treat + // the node as if it actually had those flags. + export function getCombinedNodeFlags(node: Node): NodeFlags { + node = walkUpBindingElementsAndPatterns(node); + + var flags = node.flags; + if (node.kind === SyntaxKind.VariableDeclaration) { + node = node.parent; + } + + if (node && node.kind === SyntaxKind.VariableDeclarationList) { + flags |= node.flags; + node = node.parent; + } + + if (node && node.kind === SyntaxKind.VariableStatement) { + flags |= node.flags; + } + + return flags; + } + export function isConst(node: Node): boolean { - return !!(node.flags & NodeFlags.Const); + return !!(getCombinedNodeFlags(node) & NodeFlags.Const); } export function isLet(node: Node): boolean { - return !!(node.flags & NodeFlags.Let); + return !!(getCombinedNodeFlags(node) & NodeFlags.Let); } export function isPrologueDirective(node: Node): boolean { @@ -281,9 +343,7 @@ module ts { case SyntaxKind.DefaultClause: case SyntaxKind.LabeledStatement: case SyntaxKind.TryStatement: - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: return forEachChild(node, traverse); } } @@ -455,12 +515,14 @@ module ts { case SyntaxKind.SwitchStatement: return (parent).expression === node; case SyntaxKind.ForStatement: - return (parent).initializer === node || - (parent).condition === node || - (parent).iterator === node; + var forStatement = parent; + return (forStatement.initializer === node && forStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || + forStatement.condition === node || + forStatement.iterator === node; case SyntaxKind.ForInStatement: - return (parent).variable === node || - (parent).expression === node; + var forInStatement = parent; + return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) || + forInStatement.expression === node; case SyntaxKind.TypeAssertionExpression: return node === (parent).expression; case SyntaxKind.TemplateSpan: @@ -474,6 +536,12 @@ module ts { return false; } + export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { + var moduleState = getModuleInstanceState(node) + return moduleState === ModuleInstanceState.Instantiated || + (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); + } + export function isExternalModuleImportDeclaration(node: Node) { return node.kind === SyntaxKind.ImportDeclaration && (node).moduleReference.kind === SyntaxKind.ExternalModuleReference; } @@ -532,7 +600,10 @@ module ts { export function isInAmbientContext(node: Node): boolean { while (node) { - if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) return true; + if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) { + return true; + } + node = node.parent; } return false; @@ -637,11 +708,11 @@ module ts { return undefined; } - export function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference) { - if (!program.getCompilerOptions().noResolve) { + export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) { + if (!host.getCompilerOptions().noResolve) { var referenceFileName = isRootedDiskPath(reference.filename) ? reference.filename : combinePaths(getDirectoryPath(sourceFile.filename), reference.filename); - referenceFileName = getNormalizedAbsolutePath(referenceFileName, program.getCompilerHost().getCurrentDirectory()); - return program.getSourceFile(referenceFileName); + referenceFileName = getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); + return host.getSourceFile(referenceFileName); } } @@ -710,6 +781,7 @@ module ts { } } } + return undefined; } @@ -735,4 +807,229 @@ module ts { return false; } + export function createEmitHostFromProgram(program: Program): EmitHost { + var compilerHost = program.getCompilerHost(); + return { + getCanonicalFileName: compilerHost.getCanonicalFileName, + getCommonSourceDirectory: program.getCommonSourceDirectory, + getCompilerOptions: program.getCompilerOptions, + getCurrentDirectory: compilerHost.getCurrentDirectory, + getNewLine: compilerHost.getNewLine, + getSourceFile: program.getSourceFile, + getSourceFiles: program.getSourceFiles, + isEmitBlocked: program.isEmitBlocked, + writeFile: compilerHost.writeFile, + }; + } + + export function textSpanEnd(span: TextSpan) { + return span.start + span.length + } + + export function textSpanIsEmpty(span: TextSpan) { + return span.length === 0 + } + + export function textSpanContainsPosition(span: TextSpan, position: number) { + return position >= span.start && position < textSpanEnd(span); + } + + // Returns true if 'span' contains 'other'. + export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) { + return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span); + } + + export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { + var overlapStart = Math.max(span.start, other.start); + var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + return overlapStart < overlapEnd; + } + + export function textSpanOverlap(span1: TextSpan, span2: TextSpan) { + var overlapStart = Math.max(span1.start, span2.start); + var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (overlapStart < overlapEnd) { + return createTextSpanFromBounds(overlapStart, overlapEnd); + } + return undefined; + } + + export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) { + return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start + } + + export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { + var end = start + length; + return start <= textSpanEnd(span) && end >= span.start; + } + + export function textSpanIntersectsWithPosition(span: TextSpan, position: number) { + return position <= textSpanEnd(span) && position >= span.start; + } + + export function textSpanIntersection(span1: TextSpan, span2: TextSpan) { + var intersectStart = Math.max(span1.start, span2.start); + var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + if (intersectStart <= intersectEnd) { + return createTextSpanFromBounds(intersectStart, intersectEnd); + } + return undefined; + } + + export function createTextSpan(start: number, length: number): TextSpan { + if (start < 0) { + throw new Error("start < 0"); + } + if (length < 0) { + throw new Error("length < 0"); + } + + return { start, length }; + } + + export function createTextSpanFromBounds(start: number, end: number) { + return createTextSpan(start, end - start); + } + + export function textChangeRangeNewSpan(range: TextChangeRange) { + return createTextSpan(range.span.start, range.newLength); + } + + export function textChangeRangeIsUnchanged(range: TextChangeRange) { + return textSpanIsEmpty(range.span) && range.newLength === 0; + } + + export function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange { + if (newLength < 0) { + throw new Error("newLength < 0"); + } + + return { span, newLength }; + } + + export var unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); + + /** + * Called to merge all the changes that occurred across several versions of a script snapshot + * into a single change. i.e. if a user keeps making successive edits to a script we will + * have a text change from V1 to V2, V2 to V3, ..., Vn. + * + * This function will then merge those changes into a single change range valid between V1 and + * Vn. + */ + export function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange { + if (changes.length === 0) { + return unchangedTextChangeRange; + } + + if (changes.length === 1) { + return changes[0]; + } + + // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } + // as it makes things much easier to reason about. + var change0 = changes[0]; + + var oldStartN = change0.span.start; + var oldEndN = textSpanEnd(change0.span); + var newEndN = oldStartN + change0.newLength; + + for (var i = 1; i < changes.length; i++) { + var nextChange = changes[i]; + + // Consider the following case: + // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting + // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. + // i.e. the span starting at 30 with length 30 is increased to length 40. + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------------------------------------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------------------------------------------------- + // | \ + // | \ + // T2 | \ + // | \ + // | \ + // ------------------------------------------------------------------------------------------------------- + // + // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial + // it's just the min of the old and new starts. i.e.: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // ------------------------------------------------------------*------------------------------------------ + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ----------------------------------------$-------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // (Note the dots represent the newly inferrred start. + // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the + // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see + // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that + // means: + // + // 0 10 20 30 40 50 60 70 80 90 100 + // --------------------------------------------------------------------------------*---------------------- + // | / + // | /---- + // T1 | /---- + // | /---- + // | /---- + // ------------------------------------------------------------$------------------------------------------ + // . | \ + // . | \ + // T2 . | \ + // . | \ + // . | \ + // ----------------------------------------------------------------------*-------------------------------- + // + // In other words (in this case), we're recognizing that the second edit happened after where the first edit + // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started + // that's the same as if we started at char 80 instead of 60. + // + // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter + // than pusing the first edit forward to match the second, we'll push the second edit forward to match the + // first. + // + // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange + // semantics: { { start: 10, length: 70 }, newLength: 60 } + // + // The math then works out as follows. + // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the + // final result like so: + // + // { + // oldStart3: Min(oldStart1, oldStart2), + // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // } + + var oldStart1 = oldStartN; + var oldEnd1 = oldEndN; + var newEnd1 = newEndN; + + var oldStart2 = nextChange.span.start; + var oldEnd2 = textSpanEnd(nextChange.span); + var newEnd2 = oldStart2 + nextChange.newLength; + + oldStartN = Math.min(oldStart1, oldStart2); + oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); + newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); + } + + return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength: */newEndN - oldStartN); + } } \ No newline at end of file diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index fd49078d04..a88620c4e6 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -53,7 +53,7 @@ class CompilerBaselineRunner extends RunnerBase { var rootDir: string; var result: Harness.Compiler.CompilerResult; - var checker: ts.TypeChecker; + var program: ts.Program; var options: ts.CompilerOptions; // equivalent to the files that will be passed on the command line var toBeCompiled: { unitName: string; content: string }[]; @@ -61,12 +61,6 @@ class CompilerBaselineRunner extends RunnerBase { var otherFiles: { unitName: string; content: string }[]; var harnessCompiler: Harness.Compiler.HarnessCompiler; - var declFileCompilationResult: { - declInputFiles: { unitName: string; content: string }[]; - declOtherFiles: { unitName: string; content: string }[]; - declResult: Harness.Compiler.CompilerResult; - }; - var createNewInstance = false; before(() => { @@ -97,10 +91,10 @@ class CompilerBaselineRunner extends RunnerBase { }); } - options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _checker) { + options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _program) { result = compileResult; - // The checker will be used by typeWriter - checker = _checker; + // The program will be used by typeWriter + program = _program; }, function (settings) { harnessCompiler.setCompilerSettings(tcSettings); }); @@ -138,12 +132,11 @@ class CompilerBaselineRunner extends RunnerBase { lastUnit = undefined; rootDir = undefined; result = undefined; - checker = undefined; + program = undefined; options = undefined; toBeCompiled = undefined; otherFiles = undefined; harnessCompiler = undefined; - declFileCompilationResult = undefined; }); function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string { @@ -179,13 +172,6 @@ class CompilerBaselineRunner extends RunnerBase { } }); - // Compile .d.ts files - it('Correct compiler generated.d.ts for ' + fileName, () => { - declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { - harnessCompiler.setCompilerSettings(tcSettings); - }, options); - }); - it('Correct JS output for ' + fileName, () => { if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) { @@ -223,6 +209,10 @@ class CompilerBaselineRunner extends RunnerBase { } } + var declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { + harnessCompiler.setCompilerSettings(tcSettings); + }, options); + if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) { jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n'; jsCode += '\r\n\r\n'; @@ -267,10 +257,10 @@ class CompilerBaselineRunner extends RunnerBase { // NEWTODO: Type baselines if (result.errors.length === 0) { Harness.Baseline.runBaseline('Correct expression types for ' + fileName, justName.replace(/\.ts/, '.types'), () => { - var allFiles = toBeCompiled.concat(otherFiles).filter(file => !!checker.getProgram().getSourceFile(file.unitName)); + var allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName)); var typeLines: string[] = []; var typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; - var walker = new TypeWriterWalker(checker); + var walker = new TypeWriterWalker(program); allFiles.forEach(file => { var codeLines = file.content.split('\n'); walker.getTypes(file.unitName).forEach(result => { diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 174b311e76..cfc83af76e 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -18,6 +18,8 @@ /// module FourSlash { + ts.disableIncrementalParsing = false; + // Represents a parsed source file with metadata export interface FourSlashFile { // The contents of the file (with markers, etc stripped out) @@ -697,7 +699,7 @@ module FourSlash { for (var i = 0; i < references.length; i++) { var reference = references[i]; - if (reference && reference.fileName === fileName && reference.textSpan.start() === start && reference.textSpan.end() === end) { + if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) { this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.'); } @@ -828,17 +830,17 @@ module FourSlash { } ranges = ranges.sort((r1, r2) => r1.start - r2.start); - references = references.sort((r1, r2) => r1.textSpan.start() - r2.textSpan.start()); + references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start); for (var i = 0, n = ranges.length; i < n; i++) { var reference = references[i]; var range = ranges[i]; - if (reference.textSpan.start() !== range.start || - reference.textSpan.end() !== range.end) { + if (reference.textSpan.start !== range.start || + ts.textSpanEnd(reference.textSpan) !== range.end) { this.raiseError(this.assertionMessage("Rename location", - "[" + reference.textSpan.start() + "," + reference.textSpan.end() + ")", + "[" + reference.textSpan.start + "," + ts.textSpanEnd(reference.textSpan) + ")", "[" + range.start + "," + range.end + ")")); } } @@ -978,10 +980,10 @@ module FourSlash { } var expectedRange = this.getRanges()[0]; - if (renameInfo.triggerSpan.start() !== expectedRange.start || - renameInfo.triggerSpan.end() !== expectedRange.end) { + if (renameInfo.triggerSpan.start !== expectedRange.start || + ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.start + "," + expectedRange.end + "). Got [" + - renameInfo.triggerSpan.start() + "," + renameInfo.triggerSpan.end() + ") instead."); + renameInfo.triggerSpan.start + "," + ts.textSpanEnd(renameInfo.triggerSpan) + ") instead."); } } @@ -1012,7 +1014,7 @@ module FourSlash { private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) { var resultString = "SpanInfo: " + JSON.stringify(spanInfo); if (spanInfo) { - var spanString = this.activeFile.content.substr(spanInfo.start(), spanInfo.length()); + var spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); var spanLineMap = ts.computeLineStarts(spanString); for (var i = 0; i < spanLineMap.length; i++) { if (!i) { @@ -1020,7 +1022,7 @@ module FourSlash { } resultString += prefixString + spanString.substring(spanLineMap[i], spanLineMap[i + 1]); } - resultString += "\n" + prefixString + ":=> (" + this.getLineColStringAtPosition(spanInfo.start()) + ") to (" + this.getLineColStringAtPosition(spanInfo.end()) + ")"; + resultString += "\n" + prefixString + ":=> (" + this.getLineColStringAtPosition(spanInfo.start) + ") to (" + this.getLineColStringAtPosition(ts.textSpanEnd(spanInfo)) + ")"; } return resultString; @@ -1223,16 +1225,24 @@ module FourSlash { var offset = this.currentCaretPosition; var ch = ""; + var checkCadence = (count >> 2) + 1 + for (var i = 0; i < count; i++) { // Make the edit this.languageServiceShimHost.editScript(this.activeFile.fileName, offset, offset + 1, ch); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch); - this.checkPostEditInvariants(); + + if (i % checkCadence === 0) { + this.checkPostEditInvariants(); + } // Handle post-keystroke formatting if (this.enableFormatting) { var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); - offset += this.applyEdits(this.activeFile.fileName, edits, true); + if (edits.length) { + offset += this.applyEdits(this.activeFile.fileName, edits, true); + //this.checkPostEditInvariants(); + } } } @@ -1249,8 +1259,6 @@ module FourSlash { this.languageServiceShimHost.editScript(this.activeFile.fileName, start, start + length, text); this.updateMarkersForEdit(this.activeFile.fileName, start, start + length, text); this.checkPostEditInvariants(); - - this.checkPostEditInvariants(); } public deleteCharBehindMarker(count = 1) { @@ -1258,19 +1266,24 @@ module FourSlash { var offset = this.currentCaretPosition; var ch = ""; + var checkCadence = (count >> 2) + 1 for (var i = 0; i < count; i++) { offset--; // Make the edit this.languageServiceShimHost.editScript(this.activeFile.fileName, offset, offset + 1, ch); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch); - this.checkPostEditInvariants(); + + if (i % checkCadence === 0) { + this.checkPostEditInvariants(); + } // Handle post-keystroke formatting if (this.enableFormatting) { var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); - offset += this.applyEdits(this.activeFile.fileName, edits, true); - this.checkPostEditInvariants(); + if (edits.length) { + offset += this.applyEdits(this.activeFile.fileName, edits, true); + } } } @@ -1295,9 +1308,11 @@ module FourSlash { // Enters lines of text at the current caret position, invoking // language service APIs to mimic Visual Studio's behavior // as much as possible - private typeHighFidelity(text: string, errorCadence = 5) { + private typeHighFidelity(text: string) { var offset = this.currentCaretPosition; var prevChar = ' '; + var checkCadence = (text.length >> 2) + 1; + for (var i = 0; i < text.length; i++) { // Make the edit var ch = text.charAt(i); @@ -1305,7 +1320,6 @@ module FourSlash { this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch); - this.checkPostEditInvariants(); offset++; if (ch === '(' || ch === ',') { @@ -1316,16 +1330,19 @@ module FourSlash { this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset); } - if (i % errorCadence === 0) { - this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); - this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + if (i % checkCadence === 0) { + this.checkPostEditInvariants(); + // this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + // this.languageService.getSemanticDiagnostics(this.activeFile.fileName); } // Handle post-keystroke formatting if (this.enableFormatting) { var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); - offset += this.applyEdits(this.activeFile.fileName, edits, true); - this.checkPostEditInvariants(); + if (edits.length) { + offset += this.applyEdits(this.activeFile.fileName, edits, true); + // this.checkPostEditInvariants(); + } } } @@ -1350,8 +1367,10 @@ module FourSlash { // Handle formatting if (this.enableFormatting) { var edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); - offset += this.applyEdits(this.activeFile.fileName, edits, true); - this.checkPostEditInvariants(); + if (edits.length) { + offset += this.applyEdits(this.activeFile.fileName, edits, true); + this.checkPostEditInvariants(); + } } // Move the caret to wherever we ended up @@ -1365,7 +1384,7 @@ module FourSlash { var incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined); - var incrementalSyntaxDiagnostics = JSON.stringify(Utils.convertDiagnostics(incrementalSourceFile.getSyntacticDiagnostics())); + var incrementalSyntaxDiagnostics = incrementalSourceFile.getSyntacticDiagnostics(); // Check syntactic structure var snapshot = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName); @@ -1373,32 +1392,10 @@ module FourSlash { var referenceSourceFile = ts.createLanguageServiceSourceFile( this.activeFile.fileName, createScriptSnapShot(content), ts.ScriptTarget.Latest, /*version:*/ "0", /*isOpen:*/ false, /*setNodeParents:*/ false); - var referenceSyntaxDiagnostics = JSON.stringify(Utils.convertDiagnostics(referenceSourceFile.getSyntacticDiagnostics())); - - if (incrementalSyntaxDiagnostics !== referenceSyntaxDiagnostics) { - this.raiseError('Mismatched incremental/reference syntactic diagnostics for file ' + this.activeFile.fileName + '.\n=== Incremental diagnostics ===\n' + incrementalSyntaxDiagnostics + '\n=== Reference Diagnostics ===\n' + referenceSyntaxDiagnostics); - } + var referenceSyntaxDiagnostics = referenceSourceFile.getSyntacticDiagnostics(); + Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics); Utils.assertStructuralEquals(incrementalSourceFile, referenceSourceFile); - - //if (this.editValidation !== IncrementalEditValidation.SyntacticOnly) { - // var compiler = new TypeScript.TypeScriptCompiler(); - // for (var i = 0; i < this.testData.files.length; i++) { - // snapshot = this.languageServiceShimHost.getScriptSnapshot(this.testData.files[i].fileName); - // compiler.addFile(this.testData.files[i].fileName, TypeScript.ScriptSnapshot.fromString(snapshot.getText(0, snapshot.getLength())), ts.ByteOrderMark.None, 0, true); - // } - - // compiler.addFile('lib.d.ts', TypeScript.ScriptSnapshot.fromString(Harness.Compiler.libTextMinimal), ts.ByteOrderMark.None, 0, true); - - // for (var i = 0; i < this.testData.files.length; i++) { - // var refSemanticErrs = JSON.stringify(compiler.getSemanticDiagnostics(this.testData.files[i].fileName)); - // var incrSemanticErrs = JSON.stringify(this.languageService.getSemanticDiagnostics(this.testData.files[i].fileName)); - - // if (incrSemanticErrs !== refSemanticErrs) { - // this.raiseError('Mismatched incremental/full semantic errors for file ' + this.testData.files[i].fileName + '\n=== Incremental errors ===\n' + incrSemanticErrs + '\n=== Full Errors ===\n' + refSemanticErrs); - // } - // } - //} } private fixCaretPosition() { @@ -1416,14 +1413,14 @@ module FourSlash { // We get back a set of edits, but langSvc.editScript only accepts one at a time. Use this to keep track // of the incremental offset from each edit to the next. Assumption is that these edit ranges don't overlap var runningOffset = 0; - edits = edits.sort((a, b) => a.span.start() - b.span.start()); + edits = edits.sort((a, b) => a.span.start - b.span.start); // Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters var snapshot = this.languageServiceShimHost.getScriptSnapshot(fileName); var oldContent = snapshot.getText(0, snapshot.getLength()); for (var j = 0; j < edits.length; j++) { - this.languageServiceShimHost.editScript(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText); - this.updateMarkersForEdit(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText); - var change = (edits[j].span.start() - edits[j].span.end()) + edits[j].newText.length; + this.languageServiceShimHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); + this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); + var change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; runningOffset += change; // TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150) // this.languageService.getScriptLexicalStructure(fileName); @@ -1500,7 +1497,7 @@ module FourSlash { var definition = definitions[definitionIndex]; this.openFile(definition.fileName); - this.currentCaretPosition = definition.textSpan.start(); + this.currentCaretPosition = definition.textSpan.start; } public verifyDefinitionLocationExists(negative: boolean) { @@ -1518,6 +1515,14 @@ module FourSlash { } } + public verifyDefinitionsCount(negative: boolean, expectedCount: number) { + var assertFn = negative ? assert.notEqual : assert.equal; + + var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + + assertFn(definitions.length, expectedCount, this.messageAtLastKnownMarker("Definitions Count")); + } + public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) { this.taoInvalidReason = 'verifyDefinititionsInfo NYI'; @@ -1526,10 +1531,10 @@ module FourSlash { var actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; if (negative) { assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name")); - assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name")); + assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name")); } else { assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name")); - assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name")); + assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name")); } } @@ -1621,7 +1626,7 @@ module FourSlash { '\t Actual: undefined'); } - var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.start(), span.end()); + var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.start, ts.textSpanEnd(span)); if (actual !== text) { this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' + '\tExpected: "' + text + '"\n' + @@ -1676,15 +1681,15 @@ module FourSlash { if (expectedSpan) { var expectedLength = expectedSpan.end - expectedSpan.start; - if (expectedSpan.start !== actualSpan.start() || expectedLength !== actualSpan.length()) { + if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) { this.raiseError("verifyClassifications failed - expected span of text to be " + "{start=" + expectedSpan.start + ", length=" + expectedLength + "}, but was " + - "{start=" + actualSpan.start() + ", length=" + actualSpan.length() + "}" + + "{start=" + actualSpan.start + ", length=" + actualSpan.length + "}" + jsonMismatchString()); } } - var actualText = this.activeFile.content.substr(actualSpan.start(), actualSpan.length()); + var actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); if (expectedClassification.text !== actualText) { this.raiseError('verifyClassifications failed - expected classified text to be ' + expectedClassification.text + ', but was ' + @@ -1702,14 +1707,14 @@ module FourSlash { public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) { var actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, - new ts.TextSpan(0, this.activeFile.content.length)); + ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); } public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) { - var actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, - new ts.TextSpan(0, this.activeFile.content.length)); + var actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, + ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); } @@ -1726,8 +1731,8 @@ module FourSlash { for (var i = 0; i < spans.length; i++) { var expectedSpan = spans[i]; var actualSpan = actual[i]; - if (expectedSpan.start !== actualSpan.textSpan.start() || expectedSpan.end !== actualSpan.textSpan.end()) { - this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start() + ',' + actualSpan.textSpan.end() + ')'); + if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) { + this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start + ',' + ts.textSpanEnd(actualSpan.textSpan) + ')'); } } } @@ -1743,10 +1748,10 @@ module FourSlash { for (var i = 0; i < spans.length; i++) { var expectedSpan = spans[i]; var actualComment = actual[i]; - var actualCommentSpan = new ts.TextSpan(actualComment.position, actualComment.message.length); + var actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); - if (expectedSpan.start !== actualCommentSpan.start() || expectedSpan.end !== actualCommentSpan.end()) { - this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start() + ',' + actualCommentSpan.end() + ')'); + if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) { + this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start + ',' + ts.textSpanEnd(actualCommentSpan) + ')'); } } } @@ -1761,12 +1766,12 @@ module FourSlash { } var actualMatchPosition = -1; - if (bracePosition === actual[0].start()) { - actualMatchPosition = actual[1].start(); - } else if (bracePosition === actual[1].start()) { - actualMatchPosition = actual[0].start(); + if (bracePosition === actual[0].start) { + actualMatchPosition = actual[1].start; + } else if (bracePosition === actual[1].start) { + actualMatchPosition = actual[0].start; } else { - this.raiseError('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start() + ',' + actual[0].end() + ') and (' + actual[1].start() + ',' + actual[1].end() + ')'); + this.raiseError('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start + ',' + ts.textSpanEnd(actual[0]) + ') and (' + actual[1].start + ',' + ts.textSpanEnd(actual[1]) + ')'); } if (actualMatchPosition !== expectedMatchPosition) { @@ -2006,7 +2011,7 @@ module FourSlash { for (var i = 0; i < occurances.length; i++) { var occurance = occurances[i]; - if (occurance && occurance.fileName === fileName && occurance.textSpan.start() === start && occurance.textSpan.end() === end) { + if (occurance && occurance.fileName === fileName && occurance.textSpan.start === start && ts.textSpanEnd(occurance.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && occurance.isWriteAccess !== isWriteAccess) { this.raiseError('verifyOccurancesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + occurance.isWriteAccess + ', expected: ' + isWriteAccess + '.'); } @@ -2196,13 +2201,13 @@ module FourSlash { ts.sys.useCaseSensitiveFileNames); // TODO (drosen): We need to enforce checking on these tests. var program = ts.createProgram([Harness.Compiler.fourslashFilename, fileName], { out: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host); - var checker = ts.createTypeChecker(program, /*fullTypeCheckMode*/ true); + var checker = ts.createTypeChecker(program, /*produceDiagnostics*/ true); var errors = program.getDiagnostics().concat(checker.getDiagnostics()); if (errors.length > 0) { throw new Error('Error compiling ' + fileName + ': ' + errors.map(e => e.messageText).join('\r\n')); } - checker.emitFiles(); + program.emitFiles(); result = result || ''; // Might have an empty fourslash file // Compile and execute the test @@ -2590,4 +2595,4 @@ module FourSlash { fileName: fileName }; } -} +} diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 7e8acdab68..ba84a3c9ff 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -16,8 +16,6 @@ /// /// -/// -/// /// /// /// @@ -290,6 +288,29 @@ module Utils { } } + export function assertDiagnosticsEquals(array1: ts.Diagnostic[], array2: ts.Diagnostic[]) { + if (array1 === array2) { + return; + } + + assert(array1, "array1"); + assert(array2, "array2"); + + assert.equal(array1.length, array2.length, "array1.length !== array2.length"); + + for (var i = 0, n = array1.length; i < n; i++) { + var d1 = array1[i]; + var d2 = array2[i]; + + assert.equal(d1.start, d2.start, "d1.start !== d2.start"); + assert.equal(d1.length, d2.length, "d1.length !== d2.length"); + assert.equal(d1.messageText, d2.messageText, "d1.messageText !== d2.messageText"); + assert.equal(d1.category, d2.category, "d1.category !== d2.category"); + assert.equal(d1.code, d2.code, "d1.code !== d2.code"); + assert.equal(d1.isEarly, d2.isEarly, "d1.isEarly !== d2.isEarly"); + } + } + export function assertStructuralEquals(node1: ts.Node, node2: ts.Node) { if (node1 === node2) { return; @@ -886,7 +907,7 @@ module Harness { public compileFiles(inputFiles: { unitName: string; content: string }[], otherFiles: { unitName: string; content: string }[], - onComplete: (result: CompilerResult, checker: ts.TypeChecker) => void, + onComplete: (result: CompilerResult, program: ts.Program) => void, settingsCallback?: (settings: ts.CompilerOptions) => void, options?: ts.CompilerOptions) { @@ -1045,14 +1066,14 @@ module Harness { options.target, useCaseSensitiveFileNames)); - var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true); + var checker = program.getTypeChecker(/*produceDiagnostics*/ true); - var isEmitBlocked = checker.isEmitBlocked(); + var isEmitBlocked = program.isEmitBlocked(); // only emit if there weren't parse errors var emitResult: ts.EmitResult; if (!isEmitBlocked) { - emitResult = checker.emitFiles(); + emitResult = program.emitFiles(); } var errors: HarnessDiagnostic[] = []; @@ -1063,7 +1084,7 @@ module Harness { this.lastErrors = errors; var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult ? emitResult.sourceMaps : undefined); - onComplete(result, checker); + onComplete(result, program); // reset what newline means in case the last test changed it ts.sys.newLine = '\r\n'; @@ -1106,29 +1127,27 @@ module Harness { } function findResultCodeFile(fileName: string) { - var dTsFileName = ts.forEach(result.program.getSourceFiles(), sourceFile => { - if (sourceFile.filename === fileName) { - // Is this file going to be emitted separately - var sourceFileName: string; - if (ts.isExternalModule(sourceFile) || !options.out) { - if (options.outDir) { - var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, result.currentDirectoryForProgram); - sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), ""); - sourceFileName = ts.combinePaths(options.outDir, sourceFilePath); - } - else { - sourceFileName = sourceFile.filename; - } - } - else { - // Goes to single --out file - sourceFileName = options.out; - } - - return ts.removeFileExtension(sourceFileName) + ".d.ts"; + var sourceFile = result.program.getSourceFile(fileName); + assert(sourceFile, "Program has no source file with name '" + fileName + "'"); + // Is this file going to be emitted separately + var sourceFileName: string; + if (ts.isExternalModule(sourceFile) || !options.out) { + if (options.outDir) { + var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, result.currentDirectoryForProgram); + sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), ""); + sourceFileName = ts.combinePaths(options.outDir, sourceFilePath); } - }); + else { + sourceFileName = sourceFile.filename; + } + } + else { + // Goes to single --out file + sourceFileName = options.out; + } + var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts"; + return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined); } @@ -1196,7 +1215,7 @@ module Harness { // Report global errors var globalErrors = diagnostics.filter(err => !err.filename); - globalErrors.forEach(err => outputErrorText(err)); + globalErrors.forEach(outputErrorText); // 'merge' the lines of each input file with any errors associated with it inputFiles.filter(f => f.content !== undefined).forEach(inputFile => { diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 0aa1415cc9..97885bdd20 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -32,8 +32,8 @@ module Harness.LanguageService { // Store edit range + new length of script this.editRanges.push({ length: this.content.length, - textChangeRange: new ts.TextChangeRange( - ts.TextSpan.fromBounds(minChar, limChar), newText.length) + textChangeRange: ts.createTextChangeRange( + ts.createTextSpanFromBounds(minChar, limChar), newText.length) }); // Update version # @@ -43,14 +43,14 @@ module Harness.LanguageService { public getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange { if (startVersion === endVersion) { // No edits! - return ts.TextChangeRange.unchanged; + return ts.unchangedTextChangeRange; } var initialEditRangeIndex = this.editRanges.length - (this.version - startVersion); var lastEditRangeIndex = this.editRanges.length - (this.version - endVersion); var entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex); - return ts.TextChangeRange.collapseChangesAcrossMultipleVersions(entries.map(e => e.textChangeRange)); + return ts.collapseTextChangeRangesAcrossMultipleVersions(entries.map(e => e.textChangeRange)); } } @@ -87,7 +87,7 @@ module Harness.LanguageService { return null; } - return JSON.stringify({ span: { start: range.span().start(), length: range.span().length() }, newLength: range.newLength() }); + return JSON.stringify({ span: { start: range.span.start, length: range.span.length }, newLength: range.newLength }); } } @@ -126,7 +126,7 @@ module Harness.LanguageService { isOpen: boolean, textChangeRange: ts.TextChangeRange ): ts.SourceFile { - return document.update(scriptSnapshot, version, isOpen, textChangeRange); + return ts.updateLanguageServiceSourceFile(document, scriptSnapshot, version, isOpen, textChangeRange); } public releaseDocument(fileName: string, compilationSettings: ts.CompilerOptions): void { @@ -346,9 +346,9 @@ module Harness.LanguageService { for (var i = edits.length - 1; i >= 0; i--) { var edit = edits[i]; - var prefix = result.substring(0, edit.span.start()); + var prefix = result.substring(0, edit.span.start); var middle = edit.newText; - var suffix = result.substring(edit.span.end()); + var suffix = result.substring(ts.textSpanEnd(edit.span)); result = prefix + middle + suffix; } return result; @@ -367,7 +367,7 @@ module Harness.LanguageService { } var temp = mapEdits(edits).sort(function (a, b) { - var result = a.edit.span.start() - b.edit.span.start(); + var result = a.edit.span.start - b.edit.span.start; if (result === 0) result = a.index - b.index; return result; @@ -386,7 +386,7 @@ module Harness.LanguageService { } var nextEdit = temp[next].edit; - var gap = nextEdit.span.start() - currentEdit.span.end(); + var gap = nextEdit.span.start - ts.textSpanEnd(currentEdit.span); // non-overlapping edits if (gap >= 0) { @@ -398,7 +398,7 @@ module Harness.LanguageService { // overlapping edits: for now, we only support ignoring an next edit // entirely contained in the current edit. - if (currentEdit.span.end() >= nextEdit.span.end()) { + if (ts.textSpanEnd(currentEdit.span) >= ts.textSpanEnd(nextEdit.span)) { next++; continue; } diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index 81791c099d..52467fdffd 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -130,9 +130,9 @@ class ProjectRunner extends RunnerBase { var errors = program.getDiagnostics(); var sourceMapData: ts.SourceMapData[] = null; if (!errors.length) { - var checker = program.getTypeChecker(/*fullTypeCheck*/ true); + var checker = program.getTypeChecker(/*produceDiagnostics:*/ true); errors = checker.getDiagnostics(); - var emitResult = checker.emitFiles(); + var emitResult = program.emitFiles(); errors = ts.concatenate(errors, emitResult.diagnostics); sourceMapData = emitResult.sourceMaps; diff --git a/src/harness/rwcRunner.ts b/src/harness/rwcRunner.ts index 8d22b1da1d..085f66f1a3 100644 --- a/src/harness/rwcRunner.ts +++ b/src/harness/rwcRunner.ts @@ -28,12 +28,6 @@ module RWC { var compilerOptions: ts.CompilerOptions; var baselineOpts: Harness.Baseline.BaselineOptions = { Subfolder: 'rwc' }; var baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2]; - // Compile .d.ts files - var declFileCompilationResult: { - declInputFiles: { unitName: string; content: string }[]; - declOtherFiles: { unitName: string; content: string }[]; - declResult: Harness.Compiler.CompilerResult; - }; after(() => { // Mocha holds onto the closure environment of the describe callback even after the test is done. @@ -44,7 +38,6 @@ module RWC { compilerOptions = undefined; baselineOpts = undefined; baseName = undefined; - declFileCompilationResult = undefined; }); it('can compile', () => { @@ -103,11 +96,6 @@ module RWC { } }); - // Baselines - it('Correct compiler generated.d.ts', () => { - declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult, /*settingscallback*/ undefined, compilerOptions); - }); - it('has the expected emitted code', () => { Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => { @@ -152,9 +140,12 @@ module RWC { }, false, baselineOpts); }); - it('has no errors in generated declaration files', () => { + // Ideally, a generated declaration file will have no errors. But we allow generated + // declaration file errors as part of the baseline. + it('has the expected errors in generated declaration files', () => { if (compilerOptions.declaration && !compilerResult.errors.length) { - Harness.Baseline.runBaseline('has no errors in generated declaration files', baseName + '.dts.errors.txt', () => { + Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => { + var declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult, /*settingscallback*/ undefined, compilerOptions); if (declFileCompilationResult.declResult.errors.length === 0) { return null; } diff --git a/src/harness/test262Runner.ts b/src/harness/test262Runner.ts index 7e5bafde22..24be77922f 100644 --- a/src/harness/test262Runner.ts +++ b/src/harness/test262Runner.ts @@ -29,7 +29,7 @@ class Test262BaselineRunner extends RunnerBase { filename: string; compilerResult: Harness.Compiler.CompilerResult; inputFiles: { unitName: string; content: string }[]; - checker: ts.TypeChecker; + program: ts.Program; }; before(() => { @@ -46,12 +46,12 @@ class Test262BaselineRunner extends RunnerBase { filename: testFilename, inputFiles: inputFiles, compilerResult: undefined, - checker: undefined, + program: undefined, }; - Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, checker) => { + Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, program) => { testState.compilerResult = compilerResult; - testState.checker = checker; + testState.program = program; }, /*settingsCallback*/ undefined, Test262BaselineRunner.options); }); @@ -78,13 +78,13 @@ class Test262BaselineRunner extends RunnerBase { }); it('satisfies invariants', () => { - var sourceFile = testState.checker.getProgram().getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename)); + var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename)); Utils.assertInvariants(sourceFile, /*parent:*/ undefined); }); it('has the expected AST',() => { Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt',() => { - var sourceFile = testState.checker.getProgram().getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename)); + var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename)); return Utils.sourceFileToJSON(sourceFile); }, false, Test262BaselineRunner.baselineOptions); }); diff --git a/src/harness/typeWriter.ts b/src/harness/typeWriter.ts index 44888059ff..332173d218 100644 --- a/src/harness/typeWriter.ts +++ b/src/harness/typeWriter.ts @@ -10,11 +10,16 @@ class TypeWriterWalker { results: TypeWriterResult[]; currentSourceFile: ts.SourceFile; - constructor(public checker: ts.TypeChecker) { + private checker: ts.TypeChecker; + + constructor(private program: ts.Program) { + // Consider getting both the diagnostics checker and the non-diagnostics checker to verify + // they are consistent. + this.checker = program.getTypeChecker(/*produceDiagnostics:*/ true); } public getTypes(fileName: string): TypeWriterResult[] { - var sourceFile = this.checker.getProgram().getSourceFile(fileName); + var sourceFile = this.program.getSourceFile(fileName); this.currentSourceFile = sourceFile; this.results = []; this.visitNode(sourceFile); diff --git a/src/services/analyzer.ts b/src/services/analyzer.ts index f181d54480..dbf91ed3ff 100644 --- a/src/services/analyzer.ts +++ b/src/services/analyzer.ts @@ -78,7 +78,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr var processedFiles: ProcessedFile[] = []; for (var i = 0, len = sourceFiles.length; i < len; ++i) { var f = sourceFiles[i]; - var fileSpan = new ts.TextSpan(0, f.text.length); + var fileSpan = ts.createTextSpan(0, f.text.length); var syntacticClassifications = ls.getSyntacticClassifications(f.filename, fileSpan); var convertedSyntactic = convertClassifications(syntacticClassifications, f, /*addHyperlinks*/ true); @@ -235,8 +235,8 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr } var classification = c.classificationType; - var start = c.textSpan.start(); - var length = c.textSpan.length(); + var start = c.textSpan.start; + var length = c.textSpan.length; var hyperlinks: Hyperlink[]; var definitionSymbolId: string; @@ -305,7 +305,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr hyperlinks = []; } - var defStart = d.textSpan.start(); + var defStart = d.textSpan.start; var defFile = program.getSourceFile(d.fileName); var token = ts.getTouchingToken(defFile, defStart, /*includeItemAtEndPosition*/ undefined); @@ -321,7 +321,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr } var link: Hyperlink = { sourceFile: d.fileName, - start: d.textSpan.start(), + start: d.textSpan.start, symbolId: makeSymbolId(d.fileName, defStart) }; hyperlinks.push(link); diff --git a/src/services/breakpoints.ts b/src/services/breakpoints.ts index 3a2cc2ad7e..e49d035559 100644 --- a/src/services/breakpoints.ts +++ b/src/services/breakpoints.ts @@ -38,7 +38,7 @@ module ts.BreakpointResolver { return spanInNode(tokenAtLocation); function textSpan(startNode: Node, endNode?: Node) { - return TextSpan.fromBounds(startNode.getStart(), (endNode || startNode).getEnd()); + return createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd()); } function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan { @@ -83,7 +83,7 @@ module ts.BreakpointResolver { switch (node.kind) { case SyntaxKind.VariableStatement: // Span on first variable declaration - return spanInVariableDeclaration((node).declarations[0]); + return spanInVariableDeclaration((node).declarationList.declarations[0]); case SyntaxKind.VariableDeclaration: case SyntaxKind.PropertyDeclaration: @@ -108,8 +108,6 @@ module ts.BreakpointResolver { return spanInFunctionBlock(node); } // Fall through - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return spanInBlock(node); @@ -263,16 +261,16 @@ module ts.BreakpointResolver { function spanInVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan { // If declaration of for in statement, just set the span in parent - if (variableDeclaration.parent.kind === SyntaxKind.ForInStatement) { - return spanInNode(variableDeclaration.parent); + if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) { + return spanInNode(variableDeclaration.parent.parent); } - var isParentVariableStatement = variableDeclaration.parent.kind === SyntaxKind.VariableStatement; - var isDeclarationOfForStatement = variableDeclaration.parent.kind === SyntaxKind.ForStatement && contains((variableDeclaration.parent).declarations, variableDeclaration); + var isParentVariableStatement = variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement; + var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement && contains(((variableDeclaration.parent.parent).initializer).declarations, variableDeclaration); var declarations = isParentVariableStatement - ? (variableDeclaration.parent).declarations + ? (variableDeclaration.parent.parent).declarationList.declarations : isDeclarationOfForStatement - ? (variableDeclaration.parent).declarations + ? ((variableDeclaration.parent.parent).initializer).declarations : undefined; // Breakpoint is possible in variableDeclaration only if there is initialization @@ -376,12 +374,18 @@ module ts.BreakpointResolver { } function spanInForStatement(forStatement: ForStatement): TextSpan { - if (forStatement.declarations) { - return spanInNode(forStatement.declarations[0]); - } if (forStatement.initializer) { - return spanInNode(forStatement.initializer); + if (forStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { + var variableDeclarationList = forStatement.initializer; + if (variableDeclarationList.declarations.length > 0) { + return spanInNode(variableDeclarationList.declarations[0]); + } + } + else { + return spanInNode(forStatement.initializer); + } } + if (forStatement.condition) { return textSpan(forStatement.condition); } @@ -429,9 +433,7 @@ module ts.BreakpointResolver { } // fall through. - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: return spanInNode((node.parent).statements[(node.parent).statements.length - 1]);; case SyntaxKind.SwitchStatement: diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index 823a5ff4e0..b5edf776d5 100644 --- a/src/services/formatting/formatting.ts +++ b/src/services/formatting/formatting.ts @@ -154,8 +154,6 @@ module ts.formatting { return body && body.kind === SyntaxKind.Block && rangeContainsRange((body).statements, node); case SyntaxKind.SourceFile: case SyntaxKind.Block: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return rangeContainsRange((parent).statements, node); case SyntaxKind.CatchClause: @@ -875,7 +873,7 @@ module ts.formatting { } function newTextChange(start: number, len: number, newText: string): TextChange { - return { span: new TextSpan(start, len), newText } + return { span: createTextSpan(start, len), newText } } function recordDelete(start: number, len: number) { @@ -939,9 +937,6 @@ module ts.formatting { function isSomeBlock(kind: SyntaxKind): boolean { switch (kind) { case SyntaxKind.Block: - case SyntaxKind.Block: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return true; } diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index bea74e529f..9fcc787030 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -525,8 +525,6 @@ module ts.formatting { case SyntaxKind.Block: case SyntaxKind.SwitchStatement: case SyntaxKind.ObjectLiteralExpression: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: return true; } @@ -580,9 +578,7 @@ module ts.formatting { case SyntaxKind.ModuleDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.Block: - case SyntaxKind.TryBlock: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: case SyntaxKind.SwitchStatement: return true; @@ -603,7 +599,6 @@ module ts.formatting { // TODO // case SyntaxKind.ElseClause: case SyntaxKind.CatchClause: - case SyntaxKind.FinallyBlock: return true; default: diff --git a/src/services/formatting/smartIndenter.ts b/src/services/formatting/smartIndenter.ts index f6f5031d60..ce240a9516 100644 --- a/src/services/formatting/smartIndenter.ts +++ b/src/services/formatting/smartIndenter.ts @@ -327,8 +327,6 @@ module ts.formatting { case SyntaxKind.EnumDeclaration: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.Block: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.TypeLiteral: @@ -404,7 +402,6 @@ module ts.formatting { case SyntaxKind.EnumDeclaration: case SyntaxKind.ObjectLiteralExpression: case SyntaxKind.Block: - case SyntaxKind.FinallyBlock: case SyntaxKind.ModuleBlock: case SyntaxKind.SwitchStatement: return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile); diff --git a/src/services/formatting/tokenRange.ts b/src/services/formatting/tokenRange.ts index 8d421140e6..61fcb26dc9 100644 --- a/src/services/formatting/tokenRange.ts +++ b/src/services/formatting/tokenRange.ts @@ -125,10 +125,8 @@ module ts.formatting { static Any: TokenRange = TokenRange.AllTokens(); static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia])); static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); - static Operators = TokenRange.FromRange(SyntaxKind.FirstOperator, SyntaxKind.LastOperator); static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword]); - static ReservedKeywords = TokenRange.FromRange(SyntaxKind.FirstFutureReservedWord, SyntaxKind.LastFutureReservedWord); static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index 29b2db72fc..9051ee8039 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -44,7 +44,7 @@ module ts.NavigationBar { function visit(node: Node) { switch (node.kind) { case SyntaxKind.VariableStatement: - forEach((node).declarations, visit); + forEach((node).declarationList.declarations, visit); break; case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: @@ -462,8 +462,8 @@ module ts.NavigationBar { function getNodeSpan(node: Node) { return node.kind === SyntaxKind.SourceFile - ? TextSpan.fromBounds(node.getFullStart(), node.getEnd()) - : TextSpan.fromBounds(node.getStart(), node.getEnd()); + ? createTextSpanFromBounds(node.getFullStart(), node.getEnd()) + : createTextSpanFromBounds(node.getStart(), node.getEnd()); } function getTextOfNode(node: Node): string { diff --git a/src/services/outliningElementsCollector.ts b/src/services/outliningElementsCollector.ts index 5af69cd362..0b39f54ca2 100644 --- a/src/services/outliningElementsCollector.ts +++ b/src/services/outliningElementsCollector.ts @@ -22,8 +22,8 @@ module ts { function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) { if (hintSpanNode && startElement && endElement) { var span: OutliningSpan = { - textSpan: TextSpan.fromBounds(startElement.pos, endElement.end), - hintSpan: TextSpan.fromBounds(hintSpanNode.getStart(), hintSpanNode.end), + textSpan: createTextSpanFromBounds(startElement.pos, endElement.end), + hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end), bannerText: collapseText, autoCollapse: autoCollapse }; @@ -68,25 +68,41 @@ module ts { parent.kind === SyntaxKind.CatchClause) { addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + break; } - else { - // Block was a standalone block. In this case we want to only collapse - // the span of the block, independent of any parent span. - var span = TextSpan.fromBounds(n.getStart(), n.end); - elements.push({ - textSpan: span, - hintSpan: span, - bannerText: collapseText, - autoCollapse: autoCollapse(n) - }); + + if (parent.kind === SyntaxKind.TryStatement) { + // Could be the try-block, or the finally-block. + var tryStatement = parent; + if (tryStatement.tryBlock === n) { + addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); + break; + } + else if (tryStatement.finallyBlock === n) { + var finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); + if (finallyKeyword) { + addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); + break; + } + } + + // fall through. } + + // Block was a standalone block. In this case we want to only collapse + // the span of the block, independent of any parent span. + var span = createTextSpanFromBounds(n.getStart(), n.end); + elements.push({ + textSpan: span, + hintSpan: span, + bannerText: collapseText, + autoCollapse: autoCollapse(n) + }); break; } // Fallthrough. case SyntaxKind.ModuleBlock: - case SyntaxKind.TryBlock: - case SyntaxKind.FinallyBlock: var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); diff --git a/src/services/services.ts b/src/services/services.ts index 67c55a8c82..1618fb6e27 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1,8 +1,4 @@ -/// -/// -/// -/// -/// +/// /// /// @@ -13,7 +9,6 @@ /// module ts { - export var servicesVersion = "0.4" export interface Node { @@ -63,10 +58,9 @@ module ts { export interface SourceFile { isOpen: boolean; version: string; + scriptSnapshot: IScriptSnapshot; - getScriptSnapshot(): IScriptSnapshot; getNamedDeclarations(): Declaration[]; - update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile; } /** @@ -365,7 +359,7 @@ module ts { // Get the cleaned js doc comment text from the declaration ts.forEach(getJsDocCommentTextRange( - declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => { + declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => { var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); if (cleanedJsDocComment) { jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); @@ -726,6 +720,7 @@ module ts { public _declarationBrand: any; public filename: string; public text: string; + public scriptSnapshot: IScriptSnapshot; public statements: NodeArray; public endOfFileToken: Node; @@ -736,6 +731,7 @@ module ts { public getPositionFromLineAndCharacter: (line: number, character: number) => number; public getLineStarts: () => number[]; public getSyntacticDiagnostics: () => Diagnostic[]; + public update: (newText: string, textChangeRange: TextChangeRange) => SourceFile; public amdDependencies: string[]; public amdModuleName: string; @@ -755,13 +751,8 @@ module ts { public languageVersion: ScriptTarget; public identifiers: Map; - private scriptSnapshot: IScriptSnapshot; private namedDeclarations: Declaration[]; - public getScriptSnapshot(): IScriptSnapshot { - return this.scriptSnapshot; - } - public getNamedDeclarations() { if (!this.namedDeclarations) { var sourceFile = this; @@ -810,6 +801,7 @@ module ts { // fall through case SyntaxKind.Constructor: case SyntaxKind.VariableStatement: + case SyntaxKind.VariableDeclarationList: case SyntaxKind.ObjectBindingPattern: case SyntaxKind.ArrayBindingPattern: case SyntaxKind.ModuleBlock: @@ -847,35 +839,6 @@ module ts { return this.namedDeclarations; } - - public update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile { - if (textChangeRange && Debug.shouldAssert(AssertionLevel.Normal)) { - var oldText = this.scriptSnapshot; - var newText = scriptSnapshot; - - Debug.assert((oldText.getLength() - textChangeRange.span().length() + textChangeRange.newLength()) === newText.getLength()); - - if (Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - var oldTextPrefix = oldText.getText(0, textChangeRange.span().start()); - var newTextPrefix = newText.getText(0, textChangeRange.span().start()); - Debug.assert(oldTextPrefix === newTextPrefix); - - var oldTextSuffix = oldText.getText(textChangeRange.span().end(), oldText.getLength()); - var newTextSuffix = newText.getText(textChangeRange.newSpan().end(), newText.getLength()); - Debug.assert(oldTextSuffix === newTextSuffix); - } - } - - return createLanguageServiceSourceFile(this.filename, scriptSnapshot, this.languageVersion, version, isOpen, /*setNodeParents:*/ true); - } - - public static createSourceFileObject(filename: string, scriptSnapshot: IScriptSnapshot, languageVersion: ScriptTarget, version: string, isOpen: boolean, setParentNodes: boolean) { - var newSourceFile = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), languageVersion, setParentNodes); - newSourceFile.version = version; - newSourceFile.isOpen = isOpen; - newSourceFile.scriptSnapshot = scriptSnapshot; - return newSourceFile; - } } export interface Logger { @@ -949,301 +912,6 @@ module ts { dispose(): void; } - - export class TextSpan { - private _start: number; - private _length: number; - - /** - * Creates a TextSpan instance beginning with the position Start and having the Length - * specified with length. - */ - constructor(start: number, length: number) { - Debug.assert(start >= 0, "start"); - Debug.assert(length >= 0, "length"); - - this._start = start; - this._length = length; - } - - public toJSON(key: any): any { - return { start: this._start, length: this._length }; - } - - public start(): number { - return this._start; - } - - public length(): number { - return this._length; - } - - public end(): number { - return this._start + this._length; - } - - public isEmpty(): boolean { - return this._length === 0; - } - - /** - * Determines whether the position lies within the span. Returns true if the position is greater than or equal to Start and strictly less - * than End, otherwise false. - * @param position The position to check. - */ - public containsPosition(position: number): boolean { - return position >= this._start && position < this.end(); - } - - /** - * Determines whether span falls completely within this span. Returns true if the specified span falls completely within this span, otherwise false. - * @param span The span to check. - */ - public containsTextSpan(span: TextSpan): boolean { - return span._start >= this._start && span.end() <= this.end(); - } - - /** - * Determines whether the given span overlaps this span. Two spans are considered to overlap - * if they have positions in common and neither is empty. Empty spans do not overlap with any - * other span. Returns true if the spans overlap, false otherwise. - * @param span The span to check. - */ - public overlapsWith(span: TextSpan): boolean { - var overlapStart = Math.max(this._start, span._start); - var overlapEnd = Math.min(this.end(), span.end()); - - return overlapStart < overlapEnd; - } - - /** - * Returns the overlap with the given span, or undefined if there is no overlap. - * @param span The span to check. - */ - public overlap(span: TextSpan): TextSpan { - var overlapStart = Math.max(this._start, span._start); - var overlapEnd = Math.min(this.end(), span.end()); - - if (overlapStart < overlapEnd) { - return TextSpan.fromBounds(overlapStart, overlapEnd); - } - - return undefined; - } - - /** - * Determines whether span intersects this span. Two spans are considered to - * intersect if they have positions in common or the end of one span - * coincides with the start of the other span. Returns true if the spans intersect, false otherwise. - * @param The span to check. - */ - public intersectsWithTextSpan(span: TextSpan): boolean { - return span._start <= this.end() && span.end() >= this._start; - } - - public intersectsWith(start: number, length: number): boolean { - var end = start + length; - return start <= this.end() && end >= this._start; - } - - /** - * Determines whether the given position intersects this span. - * A position is considered to intersect if it is between the start and - * end positions (inclusive) of this span. Returns true if the position intersects, false otherwise. - * @param position The position to check. - */ - public intersectsWithPosition(position: number): boolean { - return position <= this.end() && position >= this._start; - } - - /** - * Returns the intersection with the given span, or undefined if there is no intersection. - * @param span The span to check. - */ - public intersection(span: TextSpan): TextSpan { - var intersectStart = Math.max(this._start, span._start); - var intersectEnd = Math.min(this.end(), span.end()); - - if (intersectStart <= intersectEnd) { - return TextSpan.fromBounds(intersectStart, intersectEnd); - } - - return undefined; - } - - /** - * Creates a new TextSpan from the given start and end positions - * as opposed to a position and length. - */ - public static fromBounds(start: number, end: number): TextSpan { - Debug.assert(start >= 0); - Debug.assert(end - start >= 0); - return new TextSpan(start, end - start); - } - } - - export class TextChangeRange { - public static unchanged = new TextChangeRange(new TextSpan(0, 0), 0); - - private _span: TextSpan; - private _newLength: number; - - /** - * Initializes a new instance of TextChangeRange. - */ - constructor(span: TextSpan, newLength: number) { - Debug.assert(newLength >= 0, "newLength"); - - this._span = span; - this._newLength = newLength; - } - - /** - * The span of text before the edit which is being changed - */ - public span(): TextSpan { - return this._span; - } - - /** - * Width of the span after the edit. A 0 here would represent a delete - */ - public newLength(): number { - return this._newLength; - } - - public newSpan(): TextSpan { - return new TextSpan(this.span().start(), this.newLength()); - } - - public isUnchanged(): boolean { - return this.span().isEmpty() && this.newLength() === 0; - } - - /** - * Called to merge all the changes that occurred across several versions of a script snapshot - * into a single change. i.e. if a user keeps making successive edits to a script we will - * have a text change from V1 to V2, V2 to V3, ..., Vn. - * - * This function will then merge those changes into a single change range valid between V1 and - * Vn. - */ - public static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange { - if (changes.length === 0) { - return TextChangeRange.unchanged; - } - - if (changes.length === 1) { - return changes[0]; - } - - // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } - // as it makes things much easier to reason about. - var change0 = changes[0]; - - var oldStartN = change0.span().start(); - var oldEndN = change0.span().end(); - var newEndN = oldStartN + change0.newLength(); - - for (var i = 1; i < changes.length; i++) { - var nextChange = changes[i]; - - // Consider the following case: - // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting - // at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }. - // i.e. the span starting at 30 with length 30 is increased to length 40. - // - // 0 10 20 30 40 50 60 70 80 90 100 - // ------------------------------------------------------------------------------------------------------- - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- - // ------------------------------------------------------------------------------------------------------- - // | \ - // | \ - // T2 | \ - // | \ - // | \ - // ------------------------------------------------------------------------------------------------------- - // - // Merging these turns out to not be too difficult. First, determining the new start of the change is trivial - // it's just the min of the old and new starts. i.e.: - // - // 0 10 20 30 40 50 60 70 80 90 100 - // ------------------------------------------------------------*------------------------------------------ - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- - // ----------------------------------------$-------------------$------------------------------------------ - // . | \ - // . | \ - // T2 . | \ - // . | \ - // . | \ - // ----------------------------------------------------------------------*-------------------------------- - // - // (Note the dots represent the newly inferrred start. - // Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the - // absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see - // which if the two $'s precedes the other, and we move that one forward until they line up. in this case that - // means: - // - // 0 10 20 30 40 50 60 70 80 90 100 - // --------------------------------------------------------------------------------*---------------------- - // | / - // | /---- - // T1 | /---- - // | /---- - // | /---- - // ------------------------------------------------------------$------------------------------------------ - // . | \ - // . | \ - // T2 . | \ - // . | \ - // . | \ - // ----------------------------------------------------------------------*-------------------------------- - // - // In other words (in this case), we're recognizing that the second edit happened after where the first edit - // ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started - // that's the same as if we started at char 80 instead of 60. - // - // As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter - // than pusing the first edit forward to match the second, we'll push the second edit forward to match the - // first. - // - // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange - // semantics: { { start: 10, length: 70 }, newLength: 60 } - // - // The math then works out as follows. - // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the - // final result like so: - // - // { - // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) - // } - - var oldStart1 = oldStartN; - var oldEnd1 = oldEndN; - var newEnd1 = newEndN; - - var oldStart2 = nextChange.span().start(); - var oldEnd2 = nextChange.span().end(); - var newEnd2 = oldStart2 + nextChange.newLength(); - - oldStartN = Math.min(oldStart1, oldStart2); - oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); - newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)); - } - - return new TextChangeRange(TextSpan.fromBounds(oldStartN, oldEndN), /*newLength: */newEndN - oldStartN); - } - } export interface ClassifiedSpan { textSpan: TextSpan; @@ -1804,7 +1472,7 @@ module ts { public getChangeRange(filename: string, lastKnownVersion: string, oldScriptSnapshot: IScriptSnapshot): TextChangeRange { var currentVersion = this.getVersion(filename); if (lastKnownVersion === currentVersion) { - return TextChangeRange.unchanged; // "No changes" + return unchangedTextChangeRange; // "No changes" } var scriptSnapshot = this.getScriptSnapshot(filename); @@ -1837,25 +1505,17 @@ module ts { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); var start = new Date().getTime(); - sourceFile = createLanguageServiceSourceFile(filename, scriptSnapshot, getDefaultCompilerOptions().target, version, /*isOpen*/ true, /*setNodeParents:*/ true); + sourceFile = createLanguageServiceSourceFile(filename, scriptSnapshot, ScriptTarget.Latest, version, /*isOpen*/ true, /*setNodeParents;*/ true); this.host.log("SyntaxTreeCache.Initialize: createSourceFile: " + (new Date().getTime() - start)); - - var start = new Date().getTime(); - this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } else if (this.currentFileVersion !== version) { var scriptSnapshot = this.hostCache.getScriptSnapshot(filename); - var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.getScriptSnapshot()); + var editRange = this.hostCache.getChangeRange(filename, this.currentFileVersion, this.currentSourceFile.scriptSnapshot); var start = new Date().getTime(); - sourceFile = !editRange - ? createLanguageServiceSourceFile(filename, scriptSnapshot, getDefaultCompilerOptions().target, version, /*isOpen*/ true, /*setNodeParents:*/ true) - : this.currentSourceFile.update(scriptSnapshot, version, /*isOpen*/ true, editRange); + sourceFile = updateLanguageServiceSourceFile(this.currentSourceFile, scriptSnapshot, version, /*isOpen*/ true, editRange); this.host.log("SyntaxTreeCache.Initialize: updateSourceFile: " + (new Date().getTime() - start)); - - var start = new Date().getTime(); - this.host.log("SyntaxTreeCache.Initialize: fixupParentRefs : " + (new Date().getTime() - start)); } if (sourceFile) { @@ -1872,12 +1532,57 @@ module ts { } public getCurrentScriptSnapshot(filename: string): IScriptSnapshot { - return this.getCurrentSourceFile(filename).getScriptSnapshot(); + return this.getCurrentSourceFile(filename).scriptSnapshot; } } + function setSourceFileFields(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean) { + sourceFile.version = version; + sourceFile.isOpen = isOpen; + sourceFile.scriptSnapshot = scriptSnapshot; + } + export function createLanguageServiceSourceFile(filename: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, isOpen: boolean, setNodeParents: boolean): SourceFile { - return SourceFileObject.createSourceFileObject(filename, scriptSnapshot, scriptTarget, version, isOpen, setNodeParents); + var sourceFile = createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); + setSourceFileFields(sourceFile, scriptSnapshot, version, isOpen); + return sourceFile; + } + + export var disableIncrementalParsing = false; + + export function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile { + if (textChangeRange && Debug.shouldAssert(AssertionLevel.Normal)) { + var oldText = sourceFile.scriptSnapshot; + var newText = scriptSnapshot; + + Debug.assert((oldText.getLength() - textChangeRange.span.length + textChangeRange.newLength) === newText.getLength()); + + if (Debug.shouldAssert(AssertionLevel.VeryAggressive)) { + var oldTextPrefix = oldText.getText(0, textChangeRange.span.start); + var newTextPrefix = newText.getText(0, textChangeRange.span.start); + Debug.assert(oldTextPrefix === newTextPrefix); + + var oldTextSuffix = oldText.getText(textSpanEnd(textChangeRange.span), oldText.getLength()); + var newTextSuffix = newText.getText(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.getLength()); + Debug.assert(oldTextSuffix === newTextSuffix); + } + } + + // If we were given a text change range, and our version or open-ness changed, then + // incrementally parse this file. + if (textChangeRange) { + if (version !== sourceFile.version || isOpen != sourceFile.isOpen) { + // Once incremental parsing is ready, then just call into this function. + if (!disableIncrementalParsing) { + var newSourceFile = sourceFile.update(scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange); + setSourceFileFields(newSourceFile, scriptSnapshot, version, isOpen); + return newSourceFile; + } + } + } + + // Otherwise, just create a new source file. + return createLanguageServiceSourceFile(sourceFile.filename, scriptSnapshot, sourceFile.languageVersion, version, isOpen, /*setNodeParents:*/ true); } export function createDocumentRegistry(): DocumentRegistry { @@ -1955,11 +1660,7 @@ module ts { var entry = lookUp(bucket, filename); Debug.assert(entry !== undefined); - if (entry.sourceFile.isOpen === isOpen && entry.sourceFile.version === version) { - return entry.sourceFile; - } - - entry.sourceFile = entry.sourceFile.update(scriptSnapshot, version, isOpen, textChangeRange); + entry.sourceFile = updateLanguageServiceSourceFile(entry.sourceFile, scriptSnapshot, version, isOpen, textChangeRange); return entry.sourceFile; } @@ -2219,16 +1920,11 @@ module ts { // this checker is used to answer all LS questions except errors var typeInfoResolver: TypeChecker; - // the sole purpose of this checker is to return semantic diagnostics - // creation is deferred - use getFullTypeCheckChecker to get instance - var fullTypeCheckChecker_doNotAccessDirectly: TypeChecker; - var useCaseSensitivefilenames = false; var sourceFilesByName: Map = {}; var documentRegistry = documentRegistry; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var activeCompletionSession: CompletionSession; // The current active completion session, used to get the completion entry details - var writer: (filename: string, data: string, writeByteOrderMark: boolean) => void = undefined; // Check if the localized messages json is set, otherwise query the host for it if (!localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -2243,8 +1939,8 @@ module ts { return lookUp(sourceFilesByName, getCanonicalFileName(filename)); } - function getFullTypeCheckChecker() { - return fullTypeCheckChecker_doNotAccessDirectly || (fullTypeCheckChecker_doNotAccessDirectly = program.getTypeChecker(/*fullTypeCheck*/ true)); + function getDiagnosticsProducingTypeChecker() { + return program.getTypeChecker(/*produceDiagnostics:*/ true); } function getRuleProvider(options: FormatCodeOptions) { @@ -2271,7 +1967,6 @@ module ts { return host.getDefaultLibFilename(options); }, writeFile: (filename, data, writeByteOrderMark) => { - writer(filename, data, writeByteOrderMark); }, getCurrentDirectory: (): string => { return host.getCurrentDirectory(); @@ -2369,7 +2064,7 @@ module ts { // new text buffer). var textChangeRange: TextChangeRange = null; if (sourceFile.isOpen && isOpen) { - textChangeRange = hostCache.getChangeRange(filename, sourceFile.version, sourceFile.getScriptSnapshot()); + textChangeRange = hostCache.getChangeRange(filename, sourceFile.version, sourceFile.scriptSnapshot); } sourceFile = documentRegistry.updateDocument(sourceFile, filename, compilationSettings, scriptSnapshot, version, isOpen, textChangeRange); @@ -2384,8 +2079,7 @@ module ts { // Now create a new compiler program = createProgram(hostfilenames, compilationSettings, createCompilerHost()); - typeInfoResolver = program.getTypeChecker(/*fullTypeCheckMode*/ false); - fullTypeCheckChecker_doNotAccessDirectly = undefined; + typeInfoResolver = program.getTypeChecker(/*produceDiagnostics*/ false); } /** @@ -2395,8 +2089,7 @@ module ts { */ function cleanupSemanticCache(): void { if (program) { - typeInfoResolver = program.getTypeChecker(/*fullTypeCheckMode*/ false); - fullTypeCheckChecker_doNotAccessDirectly = undefined; + typeInfoResolver = program.getTypeChecker(/*produceDiagnostics*/ false); } } @@ -2425,7 +2118,7 @@ module ts { filename = normalizeSlashes(filename) var compilerOptions = program.getCompilerOptions(); - var checker = getFullTypeCheckChecker(); + var checker = getDiagnosticsProducingTypeChecker(); var targetSourceFile = getSourceFile(filename); // Only perform the action per file regardless of '-out' flag as LanguageServiceHost is expected to call this function per file. @@ -2434,7 +2127,7 @@ module ts { var allDiagnostics = checker.getDiagnostics(targetSourceFile); if (compilerOptions.declaration) { // If '-d' is enabled, check for emitter error. One example of emitter error is export class implements non-export interface - allDiagnostics = allDiagnostics.concat(checker.getDeclarationDiagnostics(targetSourceFile)); + allDiagnostics = allDiagnostics.concat(program.getDeclarationDiagnostics(targetSourceFile)); } return allDiagnostics } @@ -2462,7 +2155,7 @@ module ts { // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. displayName = displayName.substring(1, displayName.length - 1); } - + var isValid = isIdentifierStart(displayName.charCodeAt(0), target); for (var i = 1, n = displayName.length; isValid && i < n; i++) { isValid = isIdentifierPart(displayName.charCodeAt(i), target); @@ -2513,7 +2206,7 @@ module ts { // Completion not allowed inside comments, bail out if this is the case var insideComment = isInsideComment(sourceFile, currentToken, position); host.log("getCompletionsAtPosition: Is inside comment: " + (new Date().getTime() - start)); - + if (insideComment) { host.log("Returning an empty list because completion was inside a comment."); return undefined; @@ -2732,6 +2425,7 @@ module ts { switch (previousToken.kind) { case SyntaxKind.CommaToken: return containingNodeKind === SyntaxKind.VariableDeclaration || + containingNodeKind === SyntaxKind.VariableDeclarationList || containingNodeKind === SyntaxKind.VariableStatement || containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { foo, | isFunction(containingNodeKind); @@ -2891,7 +2585,7 @@ module ts { } // TODO(drosen): use contextual SemanticMeaning. - function getSymbolKind(symbol: Symbol, typeResolver: TypeChecker, location?: Node): string { + function getSymbolKind(symbol: Symbol, typeResolver: TypeChecker, location: Node): string { var flags = symbol.getFlags(); if (flags & SymbolFlags.Class) return ScriptElementKind.classElement; @@ -2899,7 +2593,7 @@ module ts { if (flags & SymbolFlags.TypeAlias) return ScriptElementKind.typeElement; if (flags & SymbolFlags.Interface) return ScriptElementKind.interfaceElement; if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement; - + var result = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, flags, typeResolver, location); if (result === ScriptElementKind.unknown) { if (flags & SymbolFlags.TypeParameter) return ScriptElementKind.typeParameterElement; @@ -2925,7 +2619,7 @@ module ts { else if (symbol.valueDeclaration && isConst(symbol.valueDeclaration)) { return ScriptElementKind.constElement; } - else if (forEach(symbol.declarations, declaration => isLet(declaration))) { + else if (forEach(symbol.declarations, isLet)) { return ScriptElementKind.letElement; } return isLocalVariableOrFunction(symbol) ? ScriptElementKind.localVariableElement : ScriptElementKind.variableElement; @@ -2962,7 +2656,7 @@ module ts { return ScriptElementKind.unknown; } - + function getTypeKind(type: Type): string { var flags = type.getFlags(); @@ -2983,11 +2677,12 @@ module ts { case SyntaxKind.InterfaceDeclaration: return ScriptElementKind.interfaceElement; case SyntaxKind.TypeAliasDeclaration: return ScriptElementKind.typeElement; case SyntaxKind.EnumDeclaration: return ScriptElementKind.enumElement; - case SyntaxKind.VariableDeclaration: return isConst(node) - ? ScriptElementKind.constElement - : node.flags & NodeFlags.Let - ? ScriptElementKind.letElement - : ScriptElementKind.variableElement; + case SyntaxKind.VariableDeclaration: + return isConst(node) + ? ScriptElementKind.constElement + : isLet(node) + ? ScriptElementKind.letElement + : ScriptElementKind.variableElement; case SyntaxKind.FunctionDeclaration: return ScriptElementKind.functionElement; case SyntaxKind.GetAccessor: return ScriptElementKind.memberGetAccessorElement; case SyntaxKind.SetAccessor: return ScriptElementKind.memberSetAccessorElement; @@ -3035,7 +2730,7 @@ module ts { if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) { var right = (location.parent).name; // Either the location is on the right of a property access, or on the left and the right is missing - if (right === location || (right && right.getFullWidth() === 0)){ + if (right === location || (right && right.getFullWidth() === 0)) { location = location.parent; } } @@ -3168,7 +2863,7 @@ module ts { } if (symbolFlags & SymbolFlags.Enum) { addNewLineIfDisplayPartsExist(); - if (forEach(symbol.declarations, declaration => isConstEnumDeclaration(declaration))) { + if (forEach(symbol.declarations, isConstEnumDeclaration)) { displayParts.push(keywordPart(SyntaxKind.ConstKeyword)); displayParts.push(spacePart()); } @@ -3279,7 +2974,7 @@ module ts { symbolFlags & SymbolFlags.Method || symbolFlags & SymbolFlags.Constructor || symbolFlags & SymbolFlags.Signature || - symbolFlags & SymbolFlags.Accessor || + symbolFlags & SymbolFlags.Accessor || symbolKind === ScriptElementKind.memberFunctionElement) { var allSignatures = type.getCallSignatures(); addSignatureDisplayParts(allSignatures[0], allSignatures); @@ -3367,7 +3062,7 @@ module ts { return { kind: ScriptElementKind.unknown, kindModifiers: ScriptElementKindModifier.none, - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: createTextSpan(node.getStart(), node.getWidth()), displayParts: typeToDisplayParts(typeInfoResolver, type, getContainerNode(node)), documentation: type.symbol ? type.symbol.getDocumentationComment() : undefined }; @@ -3381,7 +3076,7 @@ module ts { return { kind: displayPartsDocumentationsAndKind.symbolKind, kindModifiers: getSymbolModifiers(symbol), - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: createTextSpan(node.getStart(), node.getWidth()), displayParts: displayPartsDocumentationsAndKind.displayParts, documentation: displayPartsDocumentationsAndKind.documentation }; @@ -3389,10 +3084,87 @@ module ts { /// Goto definition function getDefinitionAtPosition(filename: string, position: number): DefinitionInfo[] { + synchronizeHostData(); + + filename = normalizeSlashes(filename); + var sourceFile = getSourceFile(filename); + + var node = getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; + } + + // Labels + if (isJumpStatementTarget(node)) { + var labelName = (node).text; + var label = getTargetLabel((node.parent), (node).text); + return label ? [getDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; + } + + /// Triple slash reference comments + var comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined); + if (comment) { + var referenceFile = tryResolveScriptReference(program, sourceFile, comment); + if (referenceFile) { + return [{ + fileName: referenceFile.filename, + textSpan: createTextSpanFromBounds(0, 0), + kind: ScriptElementKind.scriptElement, + name: comment.filename, + containerName: undefined, + containerKind: undefined + }]; + } + return undefined; + } + + var symbol = typeInfoResolver.getSymbolAtLocation(node); + + // Could not find a symbol e.g. node is string or number keyword, + // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol + if (!symbol) { + return undefined; + } + + var result: DefinitionInfo[] = []; + + // Because name in short-hand property assignment has two different meanings: property name and property value, + // using go-to-definition at such position should go to the variable declaration of the property value rather than + // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition + // is performed at the location of property access, we would like to go to definition of the property in the short-hand + // assignment. This case and others are handled by the following code. + if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { + var shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); + var shorthandDeclarations = shorthandSymbol.getDeclarations(); + var shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver, node); + var shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); + var shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); + forEach(shorthandDeclarations, declaration => { + result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); + }); + return result + } + + var declarations = symbol.getDeclarations(); + var symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = getSymbolKind(symbol, typeInfoResolver, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; + + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + forEach(declarations, declaration => { + result.push(getDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + + return result; + function getDefinitionInfo(node: Node, symbolKind: string, symbolName: string, containerName: string): DefinitionInfo { return { fileName: node.getSourceFile().filename, - textSpan: TextSpan.fromBounds(node.getStart(), node.getEnd()), + textSpan: createTextSpanFromBounds(node.getStart(), node.getEnd()), kind: symbolKind, name: symbolName, containerKind: undefined, @@ -3444,83 +3216,6 @@ module ts { } return false; } - - synchronizeHostData(); - - filename = normalizeSlashes(filename); - var sourceFile = getSourceFile(filename); - - var node = getTouchingPropertyName(sourceFile, position); - if (!node) { - return undefined; - } - - // Labels - if (isJumpStatementTarget(node)) { - var labelName = (node).text; - var label = getTargetLabel((node.parent), (node).text); - return label ? [getDefinitionInfo(label, ScriptElementKind.label, labelName, /*containerName*/ undefined)] : undefined; - } - - /// Triple slash reference comments - var comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined); - if (comment) { - var referenceFile = tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [{ - fileName: referenceFile.filename, - textSpan: TextSpan.fromBounds(0, 0), - kind: ScriptElementKind.scriptElement, - name: comment.filename, - containerName: undefined, - containerKind: undefined - }]; - } - return undefined; - } - - var symbol = typeInfoResolver.getSymbolAtLocation(node); - - // Could not find a symbol e.g. node is string or number keyword, - // or the symbol was an internal symbol and does not have a declaration e.g. undefined symbol - if (!symbol) { - return undefined; - } - - var result: DefinitionInfo[] = []; - - // Because name in short-hand property assignment has two different meanings: property name and property value, - // using go-to-definition at such position should go to the variable declaration of the property value rather than - // go to the declaration of the property name (in this case stay at the same position). However, if go-to-definition - // is performed at the location of property access, we would like to go to definition of the property in the short-hand - // assignment. This case and others are handled by the following code. - if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { - var shorthandSymbol = typeInfoResolver.getShorthandAssignmentValueSymbol(symbol.valueDeclaration); - var shorthandDeclarations = shorthandSymbol.getDeclarations(); - var shorthandSymbolKind = getSymbolKind(shorthandSymbol, typeInfoResolver); - var shorthandSymbolName = typeInfoResolver.symbolToString(shorthandSymbol); - var shorthandContainerName = typeInfoResolver.symbolToString(symbol.parent, node); - forEach(shorthandDeclarations, declaration => { - result.push(getDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName)); - }); - return result - } - - var declarations = symbol.getDeclarations(); - var symbolName = typeInfoResolver.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, typeInfoResolver); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeInfoResolver.symbolToString(containerSymbol, node) : ""; - - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - forEach(declarations, declaration => { - result.push(getDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - - return result; } /// References and Occurrences @@ -3557,13 +3252,17 @@ module ts { return getThrowOccurrences(node.parent); } break; - case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: - case SyntaxKind.FinallyKeyword: if (hasKind(parent(parent(node)), SyntaxKind.TryStatement)) { return getTryCatchFinallyOccurrences(node.parent.parent); } break; + case SyntaxKind.TryKeyword: + case SyntaxKind.FinallyKeyword: + if (hasKind(parent(node), SyntaxKind.TryStatement)) { + return getTryCatchFinallyOccurrences(node.parent); + } + break; case SyntaxKind.SwitchKeyword: if (hasKind(node.parent, SyntaxKind.SwitchStatement)) { return getSwitchCaseDefaultOccurrences(node.parent); @@ -3634,7 +3333,7 @@ module ts { if (!hasKind(ifStatement.elseStatement, SyntaxKind.IfStatement)) { break } - + ifStatement = ifStatement.elseStatement; } @@ -3656,11 +3355,11 @@ module ts { break; } } - + if (shouldHighlightNextKeyword) { result.push({ fileName: filename, - textSpan: TextSpan.fromBounds(elseKeyword.getStart(), ifKeyword.end), + textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end), isWriteAccess: false }); i++; // skip the next keyword @@ -3695,7 +3394,7 @@ module ts { return map(keywords, getReferenceEntryFromNode); } - + function getThrowOccurrences(throwStatement: ThrowStatement) { var owner = getThrowStatementOwner(throwStatement); @@ -3704,7 +3403,7 @@ module ts { } var keywords: Node[] = []; - + forEach(aggregateOwnedThrowStatements(owner), throwStatement => { pushKeywordIf(keywords, throwStatement.getFirstToken(), SyntaxKind.ThrowKeyword); }); @@ -3716,7 +3415,7 @@ module ts { pushKeywordIf(keywords, returnStatement.getFirstToken(), SyntaxKind.ReturnKeyword); }); } - + return map(keywords, getReferenceEntryFromNode); } @@ -3797,7 +3496,8 @@ module ts { } if (tryStatement.finallyBlock) { - pushKeywordIf(keywords, tryStatement.finallyBlock.getFirstToken(), SyntaxKind.FinallyKeyword); + var finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); + pushKeywordIf(keywords, finallyKeyword, SyntaxKind.FinallyKeyword); } return map(keywords, getReferenceEntryFromNode); @@ -3851,7 +3551,7 @@ module ts { return map(keywords, getReferenceEntryFromNode); } - function getBreakOrContinueStatementOccurences(breakOrContinueStatement: BreakOrContinueStatement): ReferenceEntry[]{ + function getBreakOrContinueStatementOccurences(breakOrContinueStatement: BreakOrContinueStatement): ReferenceEntry[] { var owner = getBreakOrContinueOwner(breakOrContinueStatement); if (owner) { @@ -3899,7 +3599,7 @@ module ts { if (statement.kind === SyntaxKind.ContinueStatement) { continue; } - // Fall through. + // Fall through. case SyntaxKind.ForStatement: case SyntaxKind.ForInStatement: case SyntaxKind.WhileStatement: @@ -4324,13 +4024,13 @@ module ts { * searchLocation: a node where the search value */ function getReferencesInNode(container: Node, - searchSymbol: Symbol, - searchText: string, - searchLocation: Node, - searchMeaning: SemanticMeaning, - findInStrings: boolean, - findInComments: boolean, - result: ReferenceEntry[]): void { + searchSymbol: Symbol, + searchText: string, + searchLocation: Node, + searchMeaning: SemanticMeaning, + findInStrings: boolean, + findInComments: boolean, + result: ReferenceEntry[]): void { var sourceFile = container.getSourceFile(); var tripleSlashDirectivePrefixRegex = /^\/\/\/\s*searchSpaceNode)) { return undefined; } - // Fall through + // Fall through case SyntaxKind.FunctionDeclaration: case SyntaxKind.FunctionExpression: break; @@ -4735,7 +4435,7 @@ module ts { return { fileName: node.getSourceFile().filename, - textSpan: TextSpan.fromBounds(start, end), + textSpan: createTextSpanFromBounds(start, end), isWriteAccess: isWriteAccess(node) }; } @@ -4791,7 +4491,7 @@ module ts { kindModifiers: getNodeModifiers(declaration), matchKind: MatchKind[matchKind], fileName: filename, - textSpan: TextSpan.fromBounds(declaration.getStart(), declaration.getEnd()), + textSpan: createTextSpanFromBounds(declaration.getStart(), declaration.getEnd()), // TODO(jfreeman): What should be the containerName when the container has a computed name? containerName: container && container.name ? (container.name).text : "", containerKind: container && container.name ? getNodeKind(container) : "" @@ -4858,7 +4558,7 @@ module ts { var outputFiles: OutputFile[] = []; - function getEmitOutputWriter(filename: string, data: string, writeByteOrderMark: boolean) { + function writeFile(filename: string, data: string, writeByteOrderMark: boolean) { outputFiles.push({ name: filename, writeByteOrderMark: writeByteOrderMark, @@ -4866,13 +4566,12 @@ module ts { }); } - // Initialize writer for CompilerHost.writeFile - writer = getEmitOutputWriter; + // Get an emit host from our program, but override the writeFile functionality to + // call our local writer function. + var emitHost = createEmitHostFromProgram(program); + emitHost.writeFile = writeFile; - var emitOutput = getFullTypeCheckChecker().emitFiles(sourceFile); - - // Reset writer back to undefined to make sure that we produce an error message if CompilerHost.writeFile method is called when we are not in getEmitOutput - writer = undefined; + var emitOutput = emitFiles(getDiagnosticsProducingTypeChecker().getEmitResolver(), emitHost, sourceFile); return { outputFiles, @@ -5068,7 +4767,7 @@ module ts { } } - return TextSpan.fromBounds(nodeForStartPos.getStart(), node.getEnd()); + return createTextSpanFromBounds(nodeForStartPos.getStart(), node.getEnd()); } function getBreakpointStatementAtPosition(filename: string, position: number) { @@ -5138,14 +4837,14 @@ module ts { function processNode(node: Node) { // Only walk into nodes that intersect the requested span. - if (node && span.intersectsWith(node.getStart(), node.getWidth())) { + if (node && textSpanIntersectsWith(span, node.getStart(), node.getWidth())) { if (node.kind === SyntaxKind.Identifier && node.getWidth() > 0) { var symbol = typeInfoResolver.getSymbolAtLocation(node); if (symbol) { var type = classifySymbol(symbol, getMeaningFromLocation(node)); if (type) { result.push({ - textSpan: new TextSpan(node.getStart(), node.getWidth()), + textSpan: createTextSpan(node.getStart(), node.getWidth()), classificationType: type }); } @@ -5162,39 +4861,118 @@ module ts { fileName = normalizeSlashes(fileName); var sourceFile = getCurrentSourceFile(fileName); + // Make a scanner we can get trivia from. + var triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); + var mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text); + var result: ClassifiedSpan[] = []; processElement(sourceFile); return result; - function classifyComment(comment: CommentRange) { - var width = comment.end - comment.pos; - if (span.intersectsWith(comment.pos, width)) { + function classifyLeadingTrivia(token: Node): void { + var tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false); + if (tokenStart === token.pos) { + return; + } + + // token has trivia. Classify them appropriately. + triviaScanner.setTextPos(token.pos); + while (true) { + var start = triviaScanner.getTextPos(); + var kind = triviaScanner.scan(); + var end = triviaScanner.getTextPos(); + var width = end - start; + + if (textSpanIntersectsWith(span, start, width)) { + if (!isTrivia(kind)) { + return; + } + + if (isComment(kind)) { + // Simple comment. Just add as is. + result.push({ + textSpan: createTextSpan(start, width), + classificationType: ClassificationTypeNames.comment + }) + continue; + } + + if (kind === SyntaxKind.ConflictMarkerTrivia) { + var text = sourceFile.text; + var ch = text.charCodeAt(start); + + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { + result.push({ + textSpan: createTextSpan(start, width), + classificationType: ClassificationTypeNames.comment + }); + continue; + } + + // for the ======== add a comment for the first line, and then lex all + // subsequent lines up until the end of the conflict marker. + Debug.assert(ch === CharacterCodes.equals); + classifyDisabledMergeCode(text, start, end); + } + } + } + } + + function classifyDisabledMergeCode(text: string, start: number, end: number) { + // Classify the line that the ======= marker is on as a comment. Then just lex + // all further tokens and add them to the result. + for (var i = start; i < end; i++) { + if (isLineBreak(text.charCodeAt(i))) { + break; + } + } + result.push({ + textSpan: createTextSpanFromBounds(start, i), + classificationType: ClassificationTypeNames.comment + }); + + mergeConflictScanner.setTextPos(i); + + while (mergeConflictScanner.getTextPos() < end) { + classifyDisabledCodeToken(); + } + } + + function classifyDisabledCodeToken() { + var start = mergeConflictScanner.getTextPos(); + var tokenKind = mergeConflictScanner.scan(); + var end = mergeConflictScanner.getTextPos(); + + var type = classifyTokenType(tokenKind); + if (type) { result.push({ - textSpan: new TextSpan(comment.pos, width), - classificationType: ClassificationTypeNames.comment + textSpan: createTextSpanFromBounds(start, end), + classificationType: type }); } } function classifyToken(token: Node): void { - forEach(getLeadingCommentRanges(sourceFile.text, token.getFullStart()), classifyComment); + classifyLeadingTrivia(token); if (token.getWidth() > 0) { - var type = classifyTokenType(token); + var type = classifyTokenType(token.kind, token); if (type) { result.push({ - textSpan: new TextSpan(token.getStart(), token.getWidth()), + textSpan: createTextSpan(token.getStart(), token.getWidth()), classificationType: type }); } } - - forEach(getTrailingCommentRanges(sourceFile.text, token.getEnd()), classifyComment); } - function classifyTokenType(token: Node): string { - var tokenKind = token.kind; + // for accurate classification, the actual token should be passed in. however, for + // cases like 'disabled merge code' classification, we just get the token kind and + // classify based on that instead. + function classifyTokenType(tokenKind: SyntaxKind, token?: Node): string { if (isKeyword(tokenKind)) { return ClassificationTypeNames.keyword; } @@ -5204,23 +4982,31 @@ module ts { if (tokenKind === SyntaxKind.LessThanToken || tokenKind === SyntaxKind.GreaterThanToken) { // If the node owning the token has a type argument list or type parameter list, then // we can effectively assume that a '<' and '>' belong to those lists. - if (getTypeArgumentOrTypeParameterList(token.parent)) { + if (token && getTypeArgumentOrTypeParameterList(token.parent)) { return ClassificationTypeNames.punctuation; } } - if (isPunctuation(token.kind)) { - // the '=' in a variable declaration is special cased here. - if (token.parent.kind === SyntaxKind.BinaryExpression || - token.parent.kind === SyntaxKind.VariableDeclaration || - token.parent.kind === SyntaxKind.PrefixUnaryExpression || - token.parent.kind === SyntaxKind.PostfixUnaryExpression || - token.parent.kind === SyntaxKind.ConditionalExpression) { - return ClassificationTypeNames.operator; - } - else { - return ClassificationTypeNames.punctuation; + if (isPunctuation(tokenKind)) { + if (token) { + if (tokenKind === SyntaxKind.EqualsToken) { + // the '=' in a variable declaration is special cased here. + if (token.parent.kind === SyntaxKind.VariableDeclaration || + token.parent.kind === SyntaxKind.PropertyDeclaration || + token.parent.kind === SyntaxKind.Parameter) { + return ClassificationTypeNames.operator; + } + } + + if (token.parent.kind === SyntaxKind.BinaryExpression || + token.parent.kind === SyntaxKind.PrefixUnaryExpression || + token.parent.kind === SyntaxKind.PostfixUnaryExpression || + token.parent.kind === SyntaxKind.ConditionalExpression) { + return ClassificationTypeNames.operator; + } } + + return ClassificationTypeNames.punctuation; } else if (tokenKind === SyntaxKind.NumericLiteral) { return ClassificationTypeNames.numericLiteral; @@ -5237,41 +5023,43 @@ module ts { return ClassificationTypeNames.stringLiteral; } else if (tokenKind === SyntaxKind.Identifier) { - switch (token.parent.kind) { - case SyntaxKind.ClassDeclaration: - if ((token.parent).name === token) { - return ClassificationTypeNames.className; - } - return; - case SyntaxKind.TypeParameter: - if ((token.parent).name === token) { - return ClassificationTypeNames.typeParameterName; - } - return; - case SyntaxKind.InterfaceDeclaration: - if ((token.parent).name === token) { - return ClassificationTypeNames.interfaceName; - } - return; - case SyntaxKind.EnumDeclaration: - if ((token.parent).name === token) { - return ClassificationTypeNames.enumName; - } - return; - case SyntaxKind.ModuleDeclaration: - if ((token.parent).name === token) { - return ClassificationTypeNames.moduleName; - } - return; - default: - return ClassificationTypeNames.text; + if (token) { + switch (token.parent.kind) { + case SyntaxKind.ClassDeclaration: + if ((token.parent).name === token) { + return ClassificationTypeNames.className; + } + return; + case SyntaxKind.TypeParameter: + if ((token.parent).name === token) { + return ClassificationTypeNames.typeParameterName; + } + return; + case SyntaxKind.InterfaceDeclaration: + if ((token.parent).name === token) { + return ClassificationTypeNames.interfaceName; + } + return; + case SyntaxKind.EnumDeclaration: + if ((token.parent).name === token) { + return ClassificationTypeNames.enumName; + } + return; + case SyntaxKind.ModuleDeclaration: + if ((token.parent).name === token) { + return ClassificationTypeNames.moduleName; + } + return; + } } + + return ClassificationTypeNames.text; } } function processElement(element: Node) { // Ignore nodes that don't intersect the original span to classify. - if (span.intersectsWith(element.getFullStart(), element.getFullWidth())) { + if (textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) { var children = element.getChildren(); for (var i = 0, n = children.length; i < n; i++) { var child = children[i]; @@ -5312,11 +5100,11 @@ module ts { var current = childNodes[i]; if (current.kind === matchKind) { - var range1 = new TextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); - var range2 = new TextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); + var range1 = createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); + var range2 = createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); // We want to order the braces when we return the result. - if (range1.start() < range2.start()) { + if (range1.start < range2.start) { result.push(range1, range2); } else { @@ -5560,11 +5348,11 @@ module ts { // Only allow a symbol to be renamed if it actually has at least one declaration. if (symbol && symbol.getDeclarations() && symbol.getDeclarations().length > 0) { - var kind = getSymbolKind(symbol, typeInfoResolver); + var kind = getSymbolKind(symbol, typeInfoResolver, node); if (kind) { return getRenameInfo(symbol.name, typeInfoResolver.getFullyQualifiedName(symbol), kind, getSymbolModifiers(symbol), - new TextSpan(node.getStart(), node.getWidth())); + createTextSpan(node.getStart(), node.getWidth())); } } } @@ -5794,7 +5582,6 @@ module ts { var start = scanner.getTokenPos(); var end = scanner.getTextPos(); - // add the token addResult(end - start, classFromKind(token)); if (end >= text.length) { diff --git a/src/services/shims.ts b/src/services/shims.ts index 8fce67025f..3841d397a3 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -203,8 +203,8 @@ module ts { } var decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded); - return new TextChangeRange( - new TextSpan(decoded.span.start, decoded.span.length), decoded.newLength); + return createTextChangeRange( + createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength); } } @@ -391,7 +391,7 @@ module ts { return this.forwardJSONCall( "getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")", () => { - var classifications = this.languageService.getSyntacticClassifications(fileName, new TextSpan(start, length)); + var classifications = this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length)); return classifications; }); } @@ -400,7 +400,7 @@ module ts { return this.forwardJSONCall( "getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")", () => { - var classifications = this.languageService.getSemanticClassifications(fileName, new TextSpan(start, length)); + var classifications = this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length)); return classifications; }); } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 408fe60a6c..426bd73288 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -367,7 +367,7 @@ module ts.SignatureHelp { // but not including parentheses) var applicableSpanStart = argumentsList.getFullStart(); var applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false); - return new TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getApplicableSpanForTaggedTemplate(taggedTemplate: TaggedTemplateExpression): TextSpan { @@ -391,7 +391,7 @@ module ts.SignatureHelp { } } - return new TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); + return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node: Node): ArgumentListInfo { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 146ea141d7..10d0039816 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -271,7 +271,7 @@ module ts { } export function getNodeModifiers(node: Node): string { - var flags = node.flags; + var flags = getCombinedNodeFlags(node); var result: string[] = []; if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier); diff --git a/tests/baselines/reference/FunctionDeclaration5_es6.errors.txt b/tests/baselines/reference/FunctionDeclaration5_es6.errors.txt index a2ac8381fe..c68a6cb205 100644 --- a/tests/baselines/reference/FunctionDeclaration5_es6.errors.txt +++ b/tests/baselines/reference/FunctionDeclaration5_es6.errors.txt @@ -1,13 +1,10 @@ -tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,14): error TS1138: Parameter declaration expected. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,14): error TS2304: Cannot find name 'yield'. tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,19): error TS1005: ';' expected. -==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts (4 errors) ==== +==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts (3 errors) ==== function*foo(yield) { - ~~~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~~~~ !!! error TS1138: Parameter declaration expected. ~~~~~ diff --git a/tests/baselines/reference/VariableDeclaration10_es6.errors.txt b/tests/baselines/reference/VariableDeclaration10_es6.errors.txt index 91c071903c..b7d4bf2f1c 100644 --- a/tests/baselines/reference/VariableDeclaration10_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration10_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts (1 errors) ==== let a: number = 1 - ~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration2_es6.errors.txt b/tests/baselines/reference/VariableDeclaration2_es6.errors.txt index 1ae5920520..0d8214f542 100644 --- a/tests/baselines/reference/VariableDeclaration2_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration2_es6.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,7): error TS1155: 'const' declarations must be initialized ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts (2 errors) ==== const a - ~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. ~ !!! error TS1155: 'const' declarations must be initialized \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration3_es6.errors.txt b/tests/baselines/reference/VariableDeclaration3_es6.errors.txt index e563c4f3ea..a3b09f70d2 100644 --- a/tests/baselines/reference/VariableDeclaration3_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration3_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts (1 errors) ==== const a = 1 - ~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration4_es6.errors.txt b/tests/baselines/reference/VariableDeclaration4_es6.errors.txt index 8bb7692fb5..b4bb75b565 100644 --- a/tests/baselines/reference/VariableDeclaration4_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration4_es6.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,7): error TS1155: 'const' declarations must be initialized ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts (2 errors) ==== const a: number - ~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. ~ !!! error TS1155: 'const' declarations must be initialized \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration5_es6.errors.txt b/tests/baselines/reference/VariableDeclaration5_es6.errors.txt index e55f5a2654..c72d423e46 100644 --- a/tests/baselines/reference/VariableDeclaration5_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration5_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts (1 errors) ==== const a: number = 1 - ~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration7_es6.errors.txt b/tests/baselines/reference/VariableDeclaration7_es6.errors.txt index 5de31099e5..83d12d463e 100644 --- a/tests/baselines/reference/VariableDeclaration7_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration7_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts (1 errors) ==== let a - ~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration8_es6.errors.txt b/tests/baselines/reference/VariableDeclaration8_es6.errors.txt index 5409c6657c..e371c64c9a 100644 --- a/tests/baselines/reference/VariableDeclaration8_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration8_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts (1 errors) ==== let a = 1 - ~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/VariableDeclaration9_es6.errors.txt b/tests/baselines/reference/VariableDeclaration9_es6.errors.txt index 0a2a25858b..4a1890d469 100644 --- a/tests/baselines/reference/VariableDeclaration9_es6.errors.txt +++ b/tests/baselines/reference/VariableDeclaration9_es6.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts (1 errors) ==== let a: number - ~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/anonymousModules.errors.txt b/tests/baselines/reference/anonymousModules.errors.txt index eed6442692..4893a0c80a 100644 --- a/tests/baselines/reference/anonymousModules.errors.txt +++ b/tests/baselines/reference/anonymousModules.errors.txt @@ -1,29 +1,18 @@ tests/cases/compiler/anonymousModules.ts(1,1): error TS2304: Cannot find name 'module'. tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(2,2): error TS1129: Statement expected. -tests/cases/compiler/anonymousModules.ts(2,2): error TS1148: Cannot compile external modules unless the '--module' flag is provided. tests/cases/compiler/anonymousModules.ts(4,2): error TS2304: Cannot find name 'module'. tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(5,3): error TS1129: Statement expected. -tests/cases/compiler/anonymousModules.ts(5,14): error TS2395: Individual declarations in merged declaration bar must be all exported or all local. -tests/cases/compiler/anonymousModules.ts(6,2): error TS1128: Declaration or statement expected. -tests/cases/compiler/anonymousModules.ts(8,6): error TS2395: Individual declarations in merged declaration bar must be all exported or all local. tests/cases/compiler/anonymousModules.ts(10,2): error TS2304: Cannot find name 'module'. tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or statement expected. -==== tests/cases/compiler/anonymousModules.ts (13 errors) ==== +==== tests/cases/compiler/anonymousModules.ts (6 errors) ==== module { ~~~~~~ !!! error TS2304: Cannot find name 'module'. ~ !!! error TS1005: ';' expected. export var foo = 1; - ~~~~~~ -!!! error TS1129: Statement expected. - ~~~~~~~~~~~~~~~~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. module { ~~~~~~ @@ -31,17 +20,9 @@ tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or sta ~ !!! error TS1005: ';' expected. export var bar = 1; - ~~~~~~ -!!! error TS1129: Statement expected. - ~~~ -!!! error TS2395: Individual declarations in merged declaration bar must be all exported or all local. } - ~ -!!! error TS1128: Declaration or statement expected. var bar = 2; - ~~~ -!!! error TS2395: Individual declarations in merged declaration bar must be all exported or all local. module { ~~~~~~ @@ -50,6 +31,4 @@ tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or sta !!! error TS1005: ';' expected. var x = bar; } - } - ~ -!!! error TS1128: Declaration or statement expected. \ No newline at end of file + } \ No newline at end of file diff --git a/tests/baselines/reference/bpSpan_const.baseline b/tests/baselines/reference/bpSpan_const.baseline index bee7d93095..176fb76be8 100644 --- a/tests/baselines/reference/bpSpan_const.baseline +++ b/tests/baselines/reference/bpSpan_const.baseline @@ -76,21 +76,21 @@ -------------------------------- 7 > export const cc1 = false; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (181 to 210) SpanInfo: {"start":185,"length":24} - >export const cc1 = false - >:=> (line 7, col 4) to (line 7, col 28) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (181 to 210) SpanInfo: {"start":192,"length":17} + >const cc1 = false + >:=> (line 7, col 11) to (line 7, col 28) -------------------------------- 8 > export const cc2: number = 23; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (211 to 245) SpanInfo: {"start":215,"length":29} - >export const cc2: number = 23 - >:=> (line 8, col 4) to (line 8, col 33) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (211 to 245) SpanInfo: {"start":222,"length":22} + >const cc2: number = 23 + >:=> (line 8, col 11) to (line 8, col 33) -------------------------------- 9 > export const cc3 = 0, cc4 :string = "", cc5 = null; - ~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (246 to 270) SpanInfo: {"start":250,"length":20} - >export const cc3 = 0 - >:=> (line 9, col 4) to (line 9, col 24) + ~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (246 to 270) SpanInfo: {"start":257,"length":13} + >const cc3 = 0 + >:=> (line 9, col 11) to (line 9, col 24) 9 > export const cc3 = 0, cc4 :string = "", cc5 = null; ~~~~~~~~~~~~~~~~~~ => Pos: (271 to 288) SpanInfo: {"start":272,"length":16} diff --git a/tests/baselines/reference/bpSpan_let.baseline b/tests/baselines/reference/bpSpan_let.baseline index dff12280a9..d9a3c2f854 100644 --- a/tests/baselines/reference/bpSpan_let.baseline +++ b/tests/baselines/reference/bpSpan_let.baseline @@ -84,9 +84,9 @@ -------------------------------- 11 > export let ll2 = 0; - ~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (221 to 244) SpanInfo: {"start":225,"length":18} - >export let ll2 = 0 - >:=> (line 11, col 4) to (line 11, col 22) + ~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (221 to 244) SpanInfo: {"start":232,"length":11} + >let ll2 = 0 + >:=> (line 11, col 11) to (line 11, col 22) -------------------------------- 12 >} ~ => Pos: (245 to 245) SpanInfo: {"start":245,"length":1} diff --git a/tests/baselines/reference/bpSpan_module.baseline b/tests/baselines/reference/bpSpan_module.baseline index 1414551265..e544fc4c43 100644 --- a/tests/baselines/reference/bpSpan_module.baseline +++ b/tests/baselines/reference/bpSpan_module.baseline @@ -50,9 +50,9 @@ -------------------------------- 7 > export var x = 30; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (67 to 93) SpanInfo: {"start":75,"length":17} - >export var x = 30 - >:=> (line 7, col 8) to (line 7, col 25) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (67 to 93) SpanInfo: {"start":82,"length":10} + >var x = 30 + >:=> (line 7, col 15) to (line 7, col 25) -------------------------------- 8 > } @@ -172,15 +172,15 @@ -------------------------------- 25 > { - ~~~~~~ => Pos: (261 to 266) SpanInfo: {"start":275,"length":17} - >export var x = 30 - >:=> (line 26, col 8) to (line 26, col 25) + ~~~~~~ => Pos: (261 to 266) SpanInfo: {"start":282,"length":10} + >var x = 30 + >:=> (line 26, col 15) to (line 26, col 25) -------------------------------- 26 > export var x = 30; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (267 to 293) SpanInfo: {"start":275,"length":17} - >export var x = 30 - >:=> (line 26, col 8) to (line 26, col 25) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (267 to 293) SpanInfo: {"start":282,"length":10} + >var x = 30 + >:=> (line 26, col 15) to (line 26, col 25) -------------------------------- 27 > } diff --git a/tests/baselines/reference/bpSpan_variables.baseline b/tests/baselines/reference/bpSpan_variables.baseline index 1904c34b83..545118daf8 100644 --- a/tests/baselines/reference/bpSpan_variables.baseline +++ b/tests/baselines/reference/bpSpan_variables.baseline @@ -58,15 +58,13 @@ -------------------------------- 9 > export var xx1; - ~~~~~~~~~~~~~~~~~~~~ => Pos: (119 to 138) SpanInfo: {"start":123,"length":14} - >export var xx1 - >:=> (line 9, col 4) to (line 9, col 18) + ~~~~~~~~~~~~~~~~~~~~ => Pos: (119 to 138) SpanInfo: undefined -------------------------------- 10 > export var xx2 = 10, xx3 = 10; - ~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (139 to 162) SpanInfo: {"start":143,"length":19} - >export var xx2 = 10 - >:=> (line 10, col 4) to (line 10, col 23) + ~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (139 to 162) SpanInfo: {"start":150,"length":12} + >var xx2 = 10 + >:=> (line 10, col 11) to (line 10, col 23) 10 > export var xx2 = 10, xx3 = 10; ~~~~~~~~~~~ => Pos: (163 to 173) SpanInfo: {"start":164,"length":8} @@ -75,14 +73,7 @@ -------------------------------- 11 > export var xx4, xx5; - ~~~~~~~~~~~~~~~~~~~ => Pos: (174 to 192) SpanInfo: {"start":178,"length":14} - >export var xx4 - >:=> (line 11, col 4) to (line 11, col 18) -11 > export var xx4, xx5; - - ~~~~~~ => Pos: (193 to 198) SpanInfo: {"start":194,"length":3} - >xx5 - >:=> (line 11, col 20) to (line 11, col 23) + ~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (174 to 198) SpanInfo: undefined -------------------------------- 12 >} ~ => Pos: (199 to 199) SpanInfo: {"start":199,"length":1} diff --git a/tests/baselines/reference/callSignaturesWithParameterInitializers2.errors.txt b/tests/baselines/reference/callSignaturesWithParameterInitializers2.errors.txt index 2d3dc55dce..22f8a563e7 100644 --- a/tests/baselines/reference/callSignaturesWithParameterInitializers2.errors.txt +++ b/tests/baselines/reference/callSignaturesWithParameterInitializers2.errors.txt @@ -1,11 +1,12 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(4,14): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(11,9): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,5): error TS2300: Duplicate identifier 'foo'. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,9): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,15): error TS1005: '{' expected. tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(21,5): error TS2300: Duplicate identifier 'foo'. -==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts (5 errors) ==== +==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts (6 errors) ==== // Optional parameters allow initializers only in implementation signatures // All the below declarations are errors @@ -32,6 +33,8 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWit foo(x = 1), // error ~~~ !!! error TS2300: Duplicate identifier 'foo'. + ~~~~~ +!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. ~ !!! error TS1005: '{' expected. foo(x = 1) { }, // error diff --git a/tests/baselines/reference/cloduleWithPriorInstantiatedModule.errors.txt b/tests/baselines/reference/cloduleWithPriorInstantiatedModule.errors.txt new file mode 100644 index 0000000000..1b0d9cf13c --- /dev/null +++ b/tests/baselines/reference/cloduleWithPriorInstantiatedModule.errors.txt @@ -0,0 +1,22 @@ +tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts(2,8): error TS2434: A module declaration cannot be located prior to a class or function with which it is merged + + +==== tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts (1 errors) ==== + // Non-ambient & instantiated module. + module Moclodule { + ~~~~~~~~~ +!!! error TS2434: A module declaration cannot be located prior to a class or function with which it is merged + export interface Someinterface { + foo(): void; + } + var x = 10; + } + + class Moclodule { + } + + // Instantiated module. + module Moclodule { + export class Manager { + } + } \ No newline at end of file diff --git a/tests/baselines/reference/cloduleWithPriorInstantiatedModule.js b/tests/baselines/reference/cloduleWithPriorInstantiatedModule.js new file mode 100644 index 0000000000..601ab0a753 --- /dev/null +++ b/tests/baselines/reference/cloduleWithPriorInstantiatedModule.js @@ -0,0 +1,39 @@ +//// [cloduleWithPriorInstantiatedModule.ts] +// Non-ambient & instantiated module. +module Moclodule { + export interface Someinterface { + foo(): void; + } + var x = 10; +} + +class Moclodule { +} + +// Instantiated module. +module Moclodule { + export class Manager { + } +} + +//// [cloduleWithPriorInstantiatedModule.js] +// Non-ambient & instantiated module. +var Moclodule; +(function (Moclodule) { + var x = 10; +})(Moclodule || (Moclodule = {})); +var Moclodule = (function () { + function Moclodule() { + } + return Moclodule; +})(); +// Instantiated module. +var Moclodule; +(function (Moclodule) { + var Manager = (function () { + function Manager() { + } + return Manager; + })(); + Moclodule.Manager = Manager; +})(Moclodule || (Moclodule = {})); diff --git a/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.js b/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.js new file mode 100644 index 0000000000..cf06f1134f --- /dev/null +++ b/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.js @@ -0,0 +1,33 @@ +//// [cloduleWithPriorUninstantiatedModule.ts] +// Non-ambient & uninstantiated module. +module Moclodule { + export interface Someinterface { + foo(): void; + } +} + +class Moclodule { +} + +// Instantiated module. +module Moclodule { + export class Manager { + } +} + +//// [cloduleWithPriorUninstantiatedModule.js] +var Moclodule = (function () { + function Moclodule() { + } + return Moclodule; +})(); +// Instantiated module. +var Moclodule; +(function (Moclodule) { + var Manager = (function () { + function Manager() { + } + return Manager; + })(); + Moclodule.Manager = Manager; +})(Moclodule || (Moclodule = {})); diff --git a/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.types b/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.types new file mode 100644 index 0000000000..8dc14646a6 --- /dev/null +++ b/tests/baselines/reference/cloduleWithPriorUninstantiatedModule.types @@ -0,0 +1,25 @@ +=== tests/cases/compiler/cloduleWithPriorUninstantiatedModule.ts === +// Non-ambient & uninstantiated module. +module Moclodule { +>Moclodule : typeof Moclodule + + export interface Someinterface { +>Someinterface : Someinterface + + foo(): void; +>foo : () => void + } +} + +class Moclodule { +>Moclodule : Moclodule +} + +// Instantiated module. +module Moclodule { +>Moclodule : typeof Moclodule + + export class Manager { +>Manager : Manager + } +} diff --git a/tests/baselines/reference/conflictMarkerTrivia1.errors.txt b/tests/baselines/reference/conflictMarkerTrivia1.errors.txt index 0630337841..9f93ab5275 100644 --- a/tests/baselines/reference/conflictMarkerTrivia1.errors.txt +++ b/tests/baselines/reference/conflictMarkerTrivia1.errors.txt @@ -1,25 +1,19 @@ -tests/cases/compiler/conflictMarkerTrivia1.ts(2,1): error TS1184: Merge conflict marker encountered. -tests/cases/compiler/conflictMarkerTrivia1.ts(3,5): error TS2300: Duplicate identifier 'v'. -tests/cases/compiler/conflictMarkerTrivia1.ts(4,1): error TS1184: Merge conflict marker encountered. -tests/cases/compiler/conflictMarkerTrivia1.ts(5,5): error TS2300: Duplicate identifier 'v'. -tests/cases/compiler/conflictMarkerTrivia1.ts(6,1): error TS1184: Merge conflict marker encountered. +tests/cases/compiler/conflictMarkerTrivia1.ts(2,1): error TS1185: Merge conflict marker encountered. +tests/cases/compiler/conflictMarkerTrivia1.ts(4,1): error TS1185: Merge conflict marker encountered. +tests/cases/compiler/conflictMarkerTrivia1.ts(6,1): error TS1185: Merge conflict marker encountered. -==== tests/cases/compiler/conflictMarkerTrivia1.ts (5 errors) ==== +==== tests/cases/compiler/conflictMarkerTrivia1.ts (3 errors) ==== class C { <<<<<<< HEAD - -!!! error TS1184: Merge conflict marker encountered. + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. v = 1; - ~ -!!! error TS2300: Duplicate identifier 'v'. ======= - -!!! error TS1184: Merge conflict marker encountered. + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. v = 2; - ~ -!!! error TS2300: Duplicate identifier 'v'. >>>>>>> Branch-a - -!!! error TS1184: Merge conflict marker encountered. + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. } \ No newline at end of file diff --git a/tests/baselines/reference/conflictMarkerTrivia2.errors.txt b/tests/baselines/reference/conflictMarkerTrivia2.errors.txt new file mode 100644 index 0000000000..150dbbec69 --- /dev/null +++ b/tests/baselines/reference/conflictMarkerTrivia2.errors.txt @@ -0,0 +1,28 @@ +tests/cases/compiler/conflictMarkerTrivia2.ts(3,1): error TS1185: Merge conflict marker encountered. +tests/cases/compiler/conflictMarkerTrivia2.ts(4,6): error TS2304: Cannot find name 'a'. +tests/cases/compiler/conflictMarkerTrivia2.ts(6,1): error TS1185: Merge conflict marker encountered. +tests/cases/compiler/conflictMarkerTrivia2.ts(9,1): error TS1185: Merge conflict marker encountered. + + +==== tests/cases/compiler/conflictMarkerTrivia2.ts (4 errors) ==== + class C { + foo() { + <<<<<<< B + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. + a(); + ~ +!!! error TS2304: Cannot find name 'a'. + } + ======= + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. + b(); + } + >>>>>>> A + ~~~~~~~ +!!! error TS1185: Merge conflict marker encountered. + + public bar() { } + } + \ No newline at end of file diff --git a/tests/baselines/reference/constDeclarations-es5.errors.txt b/tests/baselines/reference/constDeclarations-es5.errors.txt index c928e6ae48..d15535349a 100644 --- a/tests/baselines/reference/constDeclarations-es5.errors.txt +++ b/tests/baselines/reference/constDeclarations-es5.errors.txt @@ -1,17 +1,17 @@ -tests/cases/compiler/constDeclarations-es5.ts(2,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/constDeclarations-es5.ts(3,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/constDeclarations-es5.ts(4,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/constDeclarations-es5.ts(2,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/constDeclarations-es5.ts(3,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/constDeclarations-es5.ts(4,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/compiler/constDeclarations-es5.ts (3 errors) ==== const z7 = false; - ~~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. const z8: number = 23; - ~~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. const z9 = 0, z10 :string = "", z11 = null; - ~~ + ~~~~~ !!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt b/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt index b668468eac..972b4bb918 100644 --- a/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt +++ b/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt @@ -1,14 +1,9 @@ tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(2,22): error TS2339: Property 'foo' does not exist on type 'string'. -tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. - Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number'. -==== tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts (2 errors) ==== +==== tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts (1 errors) ==== var f10: (x: T, b: () => (a: T) => void, y: T) => T; f10('', () => a => a.foo, ''); // a is string ~~~ !!! error TS2339: Property 'foo' does not exist on type 'string'. - var r9 = f10('', () => (a => a.foo), 1); // error - ~~~ -!!! error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. -!!! error TS2453: Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number'. \ No newline at end of file + var r9 = f10('', () => (a => a.foo), 1); // error \ No newline at end of file diff --git a/tests/baselines/reference/dottedModuleName.errors.txt b/tests/baselines/reference/dottedModuleName.errors.txt index 462ce1dbce..afb8b94435 100644 --- a/tests/baselines/reference/dottedModuleName.errors.txt +++ b/tests/baselines/reference/dottedModuleName.errors.txt @@ -1,14 +1,11 @@ -tests/cases/compiler/dottedModuleName.ts(3,18): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/dottedModuleName.ts(3,29): error TS1144: '{' or ';' expected. tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name 'x'. -==== tests/cases/compiler/dottedModuleName.ts (3 errors) ==== +==== tests/cases/compiler/dottedModuleName.ts (2 errors) ==== module M { export module N { export function f(x:number)=>2*x; - ~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~ !!! error TS1144: '{' or ';' expected. ~ diff --git a/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt b/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt new file mode 100644 index 0000000000..94e246f897 --- /dev/null +++ b/tests/baselines/reference/functionsWithModifiersInBlocks1.errors.txt @@ -0,0 +1,35 @@ +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,4): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,21): error TS2393: Duplicate function implementation. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,25): error TS1184: An implementation cannot be declared in ambient contexts. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,4): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,20): error TS2393: Duplicate function implementation. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,4): error TS1184: Modifiers cannot appear here. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,12): error TS1029: 'export' modifier must precede 'declare' modifier. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,28): error TS2393: Duplicate function implementation. +tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,32): error TS1184: An implementation cannot be declared in ambient contexts. + + +==== tests/cases/compiler/functionsWithModifiersInBlocks1.ts (9 errors) ==== + { + declare function f() { } + ~~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + ~ +!!! error TS2393: Duplicate function implementation. + ~ +!!! error TS1184: An implementation cannot be declared in ambient contexts. + export function f() { } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + ~ +!!! error TS2393: Duplicate function implementation. + declare export function f() { } + ~~~~~~~ +!!! error TS1184: Modifiers cannot appear here. + ~~~~~~ +!!! error TS1029: 'export' modifier must precede 'declare' modifier. + ~ +!!! error TS2393: Duplicate function implementation. + ~ +!!! error TS1184: An implementation cannot be declared in ambient contexts. + } \ No newline at end of file diff --git a/tests/baselines/reference/genericAndNonGenericInheritedSignature1.errors.txt b/tests/baselines/reference/genericAndNonGenericInheritedSignature1.errors.txt new file mode 100644 index 0000000000..63ff9d9313 --- /dev/null +++ b/tests/baselines/reference/genericAndNonGenericInheritedSignature1.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts(7,11): error TS2320: Interface 'Hello' cannot simultaneously extend types 'Foo' and 'Bar'. + Named properties 'f' of types 'Foo' and 'Bar' are not identical. + + +==== tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts (1 errors) ==== + interface Foo { + f(x: any): any; + } + interface Bar { + f(x: T): T; + } + interface Hello extends Foo, Bar { + ~~~~~ +!!! error TS2320: Interface 'Hello' cannot simultaneously extend types 'Foo' and 'Bar'. +!!! error TS2320: Named properties 'f' of types 'Foo' and 'Bar' are not identical. + } + \ No newline at end of file diff --git a/tests/baselines/reference/genericAndNonGenericInheritedSignature1.js b/tests/baselines/reference/genericAndNonGenericInheritedSignature1.js new file mode 100644 index 0000000000..15ea71b122 --- /dev/null +++ b/tests/baselines/reference/genericAndNonGenericInheritedSignature1.js @@ -0,0 +1,12 @@ +//// [genericAndNonGenericInheritedSignature1.ts] +interface Foo { + f(x: any): any; +} +interface Bar { + f(x: T): T; +} +interface Hello extends Foo, Bar { +} + + +//// [genericAndNonGenericInheritedSignature1.js] diff --git a/tests/baselines/reference/genericAndNonGenericInheritedSignature2.errors.txt b/tests/baselines/reference/genericAndNonGenericInheritedSignature2.errors.txt new file mode 100644 index 0000000000..05fdd68319 --- /dev/null +++ b/tests/baselines/reference/genericAndNonGenericInheritedSignature2.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts(7,11): error TS2320: Interface 'Hello' cannot simultaneously extend types 'Bar' and 'Foo'. + Named properties 'f' of types 'Bar' and 'Foo' are not identical. + + +==== tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts (1 errors) ==== + interface Foo { + f(x: any): any; + } + interface Bar { + f(x: T): T; + } + interface Hello extends Bar, Foo { + ~~~~~ +!!! error TS2320: Interface 'Hello' cannot simultaneously extend types 'Bar' and 'Foo'. +!!! error TS2320: Named properties 'f' of types 'Bar' and 'Foo' are not identical. + } + \ No newline at end of file diff --git a/tests/baselines/reference/genericAndNonGenericInheritedSignature2.js b/tests/baselines/reference/genericAndNonGenericInheritedSignature2.js new file mode 100644 index 0000000000..d8353b81e9 --- /dev/null +++ b/tests/baselines/reference/genericAndNonGenericInheritedSignature2.js @@ -0,0 +1,12 @@ +//// [genericAndNonGenericInheritedSignature2.ts] +interface Foo { + f(x: any): any; +} +interface Bar { + f(x: T): T; +} +interface Hello extends Bar, Foo { +} + + +//// [genericAndNonGenericInheritedSignature2.js] diff --git a/tests/baselines/reference/inferenceFromParameterlessLambda.js b/tests/baselines/reference/inferenceFromParameterlessLambda.js new file mode 100644 index 0000000000..ad9a18b754 --- /dev/null +++ b/tests/baselines/reference/inferenceFromParameterlessLambda.js @@ -0,0 +1,17 @@ +//// [inferenceFromParameterlessLambda.ts] +function foo(o: Take, i: Make) { } +interface Make { + (): T; +} +interface Take { + (n: T): void; +} +// Infer string from second argument because it isn't context sensitive +foo(n => n.length, () => 'hi'); + + +//// [inferenceFromParameterlessLambda.js] +function foo(o, i) { +} +// Infer string from second argument because it isn't context sensitive +foo(function (n) { return n.length; }, function () { return 'hi'; }); diff --git a/tests/baselines/reference/inferenceFromParameterlessLambda.types b/tests/baselines/reference/inferenceFromParameterlessLambda.types new file mode 100644 index 0000000000..8dbb8c5967 --- /dev/null +++ b/tests/baselines/reference/inferenceFromParameterlessLambda.types @@ -0,0 +1,37 @@ +=== tests/cases/compiler/inferenceFromParameterlessLambda.ts === +function foo(o: Take, i: Make) { } +>foo : (o: Take, i: Make) => void +>T : T +>o : Take +>Take : Take +>T : T +>i : Make +>Make : Make +>T : T + +interface Make { +>Make : Make +>T : T + + (): T; +>T : T +} +interface Take { +>Take : Take +>T : T + + (n: T): void; +>n : T +>T : T +} +// Infer string from second argument because it isn't context sensitive +foo(n => n.length, () => 'hi'); +>foo(n => n.length, () => 'hi') : void +>foo : (o: Take, i: Make) => void +>n => n.length : (n: string) => number +>n : string +>n.length : number +>n : string +>length : number +>() => 'hi' : () => string + diff --git a/tests/baselines/reference/innerModExport1.errors.txt b/tests/baselines/reference/innerModExport1.errors.txt index 25cc83104a..b4f06cc998 100644 --- a/tests/baselines/reference/innerModExport1.errors.txt +++ b/tests/baselines/reference/innerModExport1.errors.txt @@ -1,11 +1,8 @@ tests/cases/compiler/innerModExport1.ts(5,5): error TS2304: Cannot find name 'module'. tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected. -tests/cases/compiler/innerModExport1.ts(7,9): error TS1129: Statement expected. -tests/cases/compiler/innerModExport1.ts(14,5): error TS1148: Cannot compile external modules unless the '--module' flag is provided. -tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or statement expected. -==== tests/cases/compiler/innerModExport1.ts (5 errors) ==== +==== tests/cases/compiler/innerModExport1.ts (2 errors) ==== module Outer { // inner mod 1 @@ -17,8 +14,6 @@ tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or stat !!! error TS1005: ';' expected. var non_export_var = 0; export var export_var = 1; - ~~~~~~ -!!! error TS1129: Statement expected. function NonExportFunc() { return 0; } @@ -26,12 +21,8 @@ tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or stat } export var outer_var_export = 0; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. export function outerFuncExport() { return 0; } } - ~ -!!! error TS1128: Declaration or statement expected. Outer.ExportFunc(); \ No newline at end of file diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index 1456e97637..52a9d01c99 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -1,12 +1,11 @@ tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'module'. tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. -tests/cases/compiler/innerModExport2.ts(7,9): error TS1129: Statement expected. -tests/cases/compiler/innerModExport2.ts(15,5): error TS1148: Cannot compile external modules unless the '--module' flag is provided. -tests/cases/compiler/innerModExport2.ts(18,1): error TS1128: Declaration or statement expected. +tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. +tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. -==== tests/cases/compiler/innerModExport2.ts (6 errors) ==== +==== tests/cases/compiler/innerModExport2.ts (5 errors) ==== module Outer { // inner mod 1 @@ -18,23 +17,21 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport !!! error TS1005: ';' expected. var non_export_var = 0; export var export_var = 1; - ~~~~~~ -!!! error TS1129: Statement expected. + ~~~~~~~~~~ +!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. function NonExportFunc() { return 0; } export function ExportFunc() { return 0; } } var export_var: number; + ~~~~~~~~~~ +!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. export var outer_var_export = 0; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. export function outerFuncExport() { return 0; } } - ~ -!!! error TS1128: Declaration or statement expected. Outer.NonExportFunc(); ~~~~~~~~~~~~~ diff --git a/tests/baselines/reference/letDeclarations-es5-1.errors.txt b/tests/baselines/reference/letDeclarations-es5-1.errors.txt index f0430585a3..f8b5cf629d 100644 --- a/tests/baselines/reference/letDeclarations-es5-1.errors.txt +++ b/tests/baselines/reference/letDeclarations-es5-1.errors.txt @@ -1,27 +1,27 @@ -tests/cases/compiler/letDeclarations-es5-1.ts(1,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5-1.ts(2,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5-1.ts(3,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5-1.ts(4,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5-1.ts(5,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5-1.ts(6,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(2,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(3,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(4,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(5,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5-1.ts(6,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/compiler/letDeclarations-es5-1.ts (6 errors) ==== let l1; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l2: number; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l3, l4, l5 :string, l6; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l7 = false; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l8: number = 23; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l9 = 0, l10 :string = "", l11 = null; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/letDeclarations-es5.errors.txt b/tests/baselines/reference/letDeclarations-es5.errors.txt index 34bd93dba3..27d526f03e 100644 --- a/tests/baselines/reference/letDeclarations-es5.errors.txt +++ b/tests/baselines/reference/letDeclarations-es5.errors.txt @@ -1,40 +1,40 @@ -tests/cases/compiler/letDeclarations-es5.ts(2,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(3,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(4,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(6,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(7,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(8,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(10,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. -tests/cases/compiler/letDeclarations-es5.ts(12,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(2,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(3,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(4,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(6,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(7,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(8,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(10,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. +tests/cases/compiler/letDeclarations-es5.ts(12,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. ==== tests/cases/compiler/letDeclarations-es5.ts (8 errors) ==== let l1; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l2: number; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l3, l4, l5 :string, l6; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l7 = false; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l8: number = 23; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. let l9 = 0, l10 :string = "", l11 = null; - ~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. for(let l11 in {}) { } - ~~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. for(let l12 = 0; l12 < 9; l12++) { } - ~~~ + ~~~ !!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher. \ No newline at end of file diff --git a/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.errors.txt b/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.errors.txt new file mode 100644 index 0000000000..b325710a9f --- /dev/null +++ b/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.errors.txt @@ -0,0 +1,9 @@ +tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts(2,3): error TS1145: Modifiers not permitted on index signature members. + + +==== tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts (1 errors) ==== + interface I { + public [a: string]: number; + ~~~~~~ +!!! error TS1145: Modifiers not permitted on index signature members. + } \ No newline at end of file diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.js new file mode 100644 index 0000000000..983dc004ac --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.js @@ -0,0 +1,35 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt.ts] +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} + +//// [moduleSharesNameWithImportDeclarationInsideIt.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (_M) { + var M = Z.M; + function bar() { + } + _M.bar = bar; + M.bar(); // Should call Z.M.bar + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.types b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.types new file mode 100644 index 0000000000..5a29a01cec --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt.ts === +module Z.M { +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => string + + return ""; + } +} +module A.M { +>A : typeof A +>M : typeof A.M + + import M = Z.M; +>M : typeof M +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => void + } + M.bar(); // Should call Z.M.bar +>M.bar() : string +>M.bar : () => string +>M : typeof M +>bar : () => string +} diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.js new file mode 100644 index 0000000000..1366f52e7f --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.js @@ -0,0 +1,35 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt2.ts] +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + export import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} + +//// [moduleSharesNameWithImportDeclarationInsideIt2.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (M) { + M.M = Z.M; + function bar() { + } + M.bar = bar; + M.M.bar(); // Should call Z.M.bar + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.types b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.types new file mode 100644 index 0000000000..75aba0e2d0 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt2.types @@ -0,0 +1,29 @@ +=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt2.ts === +module Z.M { +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => string + + return ""; + } +} +module A.M { +>A : typeof A +>M : typeof A.M + + export import M = Z.M; +>M : typeof M +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => void + } + M.bar(); // Should call Z.M.bar +>M.bar() : string +>M.bar : () => string +>M : typeof M +>bar : () => string +} diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.errors.txt b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.errors.txt new file mode 100644 index 0000000000..f8fa117c02 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts(10,12): error TS2300: Duplicate identifier 'M'. +tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts(11,12): error TS2300: Duplicate identifier 'M'. + + +==== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts (2 errors) ==== + module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } + } + module A.M { + import M = Z.M; + ~ +!!! error TS2300: Duplicate identifier 'M'. + import M = Z.I; + ~ +!!! error TS2300: Duplicate identifier 'M'. + + export function bar() { + } + M.bar(); // Should call Z.M.bar + } \ No newline at end of file diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.js new file mode 100644 index 0000000000..c11b36f643 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt3.js @@ -0,0 +1,40 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt3.ts] +module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } +} +module A.M { + import M = Z.M; + import M = Z.I; + + export function bar() { + } + M.bar(); // Should call Z.M.bar +} + +//// [moduleSharesNameWithImportDeclarationInsideIt3.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (_M) { + var M = Z.M; + function bar() { + } + _M.bar = bar; + M.bar(); // Should call Z.M.bar + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.js new file mode 100644 index 0000000000..c61f3d4dd9 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.js @@ -0,0 +1,36 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt4.ts] +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + interface M { } + import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} + +//// [moduleSharesNameWithImportDeclarationInsideIt4.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (_M) { + var M = Z.M; + function bar() { + } + _M.bar = bar; + M.bar(); // Should call Z.M.bar + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.types b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.types new file mode 100644 index 0000000000..b4df2e0ae0 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt4.types @@ -0,0 +1,32 @@ +=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt4.ts === +module Z.M { +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => string + + return ""; + } +} +module A.M { +>A : typeof A +>M : typeof A.M + + interface M { } +>M : M + + import M = Z.M; +>M : typeof M +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => void + } + M.bar(); // Should call Z.M.bar +>M.bar() : string +>M.bar : () => string +>M : typeof M +>bar : () => string +} diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.errors.txt b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.errors.txt new file mode 100644 index 0000000000..5e548809e9 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.errors.txt @@ -0,0 +1,25 @@ +tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts(10,12): error TS2300: Duplicate identifier 'M'. +tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts(11,12): error TS2300: Duplicate identifier 'M'. + + +==== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts (2 errors) ==== + module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } + } + module A.M { + import M = Z.I; + ~ +!!! error TS2300: Duplicate identifier 'M'. + import M = Z.M; + ~ +!!! error TS2300: Duplicate identifier 'M'. + + export function bar() { + } + M.bar(); // Should call Z.M.bar + } \ No newline at end of file diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.js new file mode 100644 index 0000000000..0995dcbb9c --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt5.js @@ -0,0 +1,39 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt5.ts] +module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } +} +module A.M { + import M = Z.I; + import M = Z.M; + + export function bar() { + } + M.bar(); // Should call Z.M.bar +} + +//// [moduleSharesNameWithImportDeclarationInsideIt5.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (M) { + function bar() { + } + M.bar = bar; + M.bar(); // Should call Z.M.bar + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.js b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.js new file mode 100644 index 0000000000..51b2d4f89f --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.js @@ -0,0 +1,32 @@ +//// [moduleSharesNameWithImportDeclarationInsideIt6.ts] +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + import M = Z.M; + export function bar() { + } +} + +//// [moduleSharesNameWithImportDeclarationInsideIt6.js] +var Z; +(function (Z) { + var M; + (function (M) { + function bar() { + return ""; + } + M.bar = bar; + })(M = Z.M || (Z.M = {})); +})(Z || (Z = {})); +var A; +(function (A) { + var M; + (function (M) { + function bar() { + } + M.bar = bar; + })(M = A.M || (A.M = {})); +})(A || (A = {})); diff --git a/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.types b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.types new file mode 100644 index 0000000000..01879d2db1 --- /dev/null +++ b/tests/baselines/reference/moduleSharesNameWithImportDeclarationInsideIt6.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt6.ts === +module Z.M { +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => string + + return ""; + } +} +module A.M { +>A : typeof A +>M : typeof A.M + + import M = Z.M; +>M : typeof M +>Z : typeof Z +>M : typeof M + + export function bar() { +>bar : () => void + } +} diff --git a/tests/baselines/reference/noCatchBlock.js.map b/tests/baselines/reference/noCatchBlock.js.map index dccc7798c9..149a2167f4 100644 --- a/tests/baselines/reference/noCatchBlock.js.map +++ b/tests/baselines/reference/noCatchBlock.js.map @@ -1,2 +1,2 @@ //// [noCatchBlock.js.map] -{"version":3,"file":"noCatchBlock.js","sourceRoot":"","sources":["noCatchBlock.ts"],"names":[],"mappings":"AACA,IAAA,CAAC;AAED,CAAC;QAAC,CAAC;AAEH,CAAC"} \ No newline at end of file +{"version":3,"file":"noCatchBlock.js","sourceRoot":"","sources":["noCatchBlock.ts"],"names":[],"mappings":"AACA,IAAI,CAAC;AAEL,CAAC;QAAS,CAAC;AAEX,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/noCatchBlock.sourcemap.txt b/tests/baselines/reference/noCatchBlock.sourcemap.txt index 8d5a67339f..18cb0d5a47 100644 --- a/tests/baselines/reference/noCatchBlock.sourcemap.txt +++ b/tests/baselines/reference/noCatchBlock.sourcemap.txt @@ -14,17 +14,17 @@ sourceFile:noCatchBlock.ts 3 > ^ 1 > > -2 > -3 > t +2 >try +3 > { 1 >Emitted(1, 1) Source(2, 1) + SourceIndex(0) -2 >Emitted(1, 5) Source(2, 1) + SourceIndex(0) -3 >Emitted(1, 6) Source(2, 2) + SourceIndex(0) +2 >Emitted(1, 5) Source(2, 5) + SourceIndex(0) +3 >Emitted(1, 6) Source(2, 6) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^-> -1 >ry { +1 > > // ... > 2 >} @@ -34,16 +34,16 @@ sourceFile:noCatchBlock.ts >>>finally { 1->^^^^^^^^ 2 > ^ -1-> -2 > f -1->Emitted(3, 9) Source(4, 3) + SourceIndex(0) -2 >Emitted(3, 10) Source(4, 4) + SourceIndex(0) +1-> finally +2 > { +1->Emitted(3, 9) Source(4, 11) + SourceIndex(0) +2 >Emitted(3, 10) Source(4, 12) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> -1 >inally { +1 > > // N.B. No 'catch' block > 2 >} diff --git a/tests/baselines/reference/objectLiteralMemberWithModifiers1.errors.txt b/tests/baselines/reference/objectLiteralMemberWithModifiers1.errors.txt new file mode 100644 index 0000000000..9e739194f5 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithModifiers1.errors.txt @@ -0,0 +1,7 @@ +tests/cases/compiler/objectLiteralMemberWithModifiers1.ts(1,11): error TS1184: Modifiers cannot appear here. + + +==== tests/cases/compiler/objectLiteralMemberWithModifiers1.ts (1 errors) ==== + var v = { public foo() { } } + ~~~~~~ +!!! error TS1184: Modifiers cannot appear here. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralMemberWithModifiers1.js b/tests/baselines/reference/objectLiteralMemberWithModifiers1.js new file mode 100644 index 0000000000..8b8c76be51 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithModifiers1.js @@ -0,0 +1,6 @@ +//// [objectLiteralMemberWithModifiers1.ts] +var v = { public foo() { } } + +//// [objectLiteralMemberWithModifiers1.js] +var v = { foo: function () { +} }; diff --git a/tests/baselines/reference/objectLiteralMemberWithModifiers2.errors.txt b/tests/baselines/reference/objectLiteralMemberWithModifiers2.errors.txt new file mode 100644 index 0000000000..e939725ea6 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithModifiers2.errors.txt @@ -0,0 +1,10 @@ +tests/cases/compiler/objectLiteralMemberWithModifiers2.ts(1,22): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. +tests/cases/compiler/objectLiteralMemberWithModifiers2.ts(1,22): error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. + + +==== tests/cases/compiler/objectLiteralMemberWithModifiers2.ts (2 errors) ==== + var v = { public get foo() { } } + ~~~ +!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. + ~~~ +!!! error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.errors.txt b/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.errors.txt new file mode 100644 index 0000000000..b10ba70114 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.errors.txt @@ -0,0 +1,7 @@ +tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts(1,14): error TS1112: A class member cannot be declared optional. + + +==== tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts (1 errors) ==== + var v = { foo?() { } } + ~ +!!! error TS1112: A class member cannot be declared optional. \ No newline at end of file diff --git a/tests/baselines/reference/objectLiteralMemberWithoutBlock1.errors.txt b/tests/baselines/reference/objectLiteralMemberWithoutBlock1.errors.txt new file mode 100644 index 0000000000..fa5fb104c8 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithoutBlock1.errors.txt @@ -0,0 +1,7 @@ +tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts(1,16): error TS1005: '{' expected. + + +==== tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts (1 errors) ==== + var v = { foo(); } + ~ +!!! error TS1005: '{' expected. \ No newline at end of file diff --git a/tests/baselines/reference/objectTypesWithOptionalProperties2.errors.txt b/tests/baselines/reference/objectTypesWithOptionalProperties2.errors.txt index 227df7111c..761fba18b1 100644 --- a/tests/baselines/reference/objectTypesWithOptionalProperties2.errors.txt +++ b/tests/baselines/reference/objectTypesWithOptionalProperties2.errors.txt @@ -2,12 +2,10 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(4,9): error TS1131: Property or signature expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(8,8): error TS1005: ';' expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(8,9): error TS1131: Property or signature expected. -tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,5): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,8): error TS1144: '{' or ';' expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,9): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(16,8): error TS1005: ';' expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(16,9): error TS1131: Property or signature expected. -tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,5): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,8): error TS1144: '{' or ';' expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,9): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected. tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(25,8): error TS1005: '{' expected. @@ -15,7 +13,7 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(26,1): error TS1005: ':' expected. -==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts (15 errors) ==== +==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts (13 errors) ==== // Illegal attempts to define optional methods var a: { @@ -36,8 +34,6 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith class C { x()?: number; // error - ~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~ !!! error TS1144: '{' or ';' expected. ~ @@ -54,8 +50,6 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith class C2 { x()?: T; // error - ~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~ !!! error TS1144: '{' or ';' expected. ~ diff --git a/tests/baselines/reference/parserAccessors10.errors.txt b/tests/baselines/reference/parserAccessors10.errors.txt index 39b9665148..a5228f4744 100644 --- a/tests/baselines/reference/parserAccessors10.errors.txt +++ b/tests/baselines/reference/parserAccessors10.errors.txt @@ -1,15 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,10): error TS1005: ':' expected. -tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,10): error TS2304: Cannot find name 'get'. -tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,14): error TS1005: ',' expected. +tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,14): error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. -==== tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts (1 errors) ==== var v = { public get foo() { } - ~~~ -!!! error TS1005: ':' expected. - ~~~ -!!! error TS2304: Cannot find name 'get'. ~~~ -!!! error TS1005: ',' expected. +!!! error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement. }; \ No newline at end of file diff --git a/tests/baselines/reference/parserAccessors10.js b/tests/baselines/reference/parserAccessors10.js new file mode 100644 index 0000000000..f1bed41ede --- /dev/null +++ b/tests/baselines/reference/parserAccessors10.js @@ -0,0 +1,10 @@ +//// [parserAccessors10.ts] +var v = { + public get foo() { } +}; + +//// [parserAccessors10.js] +var v = { + get foo() { + } +}; diff --git a/tests/baselines/reference/parserComputedPropertyName5.errors.txt b/tests/baselines/reference/parserComputedPropertyName5.errors.txt index 39c5daa062..f0dd056fdf 100644 --- a/tests/baselines/reference/parserComputedPropertyName5.errors.txt +++ b/tests/baselines/reference/parserComputedPropertyName5.errors.txt @@ -1,19 +1,7 @@ -tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,18): error TS1005: ':' expected. -tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,18): error TS2304: Cannot find name 'get'. -tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,23): error TS2304: Cannot find name 'e'. -tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,28): error TS1005: ',' expected. -tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,32): error TS1128: Declaration or statement expected. +tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,22): error TS9002: Computed property names are not currently supported. -==== tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts (5 errors) ==== +==== tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts (1 errors) ==== var v = { public get [e]() { } }; - ~~~ -!!! error TS1005: ':' expected. - ~~~ -!!! error TS2304: Cannot find name 'get'. - ~ -!!! error TS2304: Cannot find name 'e'. - ~ -!!! error TS1005: ',' expected. - ~ -!!! error TS1128: Declaration or statement expected. \ No newline at end of file + ~~~ +!!! error TS9002: Computed property names are not currently supported. \ No newline at end of file diff --git a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.errors.txt b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.errors.txt index 0e2c2b9d12..4f4c37c78b 100644 --- a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.errors.txt +++ b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.errors.txt @@ -1,10 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts(1,14): error TS1144: '{' or ';' expected. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction1.ts (1 errors) ==== function f() => 4; - ~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~ !!! error TS1144: '{' or ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.errors.txt b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.errors.txt index a1e251798c..0a075c960b 100644 --- a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.errors.txt +++ b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.errors.txt @@ -1,13 +1,10 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts(1,15): error TS2304: Cannot find name 'A'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts(1,18): error TS1144: '{' or ';' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts(1,21): error TS2304: Cannot find name 'p'. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts (4 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserErrantEqualsGreaterThanAfterFunction2.ts (3 errors) ==== function f(p: A) => p; - ~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~ !!! error TS2304: Cannot find name 'A'. ~~ diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList6.errors.txt b/tests/baselines/reference/parserErrorRecovery_ParameterList6.errors.txt index 5da6749a28..61ad2fb175 100644 --- a/tests/baselines/reference/parserErrorRecovery_ParameterList6.errors.txt +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList6.errors.txt @@ -1,14 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts(2,12): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts(2,23): error TS1110: Type expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts(2,28): error TS1003: Identifier expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts(3,1): error TS1128: Declaration or statement expected. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts (4 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/ParameterLists/parserErrorRecovery_ParameterList6.ts (3 errors) ==== class Foo { public banana (x: break) { } - ~~~~~~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~~~~ !!! error TS1110: Type expected. ~ diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock1.errors.txt b/tests/baselines/reference/parserModifierOnStatementInBlock1.errors.txt index c24bc0997c..5fa104a0e8 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock1.errors.txt +++ b/tests/baselines/reference/parserModifierOnStatementInBlock1.errors.txt @@ -1,16 +1,15 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts(1,1): error TS1148: Cannot compile external modules unless the '--module' flag is provided. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts(2,4): error TS1129: Statement expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts(3,1): error TS1128: Declaration or statement expected. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts(2,4): error TS1184: Modifiers cannot appear here. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock1.ts (2 errors) ==== export function foo() { ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. export var x = this; + ~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1184: Modifiers cannot appear here. } ~ -!!! error TS1128: Declaration or statement expected. +!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. \ No newline at end of file diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock2.errors.txt b/tests/baselines/reference/parserModifierOnStatementInBlock2.errors.txt index accdc0b062..d863bf7143 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock2.errors.txt +++ b/tests/baselines/reference/parserModifierOnStatementInBlock2.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts(2,4): error TS2304: Cannot find name 'declare'. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts(2,12): error TS1005: ';' expected. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts(2,4): error TS1184: Modifiers cannot appear here. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts(2,18): error TS1039: Initializers are not allowed in ambient contexts. ==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts (2 errors) ==== { declare var x = this; ~~~~~~~ -!!! error TS2304: Cannot find name 'declare'. - ~~~ -!!! error TS1005: ';' expected. +!!! error TS1184: Modifiers cannot appear here. + ~ +!!! error TS1039: Initializers are not allowed in ambient contexts. } \ No newline at end of file diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock3.errors.txt b/tests/baselines/reference/parserModifierOnStatementInBlock3.errors.txt index ebb793783a..5bc5a49670 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock3.errors.txt +++ b/tests/baselines/reference/parserModifierOnStatementInBlock3.errors.txt @@ -1,17 +1,17 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts(1,1): error TS1148: Cannot compile external modules unless the '--module' flag is provided. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts(2,4): error TS1129: Statement expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts(4,1): error TS1128: Declaration or statement expected. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts(2,4): error TS1184: Modifiers cannot appear here. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock3.ts (2 errors) ==== export function foo() { ~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. export function bar() { + ~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ -!!! error TS1129: Statement expected. +!!! error TS1184: Modifiers cannot appear here. } + ~~~~ } ~ -!!! error TS1128: Declaration or statement expected. +!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. \ No newline at end of file diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock4.errors.txt b/tests/baselines/reference/parserModifierOnStatementInBlock4.errors.txt index b84f88c0b9..4fc38af7d5 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock4.errors.txt +++ b/tests/baselines/reference/parserModifierOnStatementInBlock4.errors.txt @@ -1,18 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts(2,4): error TS1129: Statement expected. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts(2,4): error TS1148: Cannot compile external modules unless the '--module' flag is provided. -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts(4,1): error TS1128: Declaration or statement expected. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts(2,4): error TS1184: Modifiers cannot appear here. -==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts (3 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock4.ts (1 errors) ==== { export function bar() { ~~~~~~ -!!! error TS1129: Statement expected. - ~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS1184: Modifiers cannot appear here. } - ~~~~ -!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided. } - ~ -!!! error TS1128: Declaration or statement expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock4.js b/tests/baselines/reference/parserModifierOnStatementInBlock4.js new file mode 100644 index 0000000000..82d2475a68 --- /dev/null +++ b/tests/baselines/reference/parserModifierOnStatementInBlock4.js @@ -0,0 +1,13 @@ +//// [parserModifierOnStatementInBlock4.ts] +{ + export function bar() { + } +} + + +//// [parserModifierOnStatementInBlock4.js] +{ + function bar() { + } + exports.bar = bar; +} diff --git a/tests/baselines/reference/parserSkippedTokens16.errors.txt b/tests/baselines/reference/parserSkippedTokens16.errors.txt index 7359611ef0..fc3565e978 100644 --- a/tests/baselines/reference/parserSkippedTokens16.errors.txt +++ b/tests/baselines/reference/parserSkippedTokens16.errors.txt @@ -2,14 +2,13 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.t tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,6): error TS1005: ';' expected. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,8): error TS2304: Cannot find name 'Bar'. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(1,12): error TS1005: ';' expected. -tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(2,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(2,22): error TS1127: Invalid character. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(3,3): error TS1109: Expression expected. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(6,5): error TS1138: Parameter declaration expected. tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts(8,14): error TS1109: Expression expected. -==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts (9 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.ts (8 errors) ==== foo(): Bar { } ~~~ !!! error TS2304: Cannot find name 'foo'. @@ -20,8 +19,6 @@ tests/cases/conformance/parser/ecmascript5/SkippedTokens/parserSkippedTokens16.t ~ !!! error TS1005: ';' expected. function Foo () # { } - ~~~ -!!! error TS2391: Function implementation is missing or not immediately following the declaration. !!! error TS1127: Invalid character. 4+:5 diff --git a/tests/baselines/reference/privateIndexer2.errors.txt b/tests/baselines/reference/privateIndexer2.errors.txt index 5208b0908e..8d3c1ec1e6 100644 --- a/tests/baselines/reference/privateIndexer2.errors.txt +++ b/tests/baselines/reference/privateIndexer2.errors.txt @@ -1,32 +1,21 @@ -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,13): error TS1005: ':' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15): error TS1005: ',' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,17): error TS2304: Cannot find name 'string'. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1005: ',' expected. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,15): error TS1005: ']' expected. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,23): error TS1005: ',' expected. +tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,24): error TS1136: Property assignment expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(4,32): error TS1005: ':' expected. tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(5,1): error TS1128: Declaration or statement expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,5): error TS1131: Property or signature expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,5): error TS2304: Cannot find name 'private'. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,14): error TS1005: ']' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,16): error TS2304: Cannot find name 'string'. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,22): error TS1005: ';' expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,23): error TS1128: Declaration or statement expected. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(8,25): error TS2304: Cannot find name 'string'. -tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(9,1): error TS1128: Declaration or statement expected. -==== tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts (14 errors) ==== +==== tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts (5 errors) ==== // private indexers not allowed var x = { private [x: string]: string; - ~ -!!! error TS1005: ':' expected. ~ +!!! error TS1005: ']' expected. + ~ !!! error TS1005: ',' expected. - ~~~~~~ -!!! error TS2304: Cannot find name 'string'. ~ -!!! error TS1005: ',' expected. +!!! error TS1136: Property assignment expected. ~ !!! error TS1005: ':' expected. } @@ -35,20 +24,4 @@ tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer2.ts(9,1): var y: { private[x: string]: string; - ~~~~~~~ -!!! error TS1131: Property or signature expected. - ~~~~~~~ -!!! error TS2304: Cannot find name 'private'. - ~ -!!! error TS1005: ']' expected. - ~~~~~~ -!!! error TS2304: Cannot find name 'string'. - ~ -!!! error TS1005: ';' expected. - ~ -!!! error TS1128: Declaration or statement expected. - ~~~~~~ -!!! error TS2304: Cannot find name 'string'. - } - ~ -!!! error TS1128: Declaration or statement expected. \ No newline at end of file + } \ No newline at end of file diff --git a/tests/baselines/reference/promiseChaining.js b/tests/baselines/reference/promiseChaining.js index 1d0962d30d..20961542b2 100644 --- a/tests/baselines/reference/promiseChaining.js +++ b/tests/baselines/reference/promiseChaining.js @@ -19,7 +19,7 @@ var Chain = (function () { Chain.prototype.then = function (cb) { var result = cb(this.value); // should get a fresh type parameter which each then call - var z = this.then(function (x) { return result; }).then(function (x) { return "abc"; }).then(function (x) { return x.length; }) /*number*/; // No error + var z = this.then(function (x) { return result; }).then(function (x) { return "abc"; }).then(function (x) { return x.length; }); // No error return new Chain(result); }; return Chain; diff --git a/tests/baselines/reference/promiseChaining1.js b/tests/baselines/reference/promiseChaining1.js index 9dc167f2db..ee79d3268b 100644 --- a/tests/baselines/reference/promiseChaining1.js +++ b/tests/baselines/reference/promiseChaining1.js @@ -19,7 +19,7 @@ var Chain2 = (function () { Chain2.prototype.then = function (cb) { var result = cb(this.value); // should get a fresh type parameter which each then call - var z = this.then(function (x) { return result; }).then(function (x) { return "abc"; }).then(function (x) { return x.length; }) /*number*/; // Should error on "abc" because it is not a Function + var z = this.then(function (x) { return result; }).then(function (x) { return "abc"; }).then(function (x) { return x.length; }); // Should error on "abc" because it is not a Function return new Chain2(result); }; return Chain2; diff --git a/tests/baselines/reference/restElementWithInitializer1.errors.txt b/tests/baselines/reference/restElementWithInitializer1.errors.txt index 6cee9d5286..aa23192c7b 100644 --- a/tests/baselines/reference/restElementWithInitializer1.errors.txt +++ b/tests/baselines/reference/restElementWithInitializer1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/es6/destructuring/restElementWithInitializer1.ts(2,11): error TS1185: A rest element cannot have an initializer. +tests/cases/conformance/es6/destructuring/restElementWithInitializer1.ts(2,11): error TS1186: A rest element cannot have an initializer. ==== tests/cases/conformance/es6/destructuring/restElementWithInitializer1.ts (1 errors) ==== var a: number[]; var [...x = a] = a; // Error, rest element cannot have initializer ~ -!!! error TS1185: A rest element cannot have an initializer. +!!! error TS1186: A rest element cannot have an initializer. \ No newline at end of file diff --git a/tests/baselines/reference/sourceMap-SkippedNode.js.map b/tests/baselines/reference/sourceMap-SkippedNode.js.map index cdcdc80463..7734042464 100644 --- a/tests/baselines/reference/sourceMap-SkippedNode.js.map +++ b/tests/baselines/reference/sourceMap-SkippedNode.js.map @@ -1,2 +1,2 @@ //// [sourceMap-SkippedNode.js.map] -{"version":3,"file":"sourceMap-SkippedNode.js","sourceRoot":"","sources":["sourceMap-SkippedNode.ts"],"names":[],"mappings":"AAAA,IAAA,CAAC;AAED,CAAC;QAAC,CAAC;AAEH,CAAC"} \ No newline at end of file +{"version":3,"file":"sourceMap-SkippedNode.js","sourceRoot":"","sources":["sourceMap-SkippedNode.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC;AAEL,CAAC;QAAS,CAAC;AAEX,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMap-SkippedNode.sourcemap.txt b/tests/baselines/reference/sourceMap-SkippedNode.sourcemap.txt index 531a666ade..f68320a531 100644 --- a/tests/baselines/reference/sourceMap-SkippedNode.sourcemap.txt +++ b/tests/baselines/reference/sourceMap-SkippedNode.sourcemap.txt @@ -13,17 +13,17 @@ sourceFile:sourceMap-SkippedNode.ts 2 >^^^^ 3 > ^ 1 > -2 > -3 > t +2 >try +3 > { 1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) -2 >Emitted(1, 5) Source(1, 1) + SourceIndex(0) -3 >Emitted(1, 6) Source(1, 2) + SourceIndex(0) +2 >Emitted(1, 5) Source(1, 5) + SourceIndex(0) +3 >Emitted(1, 6) Source(1, 6) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^-> -1 >ry { +1 > >// ... > 2 >} @@ -33,16 +33,16 @@ sourceFile:sourceMap-SkippedNode.ts >>>finally { 1->^^^^^^^^ 2 > ^ -1-> -2 > f -1->Emitted(3, 9) Source(3, 3) + SourceIndex(0) -2 >Emitted(3, 10) Source(3, 4) + SourceIndex(0) +1-> finally +2 > { +1->Emitted(3, 9) Source(3, 11) + SourceIndex(0) +2 >Emitted(3, 10) Source(3, 12) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> -1 >inally { +1 > >// N.B. No 'catch' block > 2 >} diff --git a/tests/baselines/reference/sourceMapValidationStatements.js.map b/tests/baselines/reference/sourceMapValidationStatements.js.map index 8eb9994491..7bf883de6c 100644 --- a/tests/baselines/reference/sourceMapValidationStatements.js.map +++ b/tests/baselines/reference/sourceMapValidationStatements.js.map @@ -1,2 +1,2 @@ //// [sourceMapValidationStatements.js.map] -{"version":3,"file":"sourceMapValidationStatements.js","sourceRoot":"","sources":["sourceMapValidationStatements.ts"],"names":["f"],"mappings":"AAAA,SAAS,CAAC;IACNA,IAAIA,CAACA,CAACA;IACNA,IAAIA,CAACA,GAAGA,CAACA,CAACA;IACVA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,GAAGA,CAACA,EAAEA,CAACA,GAAGA,EAAEA,EAAEA,CAACA,EAAEA,EAAEA,CAACA;QAC1BA,CAACA,IAAIA,CAACA,CAACA;QACPA,CAACA,IAAIA,CAACA,CAACA;IACXA,CAACA;IACDA,EAAEA,CAACA,CAACA,CAACA,GAAGA,EAAEA,CAACA,CAACA,CAACA;QACTA,CAACA,IAAIA,CAACA,CAACA;IACXA,CAACA;IAACA,IAAIA,CAACA,CAACA;QACJA,CAACA,IAAIA,EAAEA,CAACA;QACRA,CAACA,EAAEA,CAACA;IACRA,CAACA;IACDA,IAAIA,CAACA,GAAGA;QACJA,CAACA;QACDA,CAACA;QACDA,CAACA;KACJA,CAACA;IACFA,IAAIA,GAAGA,GAAGA;QACNA,CAACA,EAAEA,CAACA;QACJA,CAACA,EAAEA,OAAOA;KACbA,CAACA;IACFA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,IAAIA,CAACA,CAACA,CAACA,CAACA;QACdA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,CAACA,CAACA,CAACA;QACbA,IAAIA,CAACA,GAAGA,EAAEA,CAACA;IACfA,CAACA;IACDA,IAAAA,CAACA;QACGA,GAAGA,CAACA,CAACA,GAAGA,MAAMA,CAACA;IACnBA,CAAEA;IAAAA,KAAKA,CAACA,CAACA,CAACA,CAACA,CAACA,CAACA;QACTA,EAAEA,CAACA,CAACA,GAAGA,CAACA,CAACA,GAAGA,EAAEA,CAACA,CAACA,CAACA;YACbA,GAAGA,CAACA,CAACA,GAAGA,EAAEA,CAACA;QACfA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,GAAGA,CAACA,CAACA,GAAGA,KAAKA,CAACA;QAClBA,CAACA;IACLA,CAACA;IACDA,IAAAA,CAACA;QACGA,MAAMA,IAAIA,KAAKA,EAAEA,CAACA;IACtBA,CAAEA;IAAAA,KAAKA,CAACA,CAACA,EAAEA,CAACA,CAACA,CAACA;QACVA,IAAIA,CAACA,GAAGA,EAAEA,CAACA;IACfA,CAACA;YAACA,CAACA;QACCA,CAACA,GAAGA,EAAEA,CAACA;IACXA,CAACA;IACDA,MAAMA,GAAGA,EAAEA,CAACA;QACRA,CAACA,GAAGA,CAACA,CAACA;QACNA,CAACA,GAAGA,EAAEA,CAACA;IACXA,CAACA;IACDA,MAAMA,CAACA,CAACA,GAAGA,CAACA,CAACA,CAACA,CAACA,CAACA;QACZA,KAAKA,CAACA,EAAEA,CAACA;YACLA,CAACA,EAAEA,CAACA;YACJA,KAAKA,CAACA;QAEVA,CAACA;QACDA,KAAKA,CAACA,EAAEA,CAACA;YACLA,CAACA,EAAEA,CAACA;YACJA,KAAKA,CAACA;QAEVA,CAACA;QACDA,SAASA,CAACA;YACNA,CAACA,IAAIA,CAACA,CAACA;YACPA,CAACA,GAAGA,EAAEA,CAACA;YACPA,KAAKA,CAACA;QAEVA,CAACA;IACLA,CAACA;IACDA,OAAOA,CAACA,GAAGA,EAAEA,EAAEA,CAACA;QACZA,CAACA,EAAEA,CAACA;IACRA,CAACA;IACDA,GAAGA,CAACA;QACAA,CAACA,EAAEA,CAACA;IACRA,CAACA,QAAQA,CAACA,GAAGA,CAACA,EAACA;IACfA,CAACA,GAAGA,CAACA,CAACA;IACNA,IAAIA,CAACA,GAAGA,CAACA,CAACA,IAAIA,CAACA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,CAACA;IACjCA,CAACA,CAACA,IAAIA,CAACA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,CAACA;IACzBA,CAACA,KAAKA,CAACA,CAACA;IACRA,CAACA,GAAGA,CAACA,GAAGA,EAAEA,CAACA;IACXA,IAAIA,CAACA,GAAGA,CAACA,CAACA;IACVA,MAAMA,CAACA;AACXA,CAACA;AACD,IAAI,CAAC,GAAG;IACJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC,CAAC;AACF,CAAC,EAAE,CAAC"} \ No newline at end of file +{"version":3,"file":"sourceMapValidationStatements.js","sourceRoot":"","sources":["sourceMapValidationStatements.ts"],"names":["f"],"mappings":"AAAA,SAAS,CAAC;IACNA,IAAIA,CAACA,CAACA;IACNA,IAAIA,CAACA,GAAGA,CAACA,CAACA;IACVA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,GAAGA,CAACA,EAAEA,CAACA,GAAGA,EAAEA,EAAEA,CAACA,EAAEA,EAAEA,CAACA;QAC1BA,CAACA,IAAIA,CAACA,CAACA;QACPA,CAACA,IAAIA,CAACA,CAACA;IACXA,CAACA;IACDA,EAAEA,CAACA,CAACA,CAACA,GAAGA,EAAEA,CAACA,CAACA,CAACA;QACTA,CAACA,IAAIA,CAACA,CAACA;IACXA,CAACA;IAACA,IAAIA,CAACA,CAACA;QACJA,CAACA,IAAIA,EAAEA,CAACA;QACRA,CAACA,EAAEA,CAACA;IACRA,CAACA;IACDA,IAAIA,CAACA,GAAGA;QACJA,CAACA;QACDA,CAACA;QACDA,CAACA;KACJA,CAACA;IACFA,IAAIA,GAAGA,GAAGA;QACNA,CAACA,EAAEA,CAACA;QACJA,CAACA,EAAEA,OAAOA;KACbA,CAACA;IACFA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,IAAIA,CAACA,CAACA,CAACA,CAACA;QACdA,GAAGA,CAACA,CAACA,GAAGA,CAACA,CAACA,CAACA,CAACA,CAACA;QACbA,IAAIA,CAACA,GAAGA,EAAEA,CAACA;IACfA,CAACA;IACDA,IAAIA,CAACA;QACDA,GAAGA,CAACA,CAACA,GAAGA,MAAMA,CAACA;IACnBA,CAAEA;IAAAA,KAAKA,CAACA,CAACA,CAACA,CAACA,CAACA,CAACA;QACTA,EAAEA,CAACA,CAACA,GAAGA,CAACA,CAACA,GAAGA,EAAEA,CAACA,CAACA,CAACA;YACbA,GAAGA,CAACA,CAACA,GAAGA,EAAEA,CAACA;QACfA,CAACA;QAACA,IAAIA,CAACA,CAACA;YACJA,GAAGA,CAACA,CAACA,GAAGA,KAAKA,CAACA;QAClBA,CAACA;IACLA,CAACA;IACDA,IAAIA,CAACA;QACDA,MAAMA,IAAIA,KAAKA,EAAEA,CAACA;IACtBA,CAAEA;IAAAA,KAAKA,CAACA,CAACA,EAAEA,CAACA,CAACA,CAACA;QACVA,IAAIA,CAACA,GAAGA,EAAEA,CAACA;IACfA,CAACA;YAASA,CAACA;QACPA,CAACA,GAAGA,EAAEA,CAACA;IACXA,CAACA;IACDA,MAAMA,GAAGA,EAAEA,CAACA;QACRA,CAACA,GAAGA,CAACA,CAACA;QACNA,CAACA,GAAGA,EAAEA,CAACA;IACXA,CAACA;IACDA,MAAMA,CAACA,CAACA,GAAGA,CAACA,CAACA,CAACA,CAACA,CAACA;QACZA,KAAKA,CAACA,EAAEA,CAACA;YACLA,CAACA,EAAEA,CAACA;YACJA,KAAKA,CAACA;QAEVA,CAACA;QACDA,KAAKA,CAACA,EAAEA,CAACA;YACLA,CAACA,EAAEA,CAACA;YACJA,KAAKA,CAACA;QAEVA,CAACA;QACDA,SAASA,CAACA;YACNA,CAACA,IAAIA,CAACA,CAACA;YACPA,CAACA,GAAGA,EAAEA,CAACA;YACPA,KAAKA,CAACA;QAEVA,CAACA;IACLA,CAACA;IACDA,OAAOA,CAACA,GAAGA,EAAEA,EAAEA,CAACA;QACZA,CAACA,EAAEA,CAACA;IACRA,CAACA;IACDA,GAAGA,CAACA;QACAA,CAACA,EAAEA,CAACA;IACRA,CAACA,QAAQA,CAACA,GAAGA,CAACA,EAACA;IACfA,CAACA,GAAGA,CAACA,CAACA;IACNA,IAAIA,CAACA,GAAGA,CAACA,CAACA,IAAIA,CAACA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,CAACA;IACjCA,CAACA,CAACA,IAAIA,CAACA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,GAAGA,CAACA,CAACA;IACzBA,CAACA,KAAKA,CAACA,CAACA;IACRA,CAACA,GAAGA,CAACA,GAAGA,EAAEA,CAACA;IACXA,IAAIA,CAACA,GAAGA,CAACA,CAACA;IACVA,MAAMA,CAACA;AACXA,CAACA;AACD,IAAI,CAAC,GAAG;IACJ,IAAI,CAAC,GAAG,EAAE,CAAC;IACX,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC,CAAC;AACF,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt b/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt index ef7aef275c..586063c7c1 100644 --- a/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationStatements.sourcemap.txt @@ -501,11 +501,11 @@ sourceFile:sourceMapValidationStatements.ts 4 > ^^^^^^^^^^^^^^^-> 1-> > -2 > -3 > t +2 > try +3 > { 1->Emitted(28, 5) Source(27, 5) + SourceIndex(0) name (f) -2 >Emitted(28, 9) Source(27, 5) + SourceIndex(0) name (f) -3 >Emitted(28, 10) Source(27, 6) + SourceIndex(0) name (f) +2 >Emitted(28, 9) Source(27, 9) + SourceIndex(0) name (f) +3 >Emitted(28, 10) Source(27, 10) + SourceIndex(0) name (f) --- >>> obj.q = "ohhh"; 1->^^^^^^^^ @@ -515,7 +515,7 @@ sourceFile:sourceMapValidationStatements.ts 5 > ^^^ 6 > ^^^^^^ 7 > ^ -1->ry { +1-> > 2 > obj 3 > . @@ -706,11 +706,11 @@ sourceFile:sourceMapValidationStatements.ts 4 > ^^^^^^^^^^^^^^^^^^-> 1-> > -2 > -3 > t +2 > try +3 > { 1->Emitted(39, 5) Source(36, 5) + SourceIndex(0) name (f) -2 >Emitted(39, 9) Source(36, 5) + SourceIndex(0) name (f) -3 >Emitted(39, 10) Source(36, 6) + SourceIndex(0) name (f) +2 >Emitted(39, 9) Source(36, 9) + SourceIndex(0) name (f) +3 >Emitted(39, 10) Source(36, 10) + SourceIndex(0) name (f) --- >>> throw new Error(); 1->^^^^^^^^ @@ -719,7 +719,7 @@ sourceFile:sourceMapValidationStatements.ts 4 > ^^^^^ 5 > ^^ 6 > ^ -1->ry { +1-> > 2 > throw 3 > new @@ -805,10 +805,10 @@ sourceFile:sourceMapValidationStatements.ts 1->^^^^^^^^^^^^ 2 > ^ 3 > ^^^-> -1-> -2 > f -1->Emitted(45, 13) Source(40, 7) + SourceIndex(0) name (f) -2 >Emitted(45, 14) Source(40, 8) + SourceIndex(0) name (f) +1-> finally +2 > { +1->Emitted(45, 13) Source(40, 15) + SourceIndex(0) name (f) +2 >Emitted(45, 14) Source(40, 16) + SourceIndex(0) name (f) --- >>> y = 70; 1->^^^^^^^^ @@ -816,7 +816,7 @@ sourceFile:sourceMapValidationStatements.ts 3 > ^^^ 4 > ^^ 5 > ^ -1->inally { +1-> > 2 > y 3 > = diff --git a/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map b/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map index 8971680753..4650641085 100644 --- a/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map +++ b/tests/baselines/reference/sourceMapValidationTryCatchFinally.js.map @@ -1,2 +1,2 @@ //// [sourceMapValidationTryCatchFinally.js.map] -{"version":3,"file":"sourceMapValidationTryCatchFinally.js","sourceRoot":"","sources":["sourceMapValidationTryCatchFinally.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC,GAAG,EAAE,CAAC;AACX,IAAA,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAE;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACT,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAAC,CAAC;IACC,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC;AACD,IAAA,CAAC;IAEG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,IAAI,KAAK,EAAE,CAAC;AACtB,CACA;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CACT,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QACD,CAAC;IAEG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC"} \ No newline at end of file +{"version":3,"file":"sourceMapValidationTryCatchFinally.js","sourceRoot":"","sources":["sourceMapValidationTryCatchFinally.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC,GAAG,EAAE,CAAC;AACX,IAAI,CAAC;IACD,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAE;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACT,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAAS,CAAC;IACP,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC;AACD,IACA,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,IAAI,KAAK,EAAE,CAAC;AACtB,CACA;AAAA,KAAK,CAAC,CAAC,CAAC,CAAC,CACT,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;QAED,CAAC;IACG,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt b/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt index 25dee4fbc4..d625e74c26 100644 --- a/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt +++ b/tests/baselines/reference/sourceMapValidationTryCatchFinally.sourcemap.txt @@ -35,11 +35,11 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 4 > ^^^^^^^^^^-> 1 > > -2 > -3 > t +2 >try +3 > { 1 >Emitted(2, 1) Source(2, 1) + SourceIndex(0) -2 >Emitted(2, 5) Source(2, 1) + SourceIndex(0) -3 >Emitted(2, 6) Source(2, 2) + SourceIndex(0) +2 >Emitted(2, 5) Source(2, 5) + SourceIndex(0) +3 >Emitted(2, 6) Source(2, 6) + SourceIndex(0) --- >>> x = x + 1; 1->^^^^ @@ -49,7 +49,7 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 5 > ^^^ 6 > ^ 7 > ^ -1->ry { +1-> > 2 > x 3 > = @@ -140,10 +140,10 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 1->^^^^^^^^ 2 > ^ 3 > ^^^^^^^-> -1-> -2 > f -1->Emitted(8, 9) Source(6, 3) + SourceIndex(0) -2 >Emitted(8, 10) Source(6, 4) + SourceIndex(0) +1-> finally +2 > { +1->Emitted(8, 9) Source(6, 11) + SourceIndex(0) +2 >Emitted(8, 10) Source(6, 12) + SourceIndex(0) --- >>> x = x * 10; 1->^^^^ @@ -153,7 +153,7 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 5 > ^^^ 6 > ^^ 7 > ^ -1->inally { +1-> > 2 > x 3 > = @@ -186,11 +186,12 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 4 > ^^^^^^^^^^-> 1-> > -2 > -3 > t +2 >try + > +3 > { 1->Emitted(11, 1) Source(9, 1) + SourceIndex(0) -2 >Emitted(11, 5) Source(9, 1) + SourceIndex(0) -3 >Emitted(11, 6) Source(9, 2) + SourceIndex(0) +2 >Emitted(11, 5) Source(10, 1) + SourceIndex(0) +3 >Emitted(11, 6) Source(10, 2) + SourceIndex(0) --- >>> x = x + 1; 1->^^^^ @@ -201,8 +202,7 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 6 > ^ 7 > ^ 8 > ^^^^^^^^^-> -1->ry - >{ +1-> > 2 > x 3 > = @@ -317,10 +317,11 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 2 > ^ 3 > ^^^^^^^-> 1-> + >finally > -2 > f -1->Emitted(18, 9) Source(18, 1) + SourceIndex(0) -2 >Emitted(18, 10) Source(18, 2) + SourceIndex(0) +2 > { +1->Emitted(18, 9) Source(19, 1) + SourceIndex(0) +2 >Emitted(18, 10) Source(19, 2) + SourceIndex(0) --- >>> x = x * 10; 1->^^^^ @@ -330,8 +331,7 @@ sourceFile:sourceMapValidationTryCatchFinally.ts 5 > ^^^ 6 > ^^ 7 > ^ -1->inally - >{ +1-> > 2 > x 3 > = diff --git a/tests/baselines/reference/taggedTemplateContextualTyping1.js b/tests/baselines/reference/taggedTemplateContextualTyping1.js new file mode 100644 index 0000000000..d631a718bf --- /dev/null +++ b/tests/baselines/reference/taggedTemplateContextualTyping1.js @@ -0,0 +1,48 @@ +//// [taggedTemplateContextualTyping1.ts] + +type FuncType = (x: (p: T) => T) => typeof x; + +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, x: T): T; +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, h: FuncType, x: T): T; +function tempTag1(...rest: any[]): T { + return undefined; +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag1 `${ x => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ 10 }`; +tempTag1 `${ x => { x(undefined); return x; } }${ (y: (p: T) => T) => { y(undefined); return y } }${ undefined }`; +tempTag1 `${ (x: (p: T) => T) => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ undefined }`; + + +//// [taggedTemplateContextualTyping1.js] +function tempTag1(...rest) { + return undefined; +} +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag1 `${function (x) { + x(undefined); + return x; +}}${function (y) { + y(undefined); + return y; +}}${10}`; +tempTag1 `${function (x) { + x(undefined); + return x; +}}${function (y) { + y(undefined); + return y; +}}${undefined}`; +tempTag1 `${function (x) { + x(undefined); + return x; +}}${function (y) { + y(undefined); + return y; +}}${undefined}`; diff --git a/tests/baselines/reference/taggedTemplateContextualTyping1.types b/tests/baselines/reference/taggedTemplateContextualTyping1.types new file mode 100644 index 0000000000..a87d5eaa7a --- /dev/null +++ b/tests/baselines/reference/taggedTemplateContextualTyping1.types @@ -0,0 +1,104 @@ +=== tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts === + +type FuncType = (x: (p: T) => T) => typeof x; +>FuncType : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>T : T +>p : T +>T : T +>T : T +>x : (p: T) => T + +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, x: T): T; +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>T : T +>templateStrs : TemplateStringsArray +>TemplateStringsArray : TemplateStringsArray +>f : (x: (p: T) => T) => (p: T) => T +>FuncType : (x: (p: T) => T) => (p: T) => T +>x : T +>T : T +>T : T + +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, h: FuncType, x: T): T; +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>T : T +>templateStrs : TemplateStringsArray +>TemplateStringsArray : TemplateStringsArray +>f : (x: (p: T) => T) => (p: T) => T +>FuncType : (x: (p: T) => T) => (p: T) => T +>h : (x: (p: T) => T) => (p: T) => T +>FuncType : (x: (p: T) => T) => (p: T) => T +>x : T +>T : T +>T : T + +function tempTag1(...rest: any[]): T { +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>T : T +>rest : any[] +>T : T + + return undefined; +>undefined : undefined +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag1 `${ x => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ 10 }`; +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>x => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>x(undefined) : number +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T +>y => { y(undefined); return y; } : (y: (p: T) => T) => (p: T) => T +>y : (p: T) => T +>y(undefined) : number +>y : (p: T) => T +>undefined : undefined +>y : (p: T) => T + +tempTag1 `${ x => { x(undefined); return x; } }${ (y: (p: T) => T) => { y(undefined); return y } }${ undefined }`; +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>x => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>x(undefined) : number +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T +>(y: (p: T) => T) => { y(undefined); return y } : (y: (p: T) => T) => (p: T) => T +>y : (p: T) => T +>T : T +>p : T +>T : T +>T : T +>y(undefined) : number +>y : (p: T) => T +>undefined : undefined +>y : (p: T) => T +>undefined : undefined + +tempTag1 `${ (x: (p: T) => T) => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ undefined }`; +>tempTag1 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: T): T; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: T): T; } +>(x: (p: T) => T) => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>T : T +>p : T +>T : T +>T : T +>x(undefined) : number +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T +>y => { y(undefined); return y; } : (y: (p: T) => T) => (p: T) => T +>y : (p: T) => T +>y(undefined) : number +>y : (p: T) => T +>undefined : undefined +>y : (p: T) => T +>undefined : undefined + diff --git a/tests/baselines/reference/taggedTemplateContextualTyping2.js b/tests/baselines/reference/taggedTemplateContextualTyping2.js new file mode 100644 index 0000000000..a24de8224f --- /dev/null +++ b/tests/baselines/reference/taggedTemplateContextualTyping2.js @@ -0,0 +1,42 @@ +//// [taggedTemplateContextualTyping2.ts] + +type FuncType1 = (x: (p: T) => T) => typeof x; +type FuncType2 = (x: (p: T) => T) => typeof x; + +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType1, x: number): number; +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType2, h: FuncType2, x: string): string; +function tempTag2(...rest: any[]): any { + return undefined; +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag2 `${ x => { x(undefined); return x; } }${ 0 }`; +tempTag2 `${ x => { x(undefined); return x; } }${ y => { y(null); return y; } }${ "hello" }`; +tempTag2 `${ x => { x(undefined); return x; } }${ undefined }${ "hello" }`; + +//// [taggedTemplateContextualTyping2.js] +function tempTag2(...rest) { + return undefined; +} +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag2 `${function (x) { + x(undefined); + return x; +}}${0}`; +tempTag2 `${function (x) { + x(undefined); + return x; +}}${function (y) { + y(null); + return y; +}}${"hello"}`; +tempTag2 `${function (x) { + x(undefined); + return x; +}}${undefined}${"hello"}`; diff --git a/tests/baselines/reference/taggedTemplateContextualTyping2.types b/tests/baselines/reference/taggedTemplateContextualTyping2.types new file mode 100644 index 0000000000..9ca7386dc3 --- /dev/null +++ b/tests/baselines/reference/taggedTemplateContextualTyping2.types @@ -0,0 +1,84 @@ +=== tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts === + +type FuncType1 = (x: (p: T) => T) => typeof x; +>FuncType1 : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>T : T +>p : T +>T : T +>T : T +>x : (p: T) => T + +type FuncType2 = (x: (p: T) => T) => typeof x; +>FuncType2 : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>S : S +>T : T +>p : T +>T : T +>T : T +>x : (p: T) => T + +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType1, x: number): number; +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>templateStrs : TemplateStringsArray +>TemplateStringsArray : TemplateStringsArray +>f : (x: (p: T) => T) => (p: T) => T +>FuncType1 : (x: (p: T) => T) => (p: T) => T +>x : number + +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType2, h: FuncType2, x: string): string; +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>templateStrs : TemplateStringsArray +>TemplateStringsArray : TemplateStringsArray +>f : (x: (p: T) => T) => (p: T) => T +>FuncType2 : (x: (p: T) => T) => (p: T) => T +>h : (x: (p: T) => T) => (p: T) => T +>FuncType2 : (x: (p: T) => T) => (p: T) => T +>x : string + +function tempTag2(...rest: any[]): any { +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>rest : any[] + + return undefined; +>undefined : undefined +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag2 `${ x => { x(undefined); return x; } }${ 0 }`; +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>x => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>x(undefined) : number +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T + +tempTag2 `${ x => { x(undefined); return x; } }${ y => { y(null); return y; } }${ "hello" }`; +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>x => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>x(undefined) : string +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T +>y => { y(null); return y; } : (y: (p: T) => T) => (p: T) => T +>y : (p: T) => T +>y(null) : number +>y : (p: T) => T +>y : (p: T) => T + +tempTag2 `${ x => { x(undefined); return x; } }${ undefined }${ "hello" }`; +>tempTag2 : { (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, x: number): number; (templateStrs: TemplateStringsArray, f: (x: (p: T) => T) => (p: T) => T, h: (x: (p: T) => T) => (p: T) => T, x: string): string; } +>x => { x(undefined); return x; } : (x: (p: T) => T) => (p: T) => T +>x : (p: T) => T +>x(undefined) : string +>x : (p: T) => T +>undefined : undefined +>x : (p: T) => T +>undefined : undefined + diff --git a/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt new file mode 100644 index 0000000000..b38a70ca18 --- /dev/null +++ b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts(6,5): error TS1159: Tagged templates are only available when targeting ECMAScript 6 and higher. +tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts(6,31): error TS2322: Type 'string' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts (2 errors) ==== + + + function foo(...rest: any[]) { + } + + foo `${function (x: number) { x = "bad"; } }`; + ~~~ +!!! error TS1159: Tagged templates are only available when targeting ECMAScript 6 and higher. + ~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt new file mode 100644 index 0000000000..6b0f4b642f --- /dev/null +++ b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt @@ -0,0 +1,11 @@ +tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts(5,31): error TS2322: Type 'string' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts (1 errors) ==== + + function foo(...rest: any[]) { + } + + foo `${function (x: number) { x = "bad"; } }`; + ~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js new file mode 100644 index 0000000000..bc18a60045 --- /dev/null +++ b/tests/baselines/reference/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js @@ -0,0 +1,13 @@ +//// [taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts] + +function foo(...rest: any[]) { +} + +foo `${function (x: number) { x = "bad"; } }`; + +//// [taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js] +function foo(...rest) { +} +foo `${function (x) { + x = "bad"; +}}`; diff --git a/tests/baselines/reference/templateStringBinaryOperations.js b/tests/baselines/reference/templateStringBinaryOperations.js new file mode 100644 index 0000000000..691dad41f7 --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperations.js @@ -0,0 +1,103 @@ +//// [templateStringBinaryOperations.ts] +var a = 1 + `${ 3 }`; +var b = 1 + `2${ 3 }`; +var c = 1 + `${ 3 }4`; +var d = 1 + `2${ 3 }4`; +var e = `${ 3 }` + 5; +var f = `2${ 3 }` + 5; +var g = `${ 3 }4` + 5; +var h = `2${ 3 }4` + 5; +var i = 1 + `${ 3 }` + 5; +var j = 1 + `2${ 3 }` + 5; +var k = 1 + `${ 3 }4` + 5; +var l = 1 + `2${ 3 }4` + 5; + +var a2 = 1 + `${ 3 - 4 }`; +var b2 = 1 + `2${ 3 - 4 }`; +var c2 = 1 + `${ 3 - 4 }5`; +var d2 = 1 + `2${ 3 - 4 }5`; +var e2 = `${ 3 - 4 }` + 6; +var f2 = `2${ 3 - 4 }` + 6; +var g2 = `${ 3 - 4 }5` + 6; +var h2 = `2${ 3 - 4 }5` + 6; +var i2 = 1 + `${ 3 - 4 }` + 6; +var j2 = 1 + `2${ 3 - 4 }` + 6; +var k2 = 1 + `${ 3 - 4 }5` + 6; +var l2 = 1 + `2${ 3 - 4 }5` + 6; + +var a3 = 1 + `${ 3 * 4 }`; +var b3 = 1 + `2${ 3 * 4 }`; +var c3 = 1 + `${ 3 * 4 }5`; +var d3 = 1 + `2${ 3 * 4 }5`; +var e3 = `${ 3 * 4 }` + 6; +var f3 = `2${ 3 * 4 }` + 6; +var g3 = `${ 3 * 4 }5` + 6; +var h3 = `2${ 3 * 4 }5` + 6; +var i3 = 1 + `${ 3 * 4 }` + 6; +var j3 = 1 + `2${ 3 * 4 }` + 6; +var k3 = 1 + `${ 3 * 4 }5` + 6; +var l3 = 1 + `2${ 3 * 4 }5` + 6; + +var a4 = 1 + `${ 3 & 4 }`; +var b4 = 1 + `2${ 3 & 4 }`; +var c4 = 1 + `${ 3 & 4 }5`; +var d4 = 1 + `2${ 3 & 4 }5`; +var e4 = `${ 3 & 4 }` + 6; +var f4 = `2${ 3 & 4 }` + 6; +var g4 = `${ 3 & 4 }5` + 6; +var h4 = `2${ 3 & 4 }5` + 6; +var i4 = 1 + `${ 3 & 4 }` + 6; +var j4 = 1 + `2${ 3 & 4 }` + 6; +var k4 = 1 + `${ 3 & 4 }5` + 6; +var l4 = 1 + `2${ 3 & 4 }5` + 6; + + +//// [templateStringBinaryOperations.js] +var a = 1 + ("" + 3); +var b = 1 + ("2" + 3); +var c = 1 + (3 + "4"); +var d = 1 + ("2" + 3 + "4"); +var e = ("" + 3) + 5; +var f = ("2" + 3) + 5; +var g = (3 + "4") + 5; +var h = ("2" + 3 + "4") + 5; +var i = 1 + ("" + 3) + 5; +var j = 1 + ("2" + 3) + 5; +var k = 1 + (3 + "4") + 5; +var l = 1 + ("2" + 3 + "4") + 5; +var a2 = 1 + ("" + (3 - 4)); +var b2 = 1 + ("2" + (3 - 4)); +var c2 = 1 + ((3 - 4) + "5"); +var d2 = 1 + ("2" + (3 - 4) + "5"); +var e2 = ("" + (3 - 4)) + 6; +var f2 = ("2" + (3 - 4)) + 6; +var g2 = ((3 - 4) + "5") + 6; +var h2 = ("2" + (3 - 4) + "5") + 6; +var i2 = 1 + ("" + (3 - 4)) + 6; +var j2 = 1 + ("2" + (3 - 4)) + 6; +var k2 = 1 + ((3 - 4) + "5") + 6; +var l2 = 1 + ("2" + (3 - 4) + "5") + 6; +var a3 = 1 + ("" + 3 * 4); +var b3 = 1 + ("2" + 3 * 4); +var c3 = 1 + (3 * 4 + "5"); +var d3 = 1 + ("2" + 3 * 4 + "5"); +var e3 = ("" + 3 * 4) + 6; +var f3 = ("2" + 3 * 4) + 6; +var g3 = (3 * 4 + "5") + 6; +var h3 = ("2" + 3 * 4 + "5") + 6; +var i3 = 1 + ("" + 3 * 4) + 6; +var j3 = 1 + ("2" + 3 * 4) + 6; +var k3 = 1 + (3 * 4 + "5") + 6; +var l3 = 1 + ("2" + 3 * 4 + "5") + 6; +var a4 = 1 + ("" + (3 & 4)); +var b4 = 1 + ("2" + (3 & 4)); +var c4 = 1 + ((3 & 4) + "5"); +var d4 = 1 + ("2" + (3 & 4) + "5"); +var e4 = ("" + (3 & 4)) + 6; +var f4 = ("2" + (3 & 4)) + 6; +var g4 = ((3 & 4) + "5") + 6; +var h4 = ("2" + (3 & 4) + "5") + 6; +var i4 = 1 + ("" + (3 & 4)) + 6; +var j4 = 1 + ("2" + (3 & 4)) + 6; +var k4 = 1 + ((3 & 4) + "5") + 6; +var l4 = 1 + ("2" + (3 & 4) + "5") + 6; diff --git a/tests/baselines/reference/templateStringBinaryOperations.types b/tests/baselines/reference/templateStringBinaryOperations.types new file mode 100644 index 0000000000..094c82f367 --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperations.types @@ -0,0 +1,245 @@ +=== tests/cases/conformance/es6/templates/templateStringBinaryOperations.ts === +var a = 1 + `${ 3 }`; +>a : string +>1 + `${ 3 }` : string + +var b = 1 + `2${ 3 }`; +>b : string +>1 + `2${ 3 }` : string + +var c = 1 + `${ 3 }4`; +>c : string +>1 + `${ 3 }4` : string + +var d = 1 + `2${ 3 }4`; +>d : string +>1 + `2${ 3 }4` : string + +var e = `${ 3 }` + 5; +>e : string +>`${ 3 }` + 5 : string + +var f = `2${ 3 }` + 5; +>f : string +>`2${ 3 }` + 5 : string + +var g = `${ 3 }4` + 5; +>g : string +>`${ 3 }4` + 5 : string + +var h = `2${ 3 }4` + 5; +>h : string +>`2${ 3 }4` + 5 : string + +var i = 1 + `${ 3 }` + 5; +>i : string +>1 + `${ 3 }` + 5 : string +>1 + `${ 3 }` : string + +var j = 1 + `2${ 3 }` + 5; +>j : string +>1 + `2${ 3 }` + 5 : string +>1 + `2${ 3 }` : string + +var k = 1 + `${ 3 }4` + 5; +>k : string +>1 + `${ 3 }4` + 5 : string +>1 + `${ 3 }4` : string + +var l = 1 + `2${ 3 }4` + 5; +>l : string +>1 + `2${ 3 }4` + 5 : string +>1 + `2${ 3 }4` : string + +var a2 = 1 + `${ 3 - 4 }`; +>a2 : string +>1 + `${ 3 - 4 }` : string +>3 - 4 : number + +var b2 = 1 + `2${ 3 - 4 }`; +>b2 : string +>1 + `2${ 3 - 4 }` : string +>3 - 4 : number + +var c2 = 1 + `${ 3 - 4 }5`; +>c2 : string +>1 + `${ 3 - 4 }5` : string +>3 - 4 : number + +var d2 = 1 + `2${ 3 - 4 }5`; +>d2 : string +>1 + `2${ 3 - 4 }5` : string +>3 - 4 : number + +var e2 = `${ 3 - 4 }` + 6; +>e2 : string +>`${ 3 - 4 }` + 6 : string +>3 - 4 : number + +var f2 = `2${ 3 - 4 }` + 6; +>f2 : string +>`2${ 3 - 4 }` + 6 : string +>3 - 4 : number + +var g2 = `${ 3 - 4 }5` + 6; +>g2 : string +>`${ 3 - 4 }5` + 6 : string +>3 - 4 : number + +var h2 = `2${ 3 - 4 }5` + 6; +>h2 : string +>`2${ 3 - 4 }5` + 6 : string +>3 - 4 : number + +var i2 = 1 + `${ 3 - 4 }` + 6; +>i2 : string +>1 + `${ 3 - 4 }` + 6 : string +>1 + `${ 3 - 4 }` : string +>3 - 4 : number + +var j2 = 1 + `2${ 3 - 4 }` + 6; +>j2 : string +>1 + `2${ 3 - 4 }` + 6 : string +>1 + `2${ 3 - 4 }` : string +>3 - 4 : number + +var k2 = 1 + `${ 3 - 4 }5` + 6; +>k2 : string +>1 + `${ 3 - 4 }5` + 6 : string +>1 + `${ 3 - 4 }5` : string +>3 - 4 : number + +var l2 = 1 + `2${ 3 - 4 }5` + 6; +>l2 : string +>1 + `2${ 3 - 4 }5` + 6 : string +>1 + `2${ 3 - 4 }5` : string +>3 - 4 : number + +var a3 = 1 + `${ 3 * 4 }`; +>a3 : string +>1 + `${ 3 * 4 }` : string +>3 * 4 : number + +var b3 = 1 + `2${ 3 * 4 }`; +>b3 : string +>1 + `2${ 3 * 4 }` : string +>3 * 4 : number + +var c3 = 1 + `${ 3 * 4 }5`; +>c3 : string +>1 + `${ 3 * 4 }5` : string +>3 * 4 : number + +var d3 = 1 + `2${ 3 * 4 }5`; +>d3 : string +>1 + `2${ 3 * 4 }5` : string +>3 * 4 : number + +var e3 = `${ 3 * 4 }` + 6; +>e3 : string +>`${ 3 * 4 }` + 6 : string +>3 * 4 : number + +var f3 = `2${ 3 * 4 }` + 6; +>f3 : string +>`2${ 3 * 4 }` + 6 : string +>3 * 4 : number + +var g3 = `${ 3 * 4 }5` + 6; +>g3 : string +>`${ 3 * 4 }5` + 6 : string +>3 * 4 : number + +var h3 = `2${ 3 * 4 }5` + 6; +>h3 : string +>`2${ 3 * 4 }5` + 6 : string +>3 * 4 : number + +var i3 = 1 + `${ 3 * 4 }` + 6; +>i3 : string +>1 + `${ 3 * 4 }` + 6 : string +>1 + `${ 3 * 4 }` : string +>3 * 4 : number + +var j3 = 1 + `2${ 3 * 4 }` + 6; +>j3 : string +>1 + `2${ 3 * 4 }` + 6 : string +>1 + `2${ 3 * 4 }` : string +>3 * 4 : number + +var k3 = 1 + `${ 3 * 4 }5` + 6; +>k3 : string +>1 + `${ 3 * 4 }5` + 6 : string +>1 + `${ 3 * 4 }5` : string +>3 * 4 : number + +var l3 = 1 + `2${ 3 * 4 }5` + 6; +>l3 : string +>1 + `2${ 3 * 4 }5` + 6 : string +>1 + `2${ 3 * 4 }5` : string +>3 * 4 : number + +var a4 = 1 + `${ 3 & 4 }`; +>a4 : string +>1 + `${ 3 & 4 }` : string +>3 & 4 : number + +var b4 = 1 + `2${ 3 & 4 }`; +>b4 : string +>1 + `2${ 3 & 4 }` : string +>3 & 4 : number + +var c4 = 1 + `${ 3 & 4 }5`; +>c4 : string +>1 + `${ 3 & 4 }5` : string +>3 & 4 : number + +var d4 = 1 + `2${ 3 & 4 }5`; +>d4 : string +>1 + `2${ 3 & 4 }5` : string +>3 & 4 : number + +var e4 = `${ 3 & 4 }` + 6; +>e4 : string +>`${ 3 & 4 }` + 6 : string +>3 & 4 : number + +var f4 = `2${ 3 & 4 }` + 6; +>f4 : string +>`2${ 3 & 4 }` + 6 : string +>3 & 4 : number + +var g4 = `${ 3 & 4 }5` + 6; +>g4 : string +>`${ 3 & 4 }5` + 6 : string +>3 & 4 : number + +var h4 = `2${ 3 & 4 }5` + 6; +>h4 : string +>`2${ 3 & 4 }5` + 6 : string +>3 & 4 : number + +var i4 = 1 + `${ 3 & 4 }` + 6; +>i4 : string +>1 + `${ 3 & 4 }` + 6 : string +>1 + `${ 3 & 4 }` : string +>3 & 4 : number + +var j4 = 1 + `2${ 3 & 4 }` + 6; +>j4 : string +>1 + `2${ 3 & 4 }` + 6 : string +>1 + `2${ 3 & 4 }` : string +>3 & 4 : number + +var k4 = 1 + `${ 3 & 4 }5` + 6; +>k4 : string +>1 + `${ 3 & 4 }5` + 6 : string +>1 + `${ 3 & 4 }5` : string +>3 & 4 : number + +var l4 = 1 + `2${ 3 & 4 }5` + 6; +>l4 : string +>1 + `2${ 3 & 4 }5` + 6 : string +>1 + `2${ 3 & 4 }5` : string +>3 & 4 : number + diff --git a/tests/baselines/reference/templateStringBinaryOperationsES6.js b/tests/baselines/reference/templateStringBinaryOperationsES6.js new file mode 100644 index 0000000000..8dcdd8a2aa --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsES6.js @@ -0,0 +1,103 @@ +//// [templateStringBinaryOperationsES6.ts] +var a = 1 + `${ 3 }`; +var b = 1 + `2${ 3 }`; +var c = 1 + `${ 3 }4`; +var d = 1 + `2${ 3 }4`; +var e = `${ 3 }` + 5; +var f = `2${ 3 }` + 5; +var g = `${ 3 }4` + 5; +var h = `2${ 3 }4` + 5; +var i = 1 + `${ 3 }` + 5; +var j = 1 + `2${ 3 }` + 5; +var k = 1 + `${ 3 }4` + 5; +var l = 1 + `2${ 3 }4` + 5; + +var a2 = 1 + `${ 3 - 4 }`; +var b2 = 1 + `2${ 3 - 4 }`; +var c2 = 1 + `${ 3 - 4 }5`; +var d2 = 1 + `2${ 3 - 4 }5`; +var e2 = `${ 3 - 4 }` + 6; +var f2 = `2${ 3 - 4 }` + 6; +var g2 = `${ 3 - 4 }5` + 6; +var h2 = `2${ 3 - 4 }5` + 6; +var i2 = 1 + `${ 3 - 4 }` + 6; +var j2 = 1 + `2${ 3 - 4 }` + 6; +var k2 = 1 + `${ 3 - 4 }5` + 6; +var l2 = 1 + `2${ 3 - 4 }5` + 6; + +var a3 = 1 + `${ 3 * 4 }`; +var b3 = 1 + `2${ 3 * 4 }`; +var c3 = 1 + `${ 3 * 4 }5`; +var d3 = 1 + `2${ 3 * 4 }5`; +var e3 = `${ 3 * 4 }` + 6; +var f3 = `2${ 3 * 4 }` + 6; +var g3 = `${ 3 * 4 }5` + 6; +var h3 = `2${ 3 * 4 }5` + 6; +var i3 = 1 + `${ 3 * 4 }` + 6; +var j3 = 1 + `2${ 3 * 4 }` + 6; +var k3 = 1 + `${ 3 * 4 }5` + 6; +var l3 = 1 + `2${ 3 * 4 }5` + 6; + +var a4 = 1 + `${ 3 & 4 }`; +var b4 = 1 + `2${ 3 & 4 }`; +var c4 = 1 + `${ 3 & 4 }5`; +var d4 = 1 + `2${ 3 & 4 }5`; +var e4 = `${ 3 & 4 }` + 6; +var f4 = `2${ 3 & 4 }` + 6; +var g4 = `${ 3 & 4 }5` + 6; +var h4 = `2${ 3 & 4 }5` + 6; +var i4 = 1 + `${ 3 & 4 }` + 6; +var j4 = 1 + `2${ 3 & 4 }` + 6; +var k4 = 1 + `${ 3 & 4 }5` + 6; +var l4 = 1 + `2${ 3 & 4 }5` + 6; + + +//// [templateStringBinaryOperationsES6.js] +var a = 1 + `${3}`; +var b = 1 + `2${3}`; +var c = 1 + `${3}4`; +var d = 1 + `2${3}4`; +var e = `${3}` + 5; +var f = `2${3}` + 5; +var g = `${3}4` + 5; +var h = `2${3}4` + 5; +var i = 1 + `${3}` + 5; +var j = 1 + `2${3}` + 5; +var k = 1 + `${3}4` + 5; +var l = 1 + `2${3}4` + 5; +var a2 = 1 + `${3 - 4}`; +var b2 = 1 + `2${3 - 4}`; +var c2 = 1 + `${3 - 4}5`; +var d2 = 1 + `2${3 - 4}5`; +var e2 = `${3 - 4}` + 6; +var f2 = `2${3 - 4}` + 6; +var g2 = `${3 - 4}5` + 6; +var h2 = `2${3 - 4}5` + 6; +var i2 = 1 + `${3 - 4}` + 6; +var j2 = 1 + `2${3 - 4}` + 6; +var k2 = 1 + `${3 - 4}5` + 6; +var l2 = 1 + `2${3 - 4}5` + 6; +var a3 = 1 + `${3 * 4}`; +var b3 = 1 + `2${3 * 4}`; +var c3 = 1 + `${3 * 4}5`; +var d3 = 1 + `2${3 * 4}5`; +var e3 = `${3 * 4}` + 6; +var f3 = `2${3 * 4}` + 6; +var g3 = `${3 * 4}5` + 6; +var h3 = `2${3 * 4}5` + 6; +var i3 = 1 + `${3 * 4}` + 6; +var j3 = 1 + `2${3 * 4}` + 6; +var k3 = 1 + `${3 * 4}5` + 6; +var l3 = 1 + `2${3 * 4}5` + 6; +var a4 = 1 + `${3 & 4}`; +var b4 = 1 + `2${3 & 4}`; +var c4 = 1 + `${3 & 4}5`; +var d4 = 1 + `2${3 & 4}5`; +var e4 = `${3 & 4}` + 6; +var f4 = `2${3 & 4}` + 6; +var g4 = `${3 & 4}5` + 6; +var h4 = `2${3 & 4}5` + 6; +var i4 = 1 + `${3 & 4}` + 6; +var j4 = 1 + `2${3 & 4}` + 6; +var k4 = 1 + `${3 & 4}5` + 6; +var l4 = 1 + `2${3 & 4}5` + 6; diff --git a/tests/baselines/reference/templateStringBinaryOperationsES6.types b/tests/baselines/reference/templateStringBinaryOperationsES6.types new file mode 100644 index 0000000000..a79885904e --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsES6.types @@ -0,0 +1,245 @@ +=== tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6.ts === +var a = 1 + `${ 3 }`; +>a : string +>1 + `${ 3 }` : string + +var b = 1 + `2${ 3 }`; +>b : string +>1 + `2${ 3 }` : string + +var c = 1 + `${ 3 }4`; +>c : string +>1 + `${ 3 }4` : string + +var d = 1 + `2${ 3 }4`; +>d : string +>1 + `2${ 3 }4` : string + +var e = `${ 3 }` + 5; +>e : string +>`${ 3 }` + 5 : string + +var f = `2${ 3 }` + 5; +>f : string +>`2${ 3 }` + 5 : string + +var g = `${ 3 }4` + 5; +>g : string +>`${ 3 }4` + 5 : string + +var h = `2${ 3 }4` + 5; +>h : string +>`2${ 3 }4` + 5 : string + +var i = 1 + `${ 3 }` + 5; +>i : string +>1 + `${ 3 }` + 5 : string +>1 + `${ 3 }` : string + +var j = 1 + `2${ 3 }` + 5; +>j : string +>1 + `2${ 3 }` + 5 : string +>1 + `2${ 3 }` : string + +var k = 1 + `${ 3 }4` + 5; +>k : string +>1 + `${ 3 }4` + 5 : string +>1 + `${ 3 }4` : string + +var l = 1 + `2${ 3 }4` + 5; +>l : string +>1 + `2${ 3 }4` + 5 : string +>1 + `2${ 3 }4` : string + +var a2 = 1 + `${ 3 - 4 }`; +>a2 : string +>1 + `${ 3 - 4 }` : string +>3 - 4 : number + +var b2 = 1 + `2${ 3 - 4 }`; +>b2 : string +>1 + `2${ 3 - 4 }` : string +>3 - 4 : number + +var c2 = 1 + `${ 3 - 4 }5`; +>c2 : string +>1 + `${ 3 - 4 }5` : string +>3 - 4 : number + +var d2 = 1 + `2${ 3 - 4 }5`; +>d2 : string +>1 + `2${ 3 - 4 }5` : string +>3 - 4 : number + +var e2 = `${ 3 - 4 }` + 6; +>e2 : string +>`${ 3 - 4 }` + 6 : string +>3 - 4 : number + +var f2 = `2${ 3 - 4 }` + 6; +>f2 : string +>`2${ 3 - 4 }` + 6 : string +>3 - 4 : number + +var g2 = `${ 3 - 4 }5` + 6; +>g2 : string +>`${ 3 - 4 }5` + 6 : string +>3 - 4 : number + +var h2 = `2${ 3 - 4 }5` + 6; +>h2 : string +>`2${ 3 - 4 }5` + 6 : string +>3 - 4 : number + +var i2 = 1 + `${ 3 - 4 }` + 6; +>i2 : string +>1 + `${ 3 - 4 }` + 6 : string +>1 + `${ 3 - 4 }` : string +>3 - 4 : number + +var j2 = 1 + `2${ 3 - 4 }` + 6; +>j2 : string +>1 + `2${ 3 - 4 }` + 6 : string +>1 + `2${ 3 - 4 }` : string +>3 - 4 : number + +var k2 = 1 + `${ 3 - 4 }5` + 6; +>k2 : string +>1 + `${ 3 - 4 }5` + 6 : string +>1 + `${ 3 - 4 }5` : string +>3 - 4 : number + +var l2 = 1 + `2${ 3 - 4 }5` + 6; +>l2 : string +>1 + `2${ 3 - 4 }5` + 6 : string +>1 + `2${ 3 - 4 }5` : string +>3 - 4 : number + +var a3 = 1 + `${ 3 * 4 }`; +>a3 : string +>1 + `${ 3 * 4 }` : string +>3 * 4 : number + +var b3 = 1 + `2${ 3 * 4 }`; +>b3 : string +>1 + `2${ 3 * 4 }` : string +>3 * 4 : number + +var c3 = 1 + `${ 3 * 4 }5`; +>c3 : string +>1 + `${ 3 * 4 }5` : string +>3 * 4 : number + +var d3 = 1 + `2${ 3 * 4 }5`; +>d3 : string +>1 + `2${ 3 * 4 }5` : string +>3 * 4 : number + +var e3 = `${ 3 * 4 }` + 6; +>e3 : string +>`${ 3 * 4 }` + 6 : string +>3 * 4 : number + +var f3 = `2${ 3 * 4 }` + 6; +>f3 : string +>`2${ 3 * 4 }` + 6 : string +>3 * 4 : number + +var g3 = `${ 3 * 4 }5` + 6; +>g3 : string +>`${ 3 * 4 }5` + 6 : string +>3 * 4 : number + +var h3 = `2${ 3 * 4 }5` + 6; +>h3 : string +>`2${ 3 * 4 }5` + 6 : string +>3 * 4 : number + +var i3 = 1 + `${ 3 * 4 }` + 6; +>i3 : string +>1 + `${ 3 * 4 }` + 6 : string +>1 + `${ 3 * 4 }` : string +>3 * 4 : number + +var j3 = 1 + `2${ 3 * 4 }` + 6; +>j3 : string +>1 + `2${ 3 * 4 }` + 6 : string +>1 + `2${ 3 * 4 }` : string +>3 * 4 : number + +var k3 = 1 + `${ 3 * 4 }5` + 6; +>k3 : string +>1 + `${ 3 * 4 }5` + 6 : string +>1 + `${ 3 * 4 }5` : string +>3 * 4 : number + +var l3 = 1 + `2${ 3 * 4 }5` + 6; +>l3 : string +>1 + `2${ 3 * 4 }5` + 6 : string +>1 + `2${ 3 * 4 }5` : string +>3 * 4 : number + +var a4 = 1 + `${ 3 & 4 }`; +>a4 : string +>1 + `${ 3 & 4 }` : string +>3 & 4 : number + +var b4 = 1 + `2${ 3 & 4 }`; +>b4 : string +>1 + `2${ 3 & 4 }` : string +>3 & 4 : number + +var c4 = 1 + `${ 3 & 4 }5`; +>c4 : string +>1 + `${ 3 & 4 }5` : string +>3 & 4 : number + +var d4 = 1 + `2${ 3 & 4 }5`; +>d4 : string +>1 + `2${ 3 & 4 }5` : string +>3 & 4 : number + +var e4 = `${ 3 & 4 }` + 6; +>e4 : string +>`${ 3 & 4 }` + 6 : string +>3 & 4 : number + +var f4 = `2${ 3 & 4 }` + 6; +>f4 : string +>`2${ 3 & 4 }` + 6 : string +>3 & 4 : number + +var g4 = `${ 3 & 4 }5` + 6; +>g4 : string +>`${ 3 & 4 }5` + 6 : string +>3 & 4 : number + +var h4 = `2${ 3 & 4 }5` + 6; +>h4 : string +>`2${ 3 & 4 }5` + 6 : string +>3 & 4 : number + +var i4 = 1 + `${ 3 & 4 }` + 6; +>i4 : string +>1 + `${ 3 & 4 }` + 6 : string +>1 + `${ 3 & 4 }` : string +>3 & 4 : number + +var j4 = 1 + `2${ 3 & 4 }` + 6; +>j4 : string +>1 + `2${ 3 & 4 }` + 6 : string +>1 + `2${ 3 & 4 }` : string +>3 & 4 : number + +var k4 = 1 + `${ 3 & 4 }5` + 6; +>k4 : string +>1 + `${ 3 & 4 }5` + 6 : string +>1 + `${ 3 & 4 }5` : string +>3 & 4 : number + +var l4 = 1 + `2${ 3 & 4 }5` + 6; +>l4 : string +>1 + `2${ 3 & 4 }5` + 6 : string +>1 + `2${ 3 & 4 }5` : string +>3 & 4 : number + diff --git a/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt new file mode 100644 index 0000000000..261eb6bd55 --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.errors.txt @@ -0,0 +1,399 @@ +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + +==== tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts (96 errors) ==== + var a = 1 - `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b = 1 - `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c = 1 - `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d = 1 - `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e = `${ 3 }` - 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f = `2${ 3 }` - 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g = `${ 3 }4` - 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h = `2${ 3 }4` - 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a2 = 1 * `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b2 = 1 * `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c2 = 1 * `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d2 = 1 * `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e2 = `${ 3 }` * 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f2 = `2${ 3 }` * 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g2 = `${ 3 }4` * 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h2 = `2${ 3 }4` * 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a3 = 1 & `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b3 = 1 & `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c3 = 1 & `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d3 = 1 & `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e3 = `${ 3 }` & 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f3 = `2${ 3 }` & 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g3 = `${ 3 }4` & 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h3 = `2${ 3 }4` & 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a4 = 1 - `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b4 = 1 - `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c4 = 1 - `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d4 = 1 - `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e4 = `${ 3 - 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f4 = `2${ 3 - 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g4 = `${ 3 - 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h4 = `2${ 3 - 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a5 = 1 - `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b5 = 1 - `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c5 = 1 - `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d5 = 1 - `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e5 = `${ 3 * 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f5 = `2${ 3 * 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g5 = `${ 3 * 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h5 = `2${ 3 * 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a6 = 1 - `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b6 = 1 - `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c6 = 1 - `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d6 = 1 - `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e6 = `${ 3 & 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f6 = `2${ 3 & 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g6 = `${ 3 & 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h6 = `2${ 3 & 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a7 = 1 * `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b7 = 1 * `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c7 = 1 * `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d7 = 1 * `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e7 = `${ 3 - 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f7 = `2${ 3 - 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g7 = `${ 3 - 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h7 = `2${ 3 - 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a8 = 1 * `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b8 = 1 * `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c8 = 1 * `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d8 = 1 * `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e8 = `${ 3 * 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f8 = `2${ 3 * 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g8 = `${ 3 * 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h8 = `2${ 3 * 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a9 = 1 * `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b9 = 1 * `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c9 = 1 * `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d9 = 1 * `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e9 = `${ 3 & 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f9 = `2${ 3 & 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g9 = `${ 3 & 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h9 = `2${ 3 & 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var aa = 1 & `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ba = 1 & `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ca = 1 & `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var da = 1 & `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ea = `${ 3 - 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fa = `2${ 3 - 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ga = `${ 3 - 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ha = `2${ 3 - 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var ab = 1 & `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var bb = 1 & `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var cb = 1 & `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var db = 1 & `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var eb = `${ 3 * 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fb = `2${ 3 * 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var gb = `${ 3 * 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var hb = `2${ 3 * 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var ac = 1 & `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var bc = 1 & `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var cc = 1 & `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var dc = 1 & `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ec = `${ 3 & 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fc = `2${ 3 & 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var gc = `${ 3 & 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var hc = `2${ 3 & 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + \ No newline at end of file diff --git a/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.js b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.js new file mode 100644 index 0000000000..4408fd1ffe --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsES6Invalid.js @@ -0,0 +1,207 @@ +//// [templateStringBinaryOperationsES6Invalid.ts] +var a = 1 - `${ 3 }`; +var b = 1 - `2${ 3 }`; +var c = 1 - `${ 3 }4`; +var d = 1 - `2${ 3 }4`; +var e = `${ 3 }` - 5; +var f = `2${ 3 }` - 5; +var g = `${ 3 }4` - 5; +var h = `2${ 3 }4` - 5; + +var a2 = 1 * `${ 3 }`; +var b2 = 1 * `2${ 3 }`; +var c2 = 1 * `${ 3 }4`; +var d2 = 1 * `2${ 3 }4`; +var e2 = `${ 3 }` * 5; +var f2 = `2${ 3 }` * 5; +var g2 = `${ 3 }4` * 5; +var h2 = `2${ 3 }4` * 5; + +var a3 = 1 & `${ 3 }`; +var b3 = 1 & `2${ 3 }`; +var c3 = 1 & `${ 3 }4`; +var d3 = 1 & `2${ 3 }4`; +var e3 = `${ 3 }` & 5; +var f3 = `2${ 3 }` & 5; +var g3 = `${ 3 }4` & 5; +var h3 = `2${ 3 }4` & 5; + +var a4 = 1 - `${ 3 - 4 }`; +var b4 = 1 - `2${ 3 - 4 }`; +var c4 = 1 - `${ 3 - 4 }5`; +var d4 = 1 - `2${ 3 - 4 }5`; +var e4 = `${ 3 - 4 }` - 6; +var f4 = `2${ 3 - 4 }` - 6; +var g4 = `${ 3 - 4 }5` - 6; +var h4 = `2${ 3 - 4 }5` - 6; + +var a5 = 1 - `${ 3 * 4 }`; +var b5 = 1 - `2${ 3 * 4 }`; +var c5 = 1 - `${ 3 * 4 }5`; +var d5 = 1 - `2${ 3 * 4 }5`; +var e5 = `${ 3 * 4 }` - 6; +var f5 = `2${ 3 * 4 }` - 6; +var g5 = `${ 3 * 4 }5` - 6; +var h5 = `2${ 3 * 4 }5` - 6; + +var a6 = 1 - `${ 3 & 4 }`; +var b6 = 1 - `2${ 3 & 4 }`; +var c6 = 1 - `${ 3 & 4 }5`; +var d6 = 1 - `2${ 3 & 4 }5`; +var e6 = `${ 3 & 4 }` - 6; +var f6 = `2${ 3 & 4 }` - 6; +var g6 = `${ 3 & 4 }5` - 6; +var h6 = `2${ 3 & 4 }5` - 6; + +var a7 = 1 * `${ 3 - 4 }`; +var b7 = 1 * `2${ 3 - 4 }`; +var c7 = 1 * `${ 3 - 4 }5`; +var d7 = 1 * `2${ 3 - 4 }5`; +var e7 = `${ 3 - 4 }` * 6; +var f7 = `2${ 3 - 4 }` * 6; +var g7 = `${ 3 - 4 }5` * 6; +var h7 = `2${ 3 - 4 }5` * 6; + +var a8 = 1 * `${ 3 * 4 }`; +var b8 = 1 * `2${ 3 * 4 }`; +var c8 = 1 * `${ 3 * 4 }5`; +var d8 = 1 * `2${ 3 * 4 }5`; +var e8 = `${ 3 * 4 }` * 6; +var f8 = `2${ 3 * 4 }` * 6; +var g8 = `${ 3 * 4 }5` * 6; +var h8 = `2${ 3 * 4 }5` * 6; + +var a9 = 1 * `${ 3 & 4 }`; +var b9 = 1 * `2${ 3 & 4 }`; +var c9 = 1 * `${ 3 & 4 }5`; +var d9 = 1 * `2${ 3 & 4 }5`; +var e9 = `${ 3 & 4 }` * 6; +var f9 = `2${ 3 & 4 }` * 6; +var g9 = `${ 3 & 4 }5` * 6; +var h9 = `2${ 3 & 4 }5` * 6; + +var aa = 1 & `${ 3 - 4 }`; +var ba = 1 & `2${ 3 - 4 }`; +var ca = 1 & `${ 3 - 4 }5`; +var da = 1 & `2${ 3 - 4 }5`; +var ea = `${ 3 - 4 }` & 6; +var fa = `2${ 3 - 4 }` & 6; +var ga = `${ 3 - 4 }5` & 6; +var ha = `2${ 3 - 4 }5` & 6; + +var ab = 1 & `${ 3 * 4 }`; +var bb = 1 & `2${ 3 * 4 }`; +var cb = 1 & `${ 3 * 4 }5`; +var db = 1 & `2${ 3 * 4 }5`; +var eb = `${ 3 * 4 }` & 6; +var fb = `2${ 3 * 4 }` & 6; +var gb = `${ 3 * 4 }5` & 6; +var hb = `2${ 3 * 4 }5` & 6; + +var ac = 1 & `${ 3 & 4 }`; +var bc = 1 & `2${ 3 & 4 }`; +var cc = 1 & `${ 3 & 4 }5`; +var dc = 1 & `2${ 3 & 4 }5`; +var ec = `${ 3 & 4 }` & 6; +var fc = `2${ 3 & 4 }` & 6; +var gc = `${ 3 & 4 }5` & 6; +var hc = `2${ 3 & 4 }5` & 6; + + +//// [templateStringBinaryOperationsES6Invalid.js] +var a = 1 - `${3}`; +var b = 1 - `2${3}`; +var c = 1 - `${3}4`; +var d = 1 - `2${3}4`; +var e = `${3}` - 5; +var f = `2${3}` - 5; +var g = `${3}4` - 5; +var h = `2${3}4` - 5; +var a2 = 1 * `${3}`; +var b2 = 1 * `2${3}`; +var c2 = 1 * `${3}4`; +var d2 = 1 * `2${3}4`; +var e2 = `${3}` * 5; +var f2 = `2${3}` * 5; +var g2 = `${3}4` * 5; +var h2 = `2${3}4` * 5; +var a3 = 1 & `${3}`; +var b3 = 1 & `2${3}`; +var c3 = 1 & `${3}4`; +var d3 = 1 & `2${3}4`; +var e3 = `${3}` & 5; +var f3 = `2${3}` & 5; +var g3 = `${3}4` & 5; +var h3 = `2${3}4` & 5; +var a4 = 1 - `${3 - 4}`; +var b4 = 1 - `2${3 - 4}`; +var c4 = 1 - `${3 - 4}5`; +var d4 = 1 - `2${3 - 4}5`; +var e4 = `${3 - 4}` - 6; +var f4 = `2${3 - 4}` - 6; +var g4 = `${3 - 4}5` - 6; +var h4 = `2${3 - 4}5` - 6; +var a5 = 1 - `${3 * 4}`; +var b5 = 1 - `2${3 * 4}`; +var c5 = 1 - `${3 * 4}5`; +var d5 = 1 - `2${3 * 4}5`; +var e5 = `${3 * 4}` - 6; +var f5 = `2${3 * 4}` - 6; +var g5 = `${3 * 4}5` - 6; +var h5 = `2${3 * 4}5` - 6; +var a6 = 1 - `${3 & 4}`; +var b6 = 1 - `2${3 & 4}`; +var c6 = 1 - `${3 & 4}5`; +var d6 = 1 - `2${3 & 4}5`; +var e6 = `${3 & 4}` - 6; +var f6 = `2${3 & 4}` - 6; +var g6 = `${3 & 4}5` - 6; +var h6 = `2${3 & 4}5` - 6; +var a7 = 1 * `${3 - 4}`; +var b7 = 1 * `2${3 - 4}`; +var c7 = 1 * `${3 - 4}5`; +var d7 = 1 * `2${3 - 4}5`; +var e7 = `${3 - 4}` * 6; +var f7 = `2${3 - 4}` * 6; +var g7 = `${3 - 4}5` * 6; +var h7 = `2${3 - 4}5` * 6; +var a8 = 1 * `${3 * 4}`; +var b8 = 1 * `2${3 * 4}`; +var c8 = 1 * `${3 * 4}5`; +var d8 = 1 * `2${3 * 4}5`; +var e8 = `${3 * 4}` * 6; +var f8 = `2${3 * 4}` * 6; +var g8 = `${3 * 4}5` * 6; +var h8 = `2${3 * 4}5` * 6; +var a9 = 1 * `${3 & 4}`; +var b9 = 1 * `2${3 & 4}`; +var c9 = 1 * `${3 & 4}5`; +var d9 = 1 * `2${3 & 4}5`; +var e9 = `${3 & 4}` * 6; +var f9 = `2${3 & 4}` * 6; +var g9 = `${3 & 4}5` * 6; +var h9 = `2${3 & 4}5` * 6; +var aa = 1 & `${3 - 4}`; +var ba = 1 & `2${3 - 4}`; +var ca = 1 & `${3 - 4}5`; +var da = 1 & `2${3 - 4}5`; +var ea = `${3 - 4}` & 6; +var fa = `2${3 - 4}` & 6; +var ga = `${3 - 4}5` & 6; +var ha = `2${3 - 4}5` & 6; +var ab = 1 & `${3 * 4}`; +var bb = 1 & `2${3 * 4}`; +var cb = 1 & `${3 * 4}5`; +var db = 1 & `2${3 * 4}5`; +var eb = `${3 * 4}` & 6; +var fb = `2${3 * 4}` & 6; +var gb = `${3 * 4}5` & 6; +var hb = `2${3 * 4}5` & 6; +var ac = 1 & `${3 & 4}`; +var bc = 1 & `2${3 & 4}`; +var cc = 1 & `${3 & 4}5`; +var dc = 1 & `2${3 & 4}5`; +var ec = `${3 & 4}` & 6; +var fc = `2${3 & 4}` & 6; +var gc = `${3 & 4}5` & 6; +var hc = `2${3 & 4}5` & 6; diff --git a/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt b/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt new file mode 100644 index 0000000000..8a6a9719a5 --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsInvalid.errors.txt @@ -0,0 +1,399 @@ +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(1,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(2,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(3,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(4,13): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(5,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(6,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(7,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(8,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(10,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(11,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(12,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(13,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(14,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(15,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(16,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(17,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(19,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(20,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(21,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(22,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(23,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(24,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(25,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(26,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(28,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(29,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(30,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(31,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(32,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(33,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(34,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(35,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(37,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(38,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(39,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(40,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(41,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(42,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(43,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(44,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(46,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(47,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(48,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(49,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(50,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(51,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(52,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(53,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(55,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(56,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(57,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(58,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(59,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(60,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(61,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(62,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(64,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(65,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(66,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(67,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(68,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(69,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(70,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(71,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(73,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(74,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(75,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(76,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(77,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(78,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(79,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(80,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(82,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(83,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(84,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(85,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(86,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(87,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(88,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(89,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(91,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(92,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(93,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(94,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(95,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(96,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(97,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(98,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(100,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(101,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(102,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(103,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(104,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(105,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(106,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts(107,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + +==== tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts (96 errors) ==== + var a = 1 - `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b = 1 - `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c = 1 - `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d = 1 - `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e = `${ 3 }` - 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f = `2${ 3 }` - 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g = `${ 3 }4` - 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h = `2${ 3 }4` - 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a2 = 1 * `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b2 = 1 * `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c2 = 1 * `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d2 = 1 * `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e2 = `${ 3 }` * 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f2 = `2${ 3 }` * 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g2 = `${ 3 }4` * 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h2 = `2${ 3 }4` * 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a3 = 1 & `${ 3 }`; + ~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b3 = 1 & `2${ 3 }`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c3 = 1 & `${ 3 }4`; + ~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d3 = 1 & `2${ 3 }4`; + ~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e3 = `${ 3 }` & 5; + ~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f3 = `2${ 3 }` & 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g3 = `${ 3 }4` & 5; + ~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h3 = `2${ 3 }4` & 5; + ~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a4 = 1 - `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b4 = 1 - `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c4 = 1 - `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d4 = 1 - `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e4 = `${ 3 - 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f4 = `2${ 3 - 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g4 = `${ 3 - 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h4 = `2${ 3 - 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a5 = 1 - `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b5 = 1 - `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c5 = 1 - `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d5 = 1 - `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e5 = `${ 3 * 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f5 = `2${ 3 * 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g5 = `${ 3 * 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h5 = `2${ 3 * 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a6 = 1 - `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b6 = 1 - `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c6 = 1 - `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d6 = 1 - `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e6 = `${ 3 & 4 }` - 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f6 = `2${ 3 & 4 }` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g6 = `${ 3 & 4 }5` - 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h6 = `2${ 3 & 4 }5` - 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a7 = 1 * `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b7 = 1 * `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c7 = 1 * `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d7 = 1 * `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e7 = `${ 3 - 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f7 = `2${ 3 - 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g7 = `${ 3 - 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h7 = `2${ 3 - 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a8 = 1 * `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b8 = 1 * `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c8 = 1 * `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d8 = 1 * `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e8 = `${ 3 * 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f8 = `2${ 3 * 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g8 = `${ 3 * 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h8 = `2${ 3 * 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var a9 = 1 * `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var b9 = 1 * `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var c9 = 1 * `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var d9 = 1 * `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var e9 = `${ 3 & 4 }` * 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var f9 = `2${ 3 & 4 }` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var g9 = `${ 3 & 4 }5` * 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var h9 = `2${ 3 & 4 }5` * 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var aa = 1 & `${ 3 - 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ba = 1 & `2${ 3 - 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ca = 1 & `${ 3 - 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var da = 1 & `2${ 3 - 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ea = `${ 3 - 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fa = `2${ 3 - 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ga = `${ 3 - 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ha = `2${ 3 - 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var ab = 1 & `${ 3 * 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var bb = 1 & `2${ 3 * 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var cb = 1 & `${ 3 * 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var db = 1 & `2${ 3 * 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var eb = `${ 3 * 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fb = `2${ 3 * 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var gb = `${ 3 * 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var hb = `2${ 3 * 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + + var ac = 1 & `${ 3 & 4 }`; + ~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var bc = 1 & `2${ 3 & 4 }`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var cc = 1 & `${ 3 & 4 }5`; + ~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var dc = 1 & `2${ 3 & 4 }5`; + ~~~~~~~~~~~~~~ +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var ec = `${ 3 & 4 }` & 6; + ~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var fc = `2${ 3 & 4 }` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var gc = `${ 3 & 4 }5` & 6; + ~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + var hc = `2${ 3 & 4 }5` & 6; + ~~~~~~~~~~~~~~ +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. + \ No newline at end of file diff --git a/tests/baselines/reference/templateStringBinaryOperationsInvalid.js b/tests/baselines/reference/templateStringBinaryOperationsInvalid.js new file mode 100644 index 0000000000..f8c0344f44 --- /dev/null +++ b/tests/baselines/reference/templateStringBinaryOperationsInvalid.js @@ -0,0 +1,207 @@ +//// [templateStringBinaryOperationsInvalid.ts] +var a = 1 - `${ 3 }`; +var b = 1 - `2${ 3 }`; +var c = 1 - `${ 3 }4`; +var d = 1 - `2${ 3 }4`; +var e = `${ 3 }` - 5; +var f = `2${ 3 }` - 5; +var g = `${ 3 }4` - 5; +var h = `2${ 3 }4` - 5; + +var a2 = 1 * `${ 3 }`; +var b2 = 1 * `2${ 3 }`; +var c2 = 1 * `${ 3 }4`; +var d2 = 1 * `2${ 3 }4`; +var e2 = `${ 3 }` * 5; +var f2 = `2${ 3 }` * 5; +var g2 = `${ 3 }4` * 5; +var h2 = `2${ 3 }4` * 5; + +var a3 = 1 & `${ 3 }`; +var b3 = 1 & `2${ 3 }`; +var c3 = 1 & `${ 3 }4`; +var d3 = 1 & `2${ 3 }4`; +var e3 = `${ 3 }` & 5; +var f3 = `2${ 3 }` & 5; +var g3 = `${ 3 }4` & 5; +var h3 = `2${ 3 }4` & 5; + +var a4 = 1 - `${ 3 - 4 }`; +var b4 = 1 - `2${ 3 - 4 }`; +var c4 = 1 - `${ 3 - 4 }5`; +var d4 = 1 - `2${ 3 - 4 }5`; +var e4 = `${ 3 - 4 }` - 6; +var f4 = `2${ 3 - 4 }` - 6; +var g4 = `${ 3 - 4 }5` - 6; +var h4 = `2${ 3 - 4 }5` - 6; + +var a5 = 1 - `${ 3 * 4 }`; +var b5 = 1 - `2${ 3 * 4 }`; +var c5 = 1 - `${ 3 * 4 }5`; +var d5 = 1 - `2${ 3 * 4 }5`; +var e5 = `${ 3 * 4 }` - 6; +var f5 = `2${ 3 * 4 }` - 6; +var g5 = `${ 3 * 4 }5` - 6; +var h5 = `2${ 3 * 4 }5` - 6; + +var a6 = 1 - `${ 3 & 4 }`; +var b6 = 1 - `2${ 3 & 4 }`; +var c6 = 1 - `${ 3 & 4 }5`; +var d6 = 1 - `2${ 3 & 4 }5`; +var e6 = `${ 3 & 4 }` - 6; +var f6 = `2${ 3 & 4 }` - 6; +var g6 = `${ 3 & 4 }5` - 6; +var h6 = `2${ 3 & 4 }5` - 6; + +var a7 = 1 * `${ 3 - 4 }`; +var b7 = 1 * `2${ 3 - 4 }`; +var c7 = 1 * `${ 3 - 4 }5`; +var d7 = 1 * `2${ 3 - 4 }5`; +var e7 = `${ 3 - 4 }` * 6; +var f7 = `2${ 3 - 4 }` * 6; +var g7 = `${ 3 - 4 }5` * 6; +var h7 = `2${ 3 - 4 }5` * 6; + +var a8 = 1 * `${ 3 * 4 }`; +var b8 = 1 * `2${ 3 * 4 }`; +var c8 = 1 * `${ 3 * 4 }5`; +var d8 = 1 * `2${ 3 * 4 }5`; +var e8 = `${ 3 * 4 }` * 6; +var f8 = `2${ 3 * 4 }` * 6; +var g8 = `${ 3 * 4 }5` * 6; +var h8 = `2${ 3 * 4 }5` * 6; + +var a9 = 1 * `${ 3 & 4 }`; +var b9 = 1 * `2${ 3 & 4 }`; +var c9 = 1 * `${ 3 & 4 }5`; +var d9 = 1 * `2${ 3 & 4 }5`; +var e9 = `${ 3 & 4 }` * 6; +var f9 = `2${ 3 & 4 }` * 6; +var g9 = `${ 3 & 4 }5` * 6; +var h9 = `2${ 3 & 4 }5` * 6; + +var aa = 1 & `${ 3 - 4 }`; +var ba = 1 & `2${ 3 - 4 }`; +var ca = 1 & `${ 3 - 4 }5`; +var da = 1 & `2${ 3 - 4 }5`; +var ea = `${ 3 - 4 }` & 6; +var fa = `2${ 3 - 4 }` & 6; +var ga = `${ 3 - 4 }5` & 6; +var ha = `2${ 3 - 4 }5` & 6; + +var ab = 1 & `${ 3 * 4 }`; +var bb = 1 & `2${ 3 * 4 }`; +var cb = 1 & `${ 3 * 4 }5`; +var db = 1 & `2${ 3 * 4 }5`; +var eb = `${ 3 * 4 }` & 6; +var fb = `2${ 3 * 4 }` & 6; +var gb = `${ 3 * 4 }5` & 6; +var hb = `2${ 3 * 4 }5` & 6; + +var ac = 1 & `${ 3 & 4 }`; +var bc = 1 & `2${ 3 & 4 }`; +var cc = 1 & `${ 3 & 4 }5`; +var dc = 1 & `2${ 3 & 4 }5`; +var ec = `${ 3 & 4 }` & 6; +var fc = `2${ 3 & 4 }` & 6; +var gc = `${ 3 & 4 }5` & 6; +var hc = `2${ 3 & 4 }5` & 6; + + +//// [templateStringBinaryOperationsInvalid.js] +var a = 1 - ("" + 3); +var b = 1 - ("2" + 3); +var c = 1 - (3 + "4"); +var d = 1 - ("2" + 3 + "4"); +var e = ("" + 3) - 5; +var f = ("2" + 3) - 5; +var g = (3 + "4") - 5; +var h = ("2" + 3 + "4") - 5; +var a2 = 1 * ("" + 3); +var b2 = 1 * ("2" + 3); +var c2 = 1 * (3 + "4"); +var d2 = 1 * ("2" + 3 + "4"); +var e2 = ("" + 3) * 5; +var f2 = ("2" + 3) * 5; +var g2 = (3 + "4") * 5; +var h2 = ("2" + 3 + "4") * 5; +var a3 = 1 & "" + 3; +var b3 = 1 & "2" + 3; +var c3 = 1 & 3 + "4"; +var d3 = 1 & "2" + 3 + "4"; +var e3 = "" + 3 & 5; +var f3 = "2" + 3 & 5; +var g3 = 3 + "4" & 5; +var h3 = "2" + 3 + "4" & 5; +var a4 = 1 - ("" + (3 - 4)); +var b4 = 1 - ("2" + (3 - 4)); +var c4 = 1 - ((3 - 4) + "5"); +var d4 = 1 - ("2" + (3 - 4) + "5"); +var e4 = ("" + (3 - 4)) - 6; +var f4 = ("2" + (3 - 4)) - 6; +var g4 = ((3 - 4) + "5") - 6; +var h4 = ("2" + (3 - 4) + "5") - 6; +var a5 = 1 - ("" + 3 * 4); +var b5 = 1 - ("2" + 3 * 4); +var c5 = 1 - (3 * 4 + "5"); +var d5 = 1 - ("2" + 3 * 4 + "5"); +var e5 = ("" + 3 * 4) - 6; +var f5 = ("2" + 3 * 4) - 6; +var g5 = (3 * 4 + "5") - 6; +var h5 = ("2" + 3 * 4 + "5") - 6; +var a6 = 1 - ("" + (3 & 4)); +var b6 = 1 - ("2" + (3 & 4)); +var c6 = 1 - ((3 & 4) + "5"); +var d6 = 1 - ("2" + (3 & 4) + "5"); +var e6 = ("" + (3 & 4)) - 6; +var f6 = ("2" + (3 & 4)) - 6; +var g6 = ((3 & 4) + "5") - 6; +var h6 = ("2" + (3 & 4) + "5") - 6; +var a7 = 1 * ("" + (3 - 4)); +var b7 = 1 * ("2" + (3 - 4)); +var c7 = 1 * ((3 - 4) + "5"); +var d7 = 1 * ("2" + (3 - 4) + "5"); +var e7 = ("" + (3 - 4)) * 6; +var f7 = ("2" + (3 - 4)) * 6; +var g7 = ((3 - 4) + "5") * 6; +var h7 = ("2" + (3 - 4) + "5") * 6; +var a8 = 1 * ("" + 3 * 4); +var b8 = 1 * ("2" + 3 * 4); +var c8 = 1 * (3 * 4 + "5"); +var d8 = 1 * ("2" + 3 * 4 + "5"); +var e8 = ("" + 3 * 4) * 6; +var f8 = ("2" + 3 * 4) * 6; +var g8 = (3 * 4 + "5") * 6; +var h8 = ("2" + 3 * 4 + "5") * 6; +var a9 = 1 * ("" + (3 & 4)); +var b9 = 1 * ("2" + (3 & 4)); +var c9 = 1 * ((3 & 4) + "5"); +var d9 = 1 * ("2" + (3 & 4) + "5"); +var e9 = ("" + (3 & 4)) * 6; +var f9 = ("2" + (3 & 4)) * 6; +var g9 = ((3 & 4) + "5") * 6; +var h9 = ("2" + (3 & 4) + "5") * 6; +var aa = 1 & "" + (3 - 4); +var ba = 1 & "2" + (3 - 4); +var ca = 1 & (3 - 4) + "5"; +var da = 1 & "2" + (3 - 4) + "5"; +var ea = "" + (3 - 4) & 6; +var fa = "2" + (3 - 4) & 6; +var ga = (3 - 4) + "5" & 6; +var ha = "2" + (3 - 4) + "5" & 6; +var ab = 1 & "" + 3 * 4; +var bb = 1 & "2" + 3 * 4; +var cb = 1 & 3 * 4 + "5"; +var db = 1 & "2" + 3 * 4 + "5"; +var eb = "" + 3 * 4 & 6; +var fb = "2" + 3 * 4 & 6; +var gb = 3 * 4 + "5" & 6; +var hb = "2" + 3 * 4 + "5" & 6; +var ac = 1 & "" + (3 & 4); +var bc = 1 & "2" + (3 & 4); +var cc = 1 & (3 & 4) + "5"; +var dc = 1 & "2" + (3 & 4) + "5"; +var ec = "" + (3 & 4) & 6; +var fc = "2" + (3 & 4) & 6; +var gc = (3 & 4) + "5" & 6; +var hc = "2" + (3 & 4) + "5" & 6; diff --git a/tests/baselines/reference/templateStringInBinaryAddition.js b/tests/baselines/reference/templateStringInBinaryAddition.js deleted file mode 100644 index 0e1f728005..0000000000 --- a/tests/baselines/reference/templateStringInBinaryAddition.js +++ /dev/null @@ -1,5 +0,0 @@ -//// [templateStringInBinaryAddition.ts] -var x = 10 + `abc${ 10 }def`; - -//// [templateStringInBinaryAddition.js] -var x = 10 + ("abc" + 10 + "def"); diff --git a/tests/baselines/reference/templateStringInBinaryAddition.types b/tests/baselines/reference/templateStringInBinaryAddition.types deleted file mode 100644 index f722ff696f..0000000000 --- a/tests/baselines/reference/templateStringInBinaryAddition.types +++ /dev/null @@ -1,5 +0,0 @@ -=== tests/cases/conformance/es6/templates/templateStringInBinaryAddition.ts === -var x = 10 + `abc${ 10 }def`; ->x : string ->10 + `abc${ 10 }def` : string - diff --git a/tests/baselines/reference/templateStringInBinaryAdditionES6.js b/tests/baselines/reference/templateStringInBinaryAdditionES6.js deleted file mode 100644 index 7a40d4cc54..0000000000 --- a/tests/baselines/reference/templateStringInBinaryAdditionES6.js +++ /dev/null @@ -1,5 +0,0 @@ -//// [templateStringInBinaryAdditionES6.ts] -var x = 10 + `abc${ 10 }def`; - -//// [templateStringInBinaryAdditionES6.js] -var x = 10 + `abc${10}def`; diff --git a/tests/baselines/reference/templateStringInBinaryAdditionES6.types b/tests/baselines/reference/templateStringInBinaryAdditionES6.types deleted file mode 100644 index b421d7dc70..0000000000 --- a/tests/baselines/reference/templateStringInBinaryAdditionES6.types +++ /dev/null @@ -1,5 +0,0 @@ -=== tests/cases/conformance/es6/templates/templateStringInBinaryAdditionES6.ts === -var x = 10 + `abc${ 10 }def`; ->x : string ->10 + `abc${ 10 }def` : string - diff --git a/tests/baselines/reference/templateStringWithEmptyLiteralPortions.js b/tests/baselines/reference/templateStringWithEmptyLiteralPortions.js index 8bc6e2c420..e7a35d76f4 100644 --- a/tests/baselines/reference/templateStringWithEmptyLiteralPortions.js +++ b/tests/baselines/reference/templateStringWithEmptyLiteralPortions.js @@ -21,18 +21,22 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; -var l = `1${ 0 }2${ 0 }3`; +var l = `${ 0 }2${ 0 }3`; + +var m = `1${ 0 }2${ 0 }3`; + //// [templateStringWithEmptyLiteralPortions.js] var a = ""; var b = "" + 0; var c = "1" + 0; -var d = "" + 0 + "2"; +var d = 0 + "2"; var e = "1" + 0 + "2"; var f = "" + 0 + 0; var g = "1" + 0 + 0; -var h = "" + 0 + "2" + 0; +var h = 0 + "2" + 0; var i = "1" + 0 + "2" + 0; var j = "" + 0 + 0 + "3"; var k = "1" + 0 + 0 + "3"; -var l = "1" + 0 + "2" + 0 + "3"; +var l = 0 + "2" + 0 + "3"; +var m = "1" + 0 + "2" + 0 + "3"; diff --git a/tests/baselines/reference/templateStringWithEmptyLiteralPortions.types b/tests/baselines/reference/templateStringWithEmptyLiteralPortions.types index a44bab8fe4..c901d67430 100644 --- a/tests/baselines/reference/templateStringWithEmptyLiteralPortions.types +++ b/tests/baselines/reference/templateStringWithEmptyLiteralPortions.types @@ -32,6 +32,9 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; >k : string -var l = `1${ 0 }2${ 0 }3`; +var l = `${ 0 }2${ 0 }3`; >l : string +var m = `1${ 0 }2${ 0 }3`; +>m : string + diff --git a/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.js b/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.js index f0e827cde6..fe1bce291f 100644 --- a/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.js +++ b/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.js @@ -21,7 +21,10 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; -var l = `1${ 0 }2${ 0 }3`; +var l = `${ 0 }2${ 0 }3`; + +var m = `1${ 0 }2${ 0 }3`; + //// [templateStringWithEmptyLiteralPortionsES6.js] var a = ``; @@ -35,4 +38,5 @@ var h = `${0}2${0}`; var i = `1${0}2${0}`; var j = `${0}${0}3`; var k = `1${0}${0}3`; -var l = `1${0}2${0}3`; +var l = `${0}2${0}3`; +var m = `1${0}2${0}3`; diff --git a/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.types b/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.types index 4074831d41..d70dd29e4d 100644 --- a/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.types +++ b/tests/baselines/reference/templateStringWithEmptyLiteralPortionsES6.types @@ -32,6 +32,9 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; >k : string -var l = `1${ 0 }2${ 0 }3`; +var l = `${ 0 }2${ 0 }3`; >l : string +var m = `1${ 0 }2${ 0 }3`; +>m : string + diff --git a/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt new file mode 100644 index 0000000000..7204f32dba --- /dev/null +++ b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.errors.txt @@ -0,0 +1,9 @@ +tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts(3,27): error TS2322: Type 'string' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts (1 errors) ==== + + + `${function (x: number) { x = "bad"; } }`; + ~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js new file mode 100644 index 0000000000..ef11331206 --- /dev/null +++ b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js @@ -0,0 +1,9 @@ +//// [templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts] + + +`${function (x: number) { x = "bad"; } }`; + +//// [templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.js] +"" + function (x) { + x = "bad"; +}; diff --git a/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt new file mode 100644 index 0000000000..9fece57ef5 --- /dev/null +++ b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.errors.txt @@ -0,0 +1,8 @@ +tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts(2,27): error TS2322: Type 'string' is not assignable to type 'number'. + + +==== tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts (1 errors) ==== + + `${function (x: number) { x = "bad"; } }`; + ~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js new file mode 100644 index 0000000000..9ce47348dc --- /dev/null +++ b/tests/baselines/reference/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js @@ -0,0 +1,8 @@ +//// [templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts] + +`${function (x: number) { x = "bad"; } }`; + +//// [templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.js] +`${function (x) { + x = "bad"; +}}`; diff --git a/tests/baselines/reference/visibilityOfTypeParameters.js b/tests/baselines/reference/visibilityOfTypeParameters.js new file mode 100644 index 0000000000..2cb006737b --- /dev/null +++ b/tests/baselines/reference/visibilityOfTypeParameters.js @@ -0,0 +1,24 @@ +//// [visibilityOfTypeParameters.ts] + +export class MyClass { + protected myMethod(val: T): T { + return val; + } +} + +//// [visibilityOfTypeParameters.js] +var MyClass = (function () { + function MyClass() { + } + MyClass.prototype.myMethod = function (val) { + return val; + }; + return MyClass; +})(); +exports.MyClass = MyClass; + + +//// [visibilityOfTypeParameters.d.ts] +export declare class MyClass { + protected myMethod(val: T): T; +} diff --git a/tests/baselines/reference/visibilityOfTypeParameters.types b/tests/baselines/reference/visibilityOfTypeParameters.types new file mode 100644 index 0000000000..60a9330eb7 --- /dev/null +++ b/tests/baselines/reference/visibilityOfTypeParameters.types @@ -0,0 +1,16 @@ +=== tests/cases/compiler/visibilityOfTypeParameters.ts === + +export class MyClass { +>MyClass : MyClass + + protected myMethod(val: T): T { +>myMethod : (val: T) => T +>T : T +>val : T +>T : T +>T : T + + return val; +>val : T + } +} diff --git a/tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts b/tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts new file mode 100644 index 0000000000..c6423ce41a --- /dev/null +++ b/tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts @@ -0,0 +1,16 @@ +// Non-ambient & instantiated module. +module Moclodule { + export interface Someinterface { + foo(): void; + } + var x = 10; +} + +class Moclodule { +} + +// Instantiated module. +module Moclodule { + export class Manager { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/cloduleWithPriorUninstantiatedModule.ts b/tests/cases/compiler/cloduleWithPriorUninstantiatedModule.ts new file mode 100644 index 0000000000..0c603b71a4 --- /dev/null +++ b/tests/cases/compiler/cloduleWithPriorUninstantiatedModule.ts @@ -0,0 +1,15 @@ +// Non-ambient & uninstantiated module. +module Moclodule { + export interface Someinterface { + foo(): void; + } +} + +class Moclodule { +} + +// Instantiated module. +module Moclodule { + export class Manager { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/conflictMarkerTrivia2.ts b/tests/cases/compiler/conflictMarkerTrivia2.ts new file mode 100644 index 0000000000..d40574c6e5 --- /dev/null +++ b/tests/cases/compiler/conflictMarkerTrivia2.ts @@ -0,0 +1,12 @@ +class C { + foo() { +<<<<<<< B + a(); + } +======= + b(); + } +>>>>>>> A + + public bar() { } +} diff --git a/tests/cases/compiler/functionsWithModifiersInBlocks1.ts b/tests/cases/compiler/functionsWithModifiersInBlocks1.ts new file mode 100644 index 0000000000..2a03d962ff --- /dev/null +++ b/tests/cases/compiler/functionsWithModifiersInBlocks1.ts @@ -0,0 +1,5 @@ +{ + declare function f() { } + export function f() { } + declare export function f() { } +} \ No newline at end of file diff --git a/tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts b/tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts new file mode 100644 index 0000000000..3e5aa480be --- /dev/null +++ b/tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts @@ -0,0 +1,8 @@ +interface Foo { + f(x: any): any; +} +interface Bar { + f(x: T): T; +} +interface Hello extends Foo, Bar { +} diff --git a/tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts b/tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts new file mode 100644 index 0000000000..f35e2ffda9 --- /dev/null +++ b/tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts @@ -0,0 +1,8 @@ +interface Foo { + f(x: any): any; +} +interface Bar { + f(x: T): T; +} +interface Hello extends Bar, Foo { +} diff --git a/tests/cases/compiler/inferenceFromParameterlessLambda.ts b/tests/cases/compiler/inferenceFromParameterlessLambda.ts new file mode 100644 index 0000000000..8585d4451f --- /dev/null +++ b/tests/cases/compiler/inferenceFromParameterlessLambda.ts @@ -0,0 +1,9 @@ +function foo(o: Take, i: Make) { } +interface Make { + (): T; +} +interface Take { + (n: T): void; +} +// Infer string from second argument because it isn't context sensitive +foo(n => n.length, () => 'hi'); diff --git a/tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts b/tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts new file mode 100644 index 0000000000..ba5eebbefc --- /dev/null +++ b/tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts @@ -0,0 +1,3 @@ +interface I { + public [a: string]: number; +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt.ts new file mode 100644 index 0000000000..dfb21cccbe --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt.ts @@ -0,0 +1,11 @@ +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt2.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt2.ts new file mode 100644 index 0000000000..f81fe17a62 --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt2.ts @@ -0,0 +1,11 @@ +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + export import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts new file mode 100644 index 0000000000..417d6aad8f --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts @@ -0,0 +1,16 @@ +module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } +} +module A.M { + import M = Z.M; + import M = Z.I; + + export function bar() { + } + M.bar(); // Should call Z.M.bar +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt4.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt4.ts new file mode 100644 index 0000000000..1c7993c596 --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt4.ts @@ -0,0 +1,12 @@ +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + interface M { } + import M = Z.M; + export function bar() { + } + M.bar(); // Should call Z.M.bar +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts new file mode 100644 index 0000000000..fa224b1b7f --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts @@ -0,0 +1,16 @@ +module Z { + export module M { + export function bar() { + return ""; + } + } + export interface I { } +} +module A.M { + import M = Z.I; + import M = Z.M; + + export function bar() { + } + M.bar(); // Should call Z.M.bar +} \ No newline at end of file diff --git a/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt6.ts b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt6.ts new file mode 100644 index 0000000000..f488a5de07 --- /dev/null +++ b/tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt6.ts @@ -0,0 +1,10 @@ +module Z.M { + export function bar() { + return ""; + } +} +module A.M { + import M = Z.M; + export function bar() { + } +} \ No newline at end of file diff --git a/tests/cases/compiler/objectLiteralMemberWithModifiers1.ts b/tests/cases/compiler/objectLiteralMemberWithModifiers1.ts new file mode 100644 index 0000000000..6bdc9476fb --- /dev/null +++ b/tests/cases/compiler/objectLiteralMemberWithModifiers1.ts @@ -0,0 +1 @@ +var v = { public foo() { } } \ No newline at end of file diff --git a/tests/cases/compiler/objectLiteralMemberWithModifiers2.ts b/tests/cases/compiler/objectLiteralMemberWithModifiers2.ts new file mode 100644 index 0000000000..0bfa0a2052 --- /dev/null +++ b/tests/cases/compiler/objectLiteralMemberWithModifiers2.ts @@ -0,0 +1 @@ +var v = { public get foo() { } } \ No newline at end of file diff --git a/tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts b/tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts new file mode 100644 index 0000000000..0529c717d1 --- /dev/null +++ b/tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts @@ -0,0 +1 @@ +var v = { foo?() { } } \ No newline at end of file diff --git a/tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts b/tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts new file mode 100644 index 0000000000..7f930a5dfd --- /dev/null +++ b/tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts @@ -0,0 +1 @@ +var v = { foo(); } \ No newline at end of file diff --git a/tests/cases/compiler/visibilityOfTypeParameters.ts b/tests/cases/compiler/visibilityOfTypeParameters.ts new file mode 100644 index 0000000000..386d0bb9cb --- /dev/null +++ b/tests/cases/compiler/visibilityOfTypeParameters.ts @@ -0,0 +1,8 @@ +// @module:commonjs +//@declaration: true + +export class MyClass { + protected myMethod(val: T): T { + return val; + } +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts b/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts new file mode 100644 index 0000000000..210f3eebbd --- /dev/null +++ b/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts @@ -0,0 +1,6 @@ + + +function foo(...rest: any[]) { +} + +foo `${function (x: number) { x = "bad"; } }`; \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts b/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts new file mode 100644 index 0000000000..0a51fea491 --- /dev/null +++ b/tests/cases/conformance/es6/templates/taggedTemplateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts @@ -0,0 +1,6 @@ +//@target: es6 + +function foo(...rest: any[]) { +} + +foo `${function (x: number) { x = "bad"; } }`; \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/templateStringBinaryOperations.ts b/tests/cases/conformance/es6/templates/templateStringBinaryOperations.ts new file mode 100644 index 0000000000..28313595f9 --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringBinaryOperations.ts @@ -0,0 +1,51 @@ +var a = 1 + `${ 3 }`; +var b = 1 + `2${ 3 }`; +var c = 1 + `${ 3 }4`; +var d = 1 + `2${ 3 }4`; +var e = `${ 3 }` + 5; +var f = `2${ 3 }` + 5; +var g = `${ 3 }4` + 5; +var h = `2${ 3 }4` + 5; +var i = 1 + `${ 3 }` + 5; +var j = 1 + `2${ 3 }` + 5; +var k = 1 + `${ 3 }4` + 5; +var l = 1 + `2${ 3 }4` + 5; + +var a2 = 1 + `${ 3 - 4 }`; +var b2 = 1 + `2${ 3 - 4 }`; +var c2 = 1 + `${ 3 - 4 }5`; +var d2 = 1 + `2${ 3 - 4 }5`; +var e2 = `${ 3 - 4 }` + 6; +var f2 = `2${ 3 - 4 }` + 6; +var g2 = `${ 3 - 4 }5` + 6; +var h2 = `2${ 3 - 4 }5` + 6; +var i2 = 1 + `${ 3 - 4 }` + 6; +var j2 = 1 + `2${ 3 - 4 }` + 6; +var k2 = 1 + `${ 3 - 4 }5` + 6; +var l2 = 1 + `2${ 3 - 4 }5` + 6; + +var a3 = 1 + `${ 3 * 4 }`; +var b3 = 1 + `2${ 3 * 4 }`; +var c3 = 1 + `${ 3 * 4 }5`; +var d3 = 1 + `2${ 3 * 4 }5`; +var e3 = `${ 3 * 4 }` + 6; +var f3 = `2${ 3 * 4 }` + 6; +var g3 = `${ 3 * 4 }5` + 6; +var h3 = `2${ 3 * 4 }5` + 6; +var i3 = 1 + `${ 3 * 4 }` + 6; +var j3 = 1 + `2${ 3 * 4 }` + 6; +var k3 = 1 + `${ 3 * 4 }5` + 6; +var l3 = 1 + `2${ 3 * 4 }5` + 6; + +var a4 = 1 + `${ 3 & 4 }`; +var b4 = 1 + `2${ 3 & 4 }`; +var c4 = 1 + `${ 3 & 4 }5`; +var d4 = 1 + `2${ 3 & 4 }5`; +var e4 = `${ 3 & 4 }` + 6; +var f4 = `2${ 3 & 4 }` + 6; +var g4 = `${ 3 & 4 }5` + 6; +var h4 = `2${ 3 & 4 }5` + 6; +var i4 = 1 + `${ 3 & 4 }` + 6; +var j4 = 1 + `2${ 3 & 4 }` + 6; +var k4 = 1 + `${ 3 & 4 }5` + 6; +var l4 = 1 + `2${ 3 & 4 }5` + 6; diff --git a/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6.ts b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6.ts new file mode 100644 index 0000000000..d734c9b4cb --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6.ts @@ -0,0 +1,52 @@ +// @target: ES6 +var a = 1 + `${ 3 }`; +var b = 1 + `2${ 3 }`; +var c = 1 + `${ 3 }4`; +var d = 1 + `2${ 3 }4`; +var e = `${ 3 }` + 5; +var f = `2${ 3 }` + 5; +var g = `${ 3 }4` + 5; +var h = `2${ 3 }4` + 5; +var i = 1 + `${ 3 }` + 5; +var j = 1 + `2${ 3 }` + 5; +var k = 1 + `${ 3 }4` + 5; +var l = 1 + `2${ 3 }4` + 5; + +var a2 = 1 + `${ 3 - 4 }`; +var b2 = 1 + `2${ 3 - 4 }`; +var c2 = 1 + `${ 3 - 4 }5`; +var d2 = 1 + `2${ 3 - 4 }5`; +var e2 = `${ 3 - 4 }` + 6; +var f2 = `2${ 3 - 4 }` + 6; +var g2 = `${ 3 - 4 }5` + 6; +var h2 = `2${ 3 - 4 }5` + 6; +var i2 = 1 + `${ 3 - 4 }` + 6; +var j2 = 1 + `2${ 3 - 4 }` + 6; +var k2 = 1 + `${ 3 - 4 }5` + 6; +var l2 = 1 + `2${ 3 - 4 }5` + 6; + +var a3 = 1 + `${ 3 * 4 }`; +var b3 = 1 + `2${ 3 * 4 }`; +var c3 = 1 + `${ 3 * 4 }5`; +var d3 = 1 + `2${ 3 * 4 }5`; +var e3 = `${ 3 * 4 }` + 6; +var f3 = `2${ 3 * 4 }` + 6; +var g3 = `${ 3 * 4 }5` + 6; +var h3 = `2${ 3 * 4 }5` + 6; +var i3 = 1 + `${ 3 * 4 }` + 6; +var j3 = 1 + `2${ 3 * 4 }` + 6; +var k3 = 1 + `${ 3 * 4 }5` + 6; +var l3 = 1 + `2${ 3 * 4 }5` + 6; + +var a4 = 1 + `${ 3 & 4 }`; +var b4 = 1 + `2${ 3 & 4 }`; +var c4 = 1 + `${ 3 & 4 }5`; +var d4 = 1 + `2${ 3 & 4 }5`; +var e4 = `${ 3 & 4 }` + 6; +var f4 = `2${ 3 & 4 }` + 6; +var g4 = `${ 3 & 4 }5` + 6; +var h4 = `2${ 3 & 4 }5` + 6; +var i4 = 1 + `${ 3 & 4 }` + 6; +var j4 = 1 + `2${ 3 & 4 }` + 6; +var k4 = 1 + `${ 3 & 4 }5` + 6; +var l4 = 1 + `2${ 3 & 4 }5` + 6; diff --git a/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts new file mode 100644 index 0000000000..0bfa84e05a --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsES6Invalid.ts @@ -0,0 +1,108 @@ +// @target: ES6 +var a = 1 - `${ 3 }`; +var b = 1 - `2${ 3 }`; +var c = 1 - `${ 3 }4`; +var d = 1 - `2${ 3 }4`; +var e = `${ 3 }` - 5; +var f = `2${ 3 }` - 5; +var g = `${ 3 }4` - 5; +var h = `2${ 3 }4` - 5; + +var a2 = 1 * `${ 3 }`; +var b2 = 1 * `2${ 3 }`; +var c2 = 1 * `${ 3 }4`; +var d2 = 1 * `2${ 3 }4`; +var e2 = `${ 3 }` * 5; +var f2 = `2${ 3 }` * 5; +var g2 = `${ 3 }4` * 5; +var h2 = `2${ 3 }4` * 5; + +var a3 = 1 & `${ 3 }`; +var b3 = 1 & `2${ 3 }`; +var c3 = 1 & `${ 3 }4`; +var d3 = 1 & `2${ 3 }4`; +var e3 = `${ 3 }` & 5; +var f3 = `2${ 3 }` & 5; +var g3 = `${ 3 }4` & 5; +var h3 = `2${ 3 }4` & 5; + +var a4 = 1 - `${ 3 - 4 }`; +var b4 = 1 - `2${ 3 - 4 }`; +var c4 = 1 - `${ 3 - 4 }5`; +var d4 = 1 - `2${ 3 - 4 }5`; +var e4 = `${ 3 - 4 }` - 6; +var f4 = `2${ 3 - 4 }` - 6; +var g4 = `${ 3 - 4 }5` - 6; +var h4 = `2${ 3 - 4 }5` - 6; + +var a5 = 1 - `${ 3 * 4 }`; +var b5 = 1 - `2${ 3 * 4 }`; +var c5 = 1 - `${ 3 * 4 }5`; +var d5 = 1 - `2${ 3 * 4 }5`; +var e5 = `${ 3 * 4 }` - 6; +var f5 = `2${ 3 * 4 }` - 6; +var g5 = `${ 3 * 4 }5` - 6; +var h5 = `2${ 3 * 4 }5` - 6; + +var a6 = 1 - `${ 3 & 4 }`; +var b6 = 1 - `2${ 3 & 4 }`; +var c6 = 1 - `${ 3 & 4 }5`; +var d6 = 1 - `2${ 3 & 4 }5`; +var e6 = `${ 3 & 4 }` - 6; +var f6 = `2${ 3 & 4 }` - 6; +var g6 = `${ 3 & 4 }5` - 6; +var h6 = `2${ 3 & 4 }5` - 6; + +var a7 = 1 * `${ 3 - 4 }`; +var b7 = 1 * `2${ 3 - 4 }`; +var c7 = 1 * `${ 3 - 4 }5`; +var d7 = 1 * `2${ 3 - 4 }5`; +var e7 = `${ 3 - 4 }` * 6; +var f7 = `2${ 3 - 4 }` * 6; +var g7 = `${ 3 - 4 }5` * 6; +var h7 = `2${ 3 - 4 }5` * 6; + +var a8 = 1 * `${ 3 * 4 }`; +var b8 = 1 * `2${ 3 * 4 }`; +var c8 = 1 * `${ 3 * 4 }5`; +var d8 = 1 * `2${ 3 * 4 }5`; +var e8 = `${ 3 * 4 }` * 6; +var f8 = `2${ 3 * 4 }` * 6; +var g8 = `${ 3 * 4 }5` * 6; +var h8 = `2${ 3 * 4 }5` * 6; + +var a9 = 1 * `${ 3 & 4 }`; +var b9 = 1 * `2${ 3 & 4 }`; +var c9 = 1 * `${ 3 & 4 }5`; +var d9 = 1 * `2${ 3 & 4 }5`; +var e9 = `${ 3 & 4 }` * 6; +var f9 = `2${ 3 & 4 }` * 6; +var g9 = `${ 3 & 4 }5` * 6; +var h9 = `2${ 3 & 4 }5` * 6; + +var aa = 1 & `${ 3 - 4 }`; +var ba = 1 & `2${ 3 - 4 }`; +var ca = 1 & `${ 3 - 4 }5`; +var da = 1 & `2${ 3 - 4 }5`; +var ea = `${ 3 - 4 }` & 6; +var fa = `2${ 3 - 4 }` & 6; +var ga = `${ 3 - 4 }5` & 6; +var ha = `2${ 3 - 4 }5` & 6; + +var ab = 1 & `${ 3 * 4 }`; +var bb = 1 & `2${ 3 * 4 }`; +var cb = 1 & `${ 3 * 4 }5`; +var db = 1 & `2${ 3 * 4 }5`; +var eb = `${ 3 * 4 }` & 6; +var fb = `2${ 3 * 4 }` & 6; +var gb = `${ 3 * 4 }5` & 6; +var hb = `2${ 3 * 4 }5` & 6; + +var ac = 1 & `${ 3 & 4 }`; +var bc = 1 & `2${ 3 & 4 }`; +var cc = 1 & `${ 3 & 4 }5`; +var dc = 1 & `2${ 3 & 4 }5`; +var ec = `${ 3 & 4 }` & 6; +var fc = `2${ 3 & 4 }` & 6; +var gc = `${ 3 & 4 }5` & 6; +var hc = `2${ 3 & 4 }5` & 6; diff --git a/tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts new file mode 100644 index 0000000000..8770edcbd3 --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringBinaryOperationsInvalid.ts @@ -0,0 +1,107 @@ +var a = 1 - `${ 3 }`; +var b = 1 - `2${ 3 }`; +var c = 1 - `${ 3 }4`; +var d = 1 - `2${ 3 }4`; +var e = `${ 3 }` - 5; +var f = `2${ 3 }` - 5; +var g = `${ 3 }4` - 5; +var h = `2${ 3 }4` - 5; + +var a2 = 1 * `${ 3 }`; +var b2 = 1 * `2${ 3 }`; +var c2 = 1 * `${ 3 }4`; +var d2 = 1 * `2${ 3 }4`; +var e2 = `${ 3 }` * 5; +var f2 = `2${ 3 }` * 5; +var g2 = `${ 3 }4` * 5; +var h2 = `2${ 3 }4` * 5; + +var a3 = 1 & `${ 3 }`; +var b3 = 1 & `2${ 3 }`; +var c3 = 1 & `${ 3 }4`; +var d3 = 1 & `2${ 3 }4`; +var e3 = `${ 3 }` & 5; +var f3 = `2${ 3 }` & 5; +var g3 = `${ 3 }4` & 5; +var h3 = `2${ 3 }4` & 5; + +var a4 = 1 - `${ 3 - 4 }`; +var b4 = 1 - `2${ 3 - 4 }`; +var c4 = 1 - `${ 3 - 4 }5`; +var d4 = 1 - `2${ 3 - 4 }5`; +var e4 = `${ 3 - 4 }` - 6; +var f4 = `2${ 3 - 4 }` - 6; +var g4 = `${ 3 - 4 }5` - 6; +var h4 = `2${ 3 - 4 }5` - 6; + +var a5 = 1 - `${ 3 * 4 }`; +var b5 = 1 - `2${ 3 * 4 }`; +var c5 = 1 - `${ 3 * 4 }5`; +var d5 = 1 - `2${ 3 * 4 }5`; +var e5 = `${ 3 * 4 }` - 6; +var f5 = `2${ 3 * 4 }` - 6; +var g5 = `${ 3 * 4 }5` - 6; +var h5 = `2${ 3 * 4 }5` - 6; + +var a6 = 1 - `${ 3 & 4 }`; +var b6 = 1 - `2${ 3 & 4 }`; +var c6 = 1 - `${ 3 & 4 }5`; +var d6 = 1 - `2${ 3 & 4 }5`; +var e6 = `${ 3 & 4 }` - 6; +var f6 = `2${ 3 & 4 }` - 6; +var g6 = `${ 3 & 4 }5` - 6; +var h6 = `2${ 3 & 4 }5` - 6; + +var a7 = 1 * `${ 3 - 4 }`; +var b7 = 1 * `2${ 3 - 4 }`; +var c7 = 1 * `${ 3 - 4 }5`; +var d7 = 1 * `2${ 3 - 4 }5`; +var e7 = `${ 3 - 4 }` * 6; +var f7 = `2${ 3 - 4 }` * 6; +var g7 = `${ 3 - 4 }5` * 6; +var h7 = `2${ 3 - 4 }5` * 6; + +var a8 = 1 * `${ 3 * 4 }`; +var b8 = 1 * `2${ 3 * 4 }`; +var c8 = 1 * `${ 3 * 4 }5`; +var d8 = 1 * `2${ 3 * 4 }5`; +var e8 = `${ 3 * 4 }` * 6; +var f8 = `2${ 3 * 4 }` * 6; +var g8 = `${ 3 * 4 }5` * 6; +var h8 = `2${ 3 * 4 }5` * 6; + +var a9 = 1 * `${ 3 & 4 }`; +var b9 = 1 * `2${ 3 & 4 }`; +var c9 = 1 * `${ 3 & 4 }5`; +var d9 = 1 * `2${ 3 & 4 }5`; +var e9 = `${ 3 & 4 }` * 6; +var f9 = `2${ 3 & 4 }` * 6; +var g9 = `${ 3 & 4 }5` * 6; +var h9 = `2${ 3 & 4 }5` * 6; + +var aa = 1 & `${ 3 - 4 }`; +var ba = 1 & `2${ 3 - 4 }`; +var ca = 1 & `${ 3 - 4 }5`; +var da = 1 & `2${ 3 - 4 }5`; +var ea = `${ 3 - 4 }` & 6; +var fa = `2${ 3 - 4 }` & 6; +var ga = `${ 3 - 4 }5` & 6; +var ha = `2${ 3 - 4 }5` & 6; + +var ab = 1 & `${ 3 * 4 }`; +var bb = 1 & `2${ 3 * 4 }`; +var cb = 1 & `${ 3 * 4 }5`; +var db = 1 & `2${ 3 * 4 }5`; +var eb = `${ 3 * 4 }` & 6; +var fb = `2${ 3 * 4 }` & 6; +var gb = `${ 3 * 4 }5` & 6; +var hb = `2${ 3 * 4 }5` & 6; + +var ac = 1 & `${ 3 & 4 }`; +var bc = 1 & `2${ 3 & 4 }`; +var cc = 1 & `${ 3 & 4 }5`; +var dc = 1 & `2${ 3 & 4 }5`; +var ec = `${ 3 & 4 }` & 6; +var fc = `2${ 3 & 4 }` & 6; +var gc = `${ 3 & 4 }5` & 6; +var hc = `2${ 3 & 4 }5` & 6; diff --git a/tests/cases/conformance/es6/templates/templateStringInBinaryAddition.ts b/tests/cases/conformance/es6/templates/templateStringInBinaryAddition.ts deleted file mode 100644 index 7f00313ca8..0000000000 --- a/tests/cases/conformance/es6/templates/templateStringInBinaryAddition.ts +++ /dev/null @@ -1 +0,0 @@ -var x = 10 + `abc${ 10 }def`; \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/templateStringInBinaryAdditionES6.ts b/tests/cases/conformance/es6/templates/templateStringInBinaryAdditionES6.ts deleted file mode 100644 index 5f44e3cb9d..0000000000 --- a/tests/cases/conformance/es6/templates/templateStringInBinaryAdditionES6.ts +++ /dev/null @@ -1,2 +0,0 @@ -// @target: ES6 -var x = 10 + `abc${ 10 }def`; \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortions.ts b/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortions.ts index 11dca4caf7..9191ca1934 100644 --- a/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortions.ts +++ b/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortions.ts @@ -20,4 +20,6 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; -var l = `1${ 0 }2${ 0 }3`; \ No newline at end of file +var l = `${ 0 }2${ 0 }3`; + +var m = `1${ 0 }2${ 0 }3`; diff --git a/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortionsES6.ts b/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortionsES6.ts index 183da57dd4..ff178d2243 100644 --- a/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortionsES6.ts +++ b/tests/cases/conformance/es6/templates/templateStringWithEmptyLiteralPortionsES6.ts @@ -21,4 +21,6 @@ var j = `${ 0 }${ 0 }3`; var k = `1${ 0 }${ 0 }3`; -var l = `1${ 0 }2${ 0 }3`; \ No newline at end of file +var l = `${ 0 }2${ 0 }3`; + +var m = `1${ 0 }2${ 0 }3`; diff --git a/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts b/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts new file mode 100644 index 0000000000..26995f21e5 --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpression.ts @@ -0,0 +1,3 @@ + + +`${function (x: number) { x = "bad"; } }`; \ No newline at end of file diff --git a/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts b/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts new file mode 100644 index 0000000000..4803285a24 --- /dev/null +++ b/tests/cases/conformance/es6/templates/templateStringsWithTypeErrorInFunctionExpressionsInSubstitutionExpressionES6.ts @@ -0,0 +1,3 @@ +//@target: es6 + +`${function (x: number) { x = "bad"; } }`; \ No newline at end of file diff --git a/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts b/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts new file mode 100644 index 0000000000..c15d911ee5 --- /dev/null +++ b/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts @@ -0,0 +1,17 @@ +// @target: ES6 + +type FuncType = (x: (p: T) => T) => typeof x; + +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, x: T): T; +function tempTag1(templateStrs: TemplateStringsArray, f: FuncType, h: FuncType, x: T): T; +function tempTag1(...rest: any[]): T { + return undefined; +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag1 `${ x => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ 10 }`; +tempTag1 `${ x => { x(undefined); return x; } }${ (y: (p: T) => T) => { y(undefined); return y } }${ undefined }`; +tempTag1 `${ (x: (p: T) => T) => { x(undefined); return x; } }${ y => { y(undefined); return y; } }${ undefined }`; diff --git a/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts b/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts new file mode 100644 index 0000000000..24fcf4a04d --- /dev/null +++ b/tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts @@ -0,0 +1,18 @@ +// @target: ES6 + +type FuncType1 = (x: (p: T) => T) => typeof x; +type FuncType2 = (x: (p: T) => T) => typeof x; + +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType1, x: number): number; +function tempTag2(templateStrs: TemplateStringsArray, f: FuncType2, h: FuncType2, x: string): string; +function tempTag2(...rest: any[]): any { + return undefined; +} + +// If contextual typing takes place, these functions should work. +// Otherwise, the arrow functions' parameters will be typed as 'any', +// and it is an error to invoke an any-typed value with type arguments, +// so this test will error. +tempTag2 `${ x => { x(undefined); return x; } }${ 0 }`; +tempTag2 `${ x => { x(undefined); return x; } }${ y => { y(null); return y; } }${ "hello" }`; +tempTag2 `${ x => { x(undefined); return x; } }${ undefined }${ "hello" }`; \ No newline at end of file diff --git a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts index 50a112f462..346a102faa 100644 --- a/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts +++ b/tests/cases/fourslash/completionListAtIdentifierDefinitionLocations_varDeclarations.ts @@ -11,7 +11,7 @@ ////var a2, a/*varName4*/ - +debugger; test.markers().forEach((m) => { goTo.position(m.position, m.fileName); verify.completionListIsEmpty(); diff --git a/tests/cases/fourslash/deleteModifierBeforeVarStatement1.ts b/tests/cases/fourslash/deleteModifierBeforeVarStatement1.ts new file mode 100644 index 0000000000..803d6bf66c --- /dev/null +++ b/tests/cases/fourslash/deleteModifierBeforeVarStatement1.ts @@ -0,0 +1,64 @@ +/// + +//// +//// +//// ///////////////////////////// +//// /// Windows Script Host APIS +//// ///////////////////////////// +//// +//// declare var ActiveXObject: { new (s: string): any; }; +//// +//// interface ITextWriter { +//// WriteLine(s): void; +//// } +//// +//// declare var WScript: { +//// Echo(s): void; +//// StdErr: ITextWriter; +//// Arguments: { length: number; Item(): string; }; +//// ScriptFullName: string; +//// Quit(): number; +//// } +//// + + +goTo.file(0); + +// : +// : |--- go here +// 1: +// 2: +goTo.position(0); + +// : +// : |--- delete "\n\n///..." +// 1: +// 2: +debugger; +edit.deleteAtCaret(100); + + +// 12: +// : |--- go here +// 13: declare var WScript: { +// 14: Echo(s): void; +goTo.position(198); + +// 12: +// : |--- delete "declare..." +// 13: declare var WScript: { +// 14: Echo(s): void; +edit.deleteAtCaret(16); + + +// 9: StdErr: ITextWriter; +// : |--- go here +// 10: Arguments: { length: number; Item(): string; }; +// 11: ScriptFullName: string; +goTo.position(198); + +// 9: StdErr: ITextWriter; +// : |--- insert "Item(): string; " +// 10: Arguments: { length: number; Item(): string; }; +// 11: ScriptFullName: string; +edit.insert("Item(): string; "); diff --git a/tests/cases/fourslash/formatConflictMarker1.ts b/tests/cases/fourslash/formatConflictMarker1.ts index 88c9703241..c0e2dbc4f6 100644 --- a/tests/cases/fourslash/formatConflictMarker1.ts +++ b/tests/cases/fourslash/formatConflictMarker1.ts @@ -2,7 +2,7 @@ ////class C { ////<<<<<<< HEAD -//// v = 1; +////v = 1; ////======= ////v = 2; ////>>>>>>> Branch - a @@ -13,6 +13,6 @@ verify.currentFileContentIs("class C {\r\n\ <<<<<<< HEAD\r\n\ v = 1;\r\n\ =======\r\n\ - v = 2;\r\n\ +v = 2;\r\n\ >>>>>>> Branch - a\r\n\ }"); \ No newline at end of file diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index f5a582868e..0f45804152 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -34,7 +34,7 @@ declare var FourSlash; // Return code used by getEmitOutput function to indicate status of the function // It is a duplicate of the one in types.ts to expose it to testcases in fourslash enum EmitReturnStatus { - Succeeded = 0, // All outputs generated as requested (.js, .map, .d.ts), no errors reported + Succeeded = 0, // All outputs generated if requested (.js, .map, .d.ts), no errors reported AllOutputGenerationSkipped = 1, // No .js generated because of syntax errors, or compiler options errors, nothing generated JSGeneratedWithSemanticErrors = 2, // .js and .map generated with semantic errors DeclarationGenerationSkipped = 3, // .d.ts generation skipped because of semantic errors or declaration emitter specific errors; Output .js with semantic errors @@ -217,6 +217,10 @@ module FourSlashInterface { FourSlash.currentTestState.verifyQuickInfoExists(this.negative); } + public definitionCountIs(expectedCount: number) { + FourSlash.currentTestState.verifyDefinitionsCount(this.negative, expectedCount); + } + public definitionLocationExists() { FourSlash.currentTestState.verifyDefinitionLocationExists(this.negative); } diff --git a/tests/cases/fourslash/getOccurrencesTryCatchFinally.ts b/tests/cases/fourslash/getOccurrencesTryCatchFinally.ts index 9037b6f802..db0f792880 100644 --- a/tests/cases/fourslash/getOccurrencesTryCatchFinally.ts +++ b/tests/cases/fourslash/getOccurrencesTryCatchFinally.ts @@ -16,7 +16,7 @@ ////[|fina/*3*/lly|] { ////} - +debugger; for (var i = 1; i <= test.markers().length; i++) { goTo.marker("" + i); verify.occurrencesAtPositionCount(3); diff --git a/tests/cases/fourslash/goToDefinitionExternamModuleName4.ts b/tests/cases/fourslash/goToDefinitionExternamModuleName4.ts index 1a0fa46c07..c8bbaa458e 100644 --- a/tests/cases/fourslash/goToDefinitionExternamModuleName4.ts +++ b/tests/cases/fourslash/goToDefinitionExternamModuleName4.ts @@ -1,4 +1,4 @@ -/// +/// // @Filename: b.ts ////import n = require('unknown/*1*/'); diff --git a/tests/cases/fourslash/goToDefinitionFunctionOverloads.ts b/tests/cases/fourslash/goToDefinitionFunctionOverloads.ts index 6dd4cc91f1..488d788073 100644 --- a/tests/cases/fourslash/goToDefinitionFunctionOverloads.ts +++ b/tests/cases/fourslash/goToDefinitionFunctionOverloads.ts @@ -1,20 +1,20 @@ -/// - -/////*functionOverload1*/function /*functionOverload*/functionOverload(); -/////*functionOverload2*/function functionOverload(value: string); -/////*functionOverloadDefinition*/function functionOverload() {} -//// +/// + +/////*functionOverload1*/function /*functionOverload*/functionOverload(); +/////*functionOverload2*/function functionOverload(value: string); +/////*functionOverloadDefinition*/function functionOverload() {} +//// /////*functionOverloadReference1*/functionOverload(); /////*functionOverloadReference2*/functionOverload("123"); -goTo.marker('functionOverloadReference1'); -goTo.definition(); -verify.caretAtMarker('functionOverloadDefinition'); - -goTo.marker('functionOverloadReference2'); -goTo.definition(); -verify.caretAtMarker('functionOverloadDefinition'); - -goTo.marker('functionOverload'); -goTo.definition(); -verify.caretAtMarker('functionOverloadDefinition'); +goTo.marker('functionOverloadReference1'); +goTo.definition(); +verify.caretAtMarker('functionOverloadDefinition'); + +goTo.marker('functionOverloadReference2'); +goTo.definition(); +verify.caretAtMarker('functionOverloadDefinition'); + +goTo.marker('functionOverload'); +goTo.definition(); +verify.caretAtMarker('functionOverloadDefinition'); diff --git a/tests/cases/fourslash/goToDefinitionFunctionOverloadsInClass.ts b/tests/cases/fourslash/goToDefinitionFunctionOverloadsInClass.ts index 1db506f968..f368120922 100644 --- a/tests/cases/fourslash/goToDefinitionFunctionOverloadsInClass.ts +++ b/tests/cases/fourslash/goToDefinitionFunctionOverloadsInClass.ts @@ -1,23 +1,23 @@ -/// - -////class clsInOverload { -//// static fnOverload(); -//// static /*staticFunctionOverload*/fnOverload(foo: string); -//// /*staticFunctionOverloadDefinition*/static fnOverload(foo: any) { } -//// public /*functionOverload*/fnOverload(): any; -//// public fnOverload(foo: string); -//// /*functionOverloadDefinition*/public fnOverload(foo: any) { return "foo" } -//// -//// constructor() { } -////} - +/// + +////class clsInOverload { +//// static fnOverload(); +//// static /*staticFunctionOverload*/fnOverload(foo: string); +//// /*staticFunctionOverloadDefinition*/static fnOverload(foo: any) { } +//// public /*functionOverload*/fnOverload(): any; +//// public fnOverload(foo: string); +//// /*functionOverloadDefinition*/public fnOverload(foo: any) { return "foo" } +//// +//// constructor() { } +////} + // this line triggers a semantic/syntactic error check, remove line when 788570 is fixed -edit.insert(''); - -goTo.marker('staticFunctionOverload'); -goTo.definition(); -verify.caretAtMarker('staticFunctionOverloadDefinition'); - -goTo.marker('functionOverload'); -goTo.definition(); +edit.insert(''); + +goTo.marker('staticFunctionOverload'); +goTo.definition(); +verify.caretAtMarker('staticFunctionOverloadDefinition'); + +goTo.marker('functionOverload'); +goTo.definition(); verify.caretAtMarker('functionOverloadDefinition'); \ No newline at end of file diff --git a/tests/cases/fourslash/goToDefinitionUnionTypeProperty.ts b/tests/cases/fourslash/goToDefinitionUnionTypeProperty1.ts similarity index 91% rename from tests/cases/fourslash/goToDefinitionUnionTypeProperty.ts rename to tests/cases/fourslash/goToDefinitionUnionTypeProperty1.ts index 74b5e2aad8..65d7201aec 100644 --- a/tests/cases/fourslash/goToDefinitionUnionTypeProperty.ts +++ b/tests/cases/fourslash/goToDefinitionUnionTypeProperty1.ts @@ -1,5 +1,5 @@ -/// - +/// + ////interface One { //// /*propertyDefinition1*/commonProperty: number; //// commonFunction(): number; @@ -13,12 +13,14 @@ ////var x : One | Two; //// ////x./*propertyReference*/commonProperty; -////x./*3*/commonFunction; - -goTo.marker("propertyReference"); -goTo.definition(0); -verify.caretAtMarker("propertyDefinition1"); - -goTo.marker("propertyReference"); -goTo.definition(1); -verify.caretAtMarker("propertyDefinition2"); +////x./*3*/commonFunction; + + +goTo.marker("propertyReference"); +verify.definitionCountIs(2); +goTo.definition(0); +verify.caretAtMarker("propertyDefinition1"); + +goTo.marker("propertyReference"); +goTo.definition(1); +verify.caretAtMarker("propertyDefinition2"); diff --git a/tests/cases/fourslash/goToDefinitionUnionTypeProperty2.ts b/tests/cases/fourslash/goToDefinitionUnionTypeProperty2.ts index 960a6b7a86..674d5f4b62 100644 --- a/tests/cases/fourslash/goToDefinitionUnionTypeProperty2.ts +++ b/tests/cases/fourslash/goToDefinitionUnionTypeProperty2.ts @@ -1,9 +1,9 @@ -/// -////interface HasAOrB { -//// /*propertyDefinition1*/a: string; -//// b: string; -////} -//// +/// +////interface HasAOrB { +//// /*propertyDefinition1*/a: string; +//// b: string; +////} +//// ////interface One { //// common: { /*propertyDefinition2*/a : number; }; ////} @@ -15,11 +15,12 @@ ////var x : One | Two; //// ////x.common./*propertyReference*/a; - -goTo.marker("propertyReference"); -goTo.definition(0); -verify.caretAtMarker("propertyDefinition2"); - -goTo.marker("propertyReference"); -goTo.definition(1); -verify.caretAtMarker("propertyDefinition1"); + +goTo.marker("propertyReference"); +verify.definitionCountIs(2); +goTo.definition(0); +verify.caretAtMarker("propertyDefinition2"); + +goTo.marker("propertyReference"); +goTo.definition(1); +verify.caretAtMarker("propertyDefinition1"); diff --git a/tests/cases/fourslash/goToDefinitionUnionTypeProperty3.ts b/tests/cases/fourslash/goToDefinitionUnionTypeProperty3.ts new file mode 100644 index 0000000000..337bae7d52 --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionUnionTypeProperty3.ts @@ -0,0 +1,15 @@ +/// + +////interface Array { +//// /*definition*/specialPop(): T +////} +//// +////var strings: string[]; +////var numbers: number[]; +//// +////var x = (strings || numbers)./*usage*/specialPop() + +goTo.marker("usage"); +verify.definitionCountIs(1); +goTo.definition(); +verify.caretAtMarker("definition"); diff --git a/tests/cases/fourslash/goToDefinitionUnionTypeProperty4.ts b/tests/cases/fourslash/goToDefinitionUnionTypeProperty4.ts new file mode 100644 index 0000000000..eb17f9570c --- /dev/null +++ b/tests/cases/fourslash/goToDefinitionUnionTypeProperty4.ts @@ -0,0 +1,32 @@ +/// + +////interface SnapCrackle { +//// /*def1*/pop(): string; +////} +//// +////interface Magnitude { +//// /*def2*/pop(): number; +////} +//// +////interface Art { +//// /*def3*/pop(): boolean; +////} +//// +////var art: Art; +////var magnitude: Magnitude; +////var snapcrackle: SnapCrackle; +//// +////var x = (snapcrackle || magnitude || art)./*usage*/pop; + +goTo.marker("usage"); +verify.definitionCountIs(3); +goTo.definition(0); +verify.caretAtMarker("def1"); + +goTo.marker("usage"); +goTo.definition(1); +verify.caretAtMarker("def2"); + +goTo.marker("usage"); +goTo.definition(2); +verify.caretAtMarker("def3"); \ No newline at end of file diff --git a/tests/cases/fourslash/incrementalParsingInsertIntoMethod1.ts b/tests/cases/fourslash/incrementalParsingInsertIntoMethod1.ts new file mode 100644 index 0000000000..930c0511ff --- /dev/null +++ b/tests/cases/fourslash/incrementalParsingInsertIntoMethod1.ts @@ -0,0 +1,13 @@ +/// + +////class C { +//// public foo1() { } +//// public foo2() { +//// return 1/*1*/; +//// } +//// public foo3() { } +////} + +debugger; +goTo.marker("1"); +edit.insert(" + 1"); \ No newline at end of file diff --git a/tests/cases/fourslash/navigateItemsLet.ts b/tests/cases/fourslash/navigateItemsLet.ts index dc39952270..8a82d04273 100644 --- a/tests/cases/fourslash/navigateItemsLet.ts +++ b/tests/cases/fourslash/navigateItemsLet.ts @@ -1,10 +1,10 @@ /// -////{| "itemName": "c", "kind": "let", "parentName": "" |}let c = 10; -////function foo() { -//// {| "itemName": "d", "kind": "let", "parentName": "foo" |}let d = 10; -////} - +////{| "itemName": "c", "kind": "let", "parentName": "" |}let c = 10; +////function foo() { +//// {| "itemName": "d", "kind": "let", "parentName": "foo" |}let d = 10; +////} +debugger; test.markers().forEach(marker => { verify.navigationItemsListContains( marker.data.itemName, diff --git a/tests/cases/fourslash/navigationItemsExactMatch2.ts b/tests/cases/fourslash/navigationItemsExactMatch2.ts index 8f934dcc3c..adf8e69761 100644 --- a/tests/cases/fourslash/navigationItemsExactMatch2.ts +++ b/tests/cases/fourslash/navigationItemsExactMatch2.ts @@ -17,7 +17,7 @@ ////function distance2(distanceParam1): void { //// var distanceLocal1; ////} - +debugger; goTo.marker("file1"); verify.navigationItemsListCount(2, "point", "exact"); verify.navigationItemsListCount(5, "distance", "prefix"); diff --git a/tests/cases/fourslash/quickInfoDisplayPartsConst.ts b/tests/cases/fourslash/quickInfoDisplayPartsConst.ts index 62295017df..8871a6cc15 100644 --- a/tests/cases/fourslash/quickInfoDisplayPartsConst.ts +++ b/tests/cases/fourslash/quickInfoDisplayPartsConst.ts @@ -22,6 +22,7 @@ /////*15*/h(10); /////*16*/h("hello"); +debugger; var marker = 0; function verifyConst(name: string, typeDisplay: ts.SymbolDisplayPart[], optionalNameDisplay?: ts.SymbolDisplayPart[], optionalKindModifiers?: string) { marker++; diff --git a/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression1.ts b/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression1.ts new file mode 100644 index 0000000000..ce6b454843 --- /dev/null +++ b/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression1.ts @@ -0,0 +1,19 @@ +/// + +////function tempTag1(templateStrs: TemplateStringsArray, f: (x: T) => T, x: T): T; +////function tempTag1(templateStrs: TemplateStringsArray, f: (x: T) => T, h: (y: T) => T, x: T): T; +////function tempTag1(...rest: any[]): T { +//// return undefined; +////} +//// +////tempTag1 `${ x => /*0*/x }${ 10 }`; +////tempTag1 `${ x => /*1*/x }${ x => /*2*/x }${ 10 }`; +////tempTag1 `${ x => /*3*/x }${ (x: number) => /*4*/x }${ undefined }`; +////tempTag1 `${ (x: number) => /*5*/x }${ x => /*6*/x }${ undefined }`; + +var markers = test.markers(); + +markers.forEach(marker => { + goTo.position(marker.position); + verify.quickInfoIs("(parameter) x: number"); +}); \ No newline at end of file diff --git a/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression2.ts b/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression2.ts new file mode 100644 index 0000000000..d878d60141 --- /dev/null +++ b/tests/cases/fourslash/quickInfoForContextuallyTypedFunctionInTaggedTemplateExpression2.ts @@ -0,0 +1,31 @@ +/// + +////function tempTag2(templateStrs: TemplateStringsArray, f: (x: number) => number, x: number): number; +////function tempTag2(templateStrs: TemplateStringsArray, f: (x: string) => string, h: (y: string) => string, x: string): string; +////function tempTag2(...rest: any[]): any { +//// return undefined; +////} +//// +////tempTag2 `${ x => /*0*/x }${ 0 }`; +////tempTag2 `${ /*1*/x => /*2*/x }${ undefined }`; +////tempTag2 `${ x => /*3*/x }${ x => /*4*/x }${ "hello" }`; +////tempTag2 `${ x => /*5*/x }${ undefined }${ "hello" }`; + +// The first group of parameters, [0, 2], should all be contextually typed as 'number'. +// The second group, [3, 5], should be typed as 'string'. +var numTypedVariableCount = 3; +var strTypedVariableCount = 3; + +if (numTypedVariableCount + strTypedVariableCount !== test.markers().length) { + throw "Unexpected number of markers in file."; +} + +for (var i = 0; i < numTypedVariableCount; i++) { + goTo.marker("" + i); + verify.quickInfoIs("(parameter) x: number"); +} + +for (var i = 0; i < strTypedVariableCount; i++) { + goTo.marker("" + (i + numTypedVariableCount)); + verify.quickInfoIs("(parameter) x: string"); +} \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsConflictMarkers1.ts b/tests/cases/fourslash/syntacticClassificationsConflictMarkers1.ts new file mode 100644 index 0000000000..e381856c41 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsConflictMarkers1.ts @@ -0,0 +1,19 @@ +/// + +////class C { +////<<<<<<< HEAD +//// v = 1; +////======= +//// v = 2; +////>>>>>>> Branch - a +////} +debugger; +var c = classification; +verify.syntacticClassificationsAre( + c.keyword("class"), c.className("C"), c.punctuation("{"), + c.comment("<<<<<<< HEAD"), + c.text("v"), c.operator("="), c.numericLiteral("1"), c.punctuation(";"), + c.comment("======="), + c.text("v"), c.punctuation("="), c.numericLiteral("2"), c.punctuation(";"), + c.comment(">>>>>>> Branch - a"), + c.punctuation("}")); \ No newline at end of file diff --git a/tests/cases/fourslash/syntacticClassificationsConflictMarkers2.ts b/tests/cases/fourslash/syntacticClassificationsConflictMarkers2.ts new file mode 100644 index 0000000000..92ede0d104 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsConflictMarkers2.ts @@ -0,0 +1,15 @@ +/// + +////<<<<<<< HEAD +////class C { } +////======= +////class D { } +////>>>>>>> Branch - a + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("<<<<<<< HEAD"), + c.keyword("class"), c.className("C"), c.punctuation("{"), c.punctuation("}"), + c.comment("======="), + c.keyword("class"), c.text("D"), c.punctuation("{"), c.punctuation("}"), + c.comment(">>>>>>> Branch - a")); \ No newline at end of file diff --git a/tests/cases/unittests/incrementalParser.ts b/tests/cases/unittests/incrementalParser.ts index e89f35aa93..a3875cf8e8 100644 --- a/tests/cases/unittests/incrementalParser.ts +++ b/tests/cases/unittests/incrementalParser.ts @@ -2,11 +2,13 @@ /// module ts { + ts.disableIncrementalParsing = false; + function withChange(text: IScriptSnapshot, start: number, length: number, newText: string): { text: IScriptSnapshot; textChangeRange: TextChangeRange; } { var contents = text.getText(0, text.getLength()); var newContents = contents.substr(0, start) + newText + contents.substring(start + length); - return { text: ScriptSnapshot.fromString(newContents), textChangeRange: new TextChangeRange(new TextSpan(start, length), newText.length) } + return { text: ScriptSnapshot.fromString(newContents), textChangeRange: createTextChangeRange(createTextSpan(start, length), newText.length) } } function withInsert(text: IScriptSnapshot, start: number, newText: string): { text: IScriptSnapshot; textChangeRange: TextChangeRange; } { @@ -18,7 +20,27 @@ module ts { } function createTree(text: IScriptSnapshot, version: string) { - return createLanguageServiceSourceFile(/*fileName:*/ "", text, ScriptTarget.ES5, version, /*isOpen:*/ true, /*setNodeParents:*/ true) + return createLanguageServiceSourceFile(/*fileName:*/ "", text, ScriptTarget.Latest, version, /*isOpen:*/ true, /*setNodeParents:*/ true) + } + + function assertSameDiagnostics(file1: SourceFile, file2: SourceFile) { + var diagnostics1 = file1.getSyntacticDiagnostics(); + var diagnostics2 = file2.getSyntacticDiagnostics(); + + assert.equal(diagnostics1.length, diagnostics2.length, "diagnostics1.length !== diagnostics2.length"); + for (var i = 0, n = diagnostics1.length; i < n; i++) { + var d1 = diagnostics1[i]; + var d2 = diagnostics2[i]; + + assert.equal(d1.file, file1, "d1.file !== file1"); + assert.equal(d2.file, file2, "d2.file !== file2"); + assert.equal(d1.start, d2.start, "d1.start !== d2.start"); + assert.equal(d1.length, d2.length, "d1.length !== d2.length"); + assert.equal(d1.messageText, d2.messageText, "d1.messageText !== d2.messageText"); + assert.equal(d1.category, d2.category, "d1.category !== d2.category"); + assert.equal(d1.code, d2.code, "d1.code !== d2.code"); + assert.equal(d1.isEarly, d2.isEarly, "d1.isEarly !== d2.isEarly"); + } } // NOTE: 'reusedElements' is the expected count of elements reused from the old tree to the new @@ -35,15 +57,21 @@ module ts { Utils.assertInvariants(newTree, /*parent:*/ undefined); // Create a tree for the new text, in an incremental fashion. - var incrementalNewTree = oldTree.update(newText, oldTree.version + ".", /*isOpen:*/ true, textChangeRange); + var incrementalNewTree = updateLanguageServiceSourceFile(oldTree, newText, oldTree.version + ".", /*isOpen:*/ true, textChangeRange); Utils.assertInvariants(incrementalNewTree, /*parent:*/ undefined); // We should get the same tree when doign a full or incremental parse. Utils.assertStructuralEquals(newTree, incrementalNewTree); + // We should also get the exact same set of diagnostics. + assertSameDiagnostics(newTree, incrementalNewTree); + // There should be no reused nodes between two trees that are fully parsed. assert.isTrue(reusedElements(oldTree, newTree) === 0); + assert.equal(newTree.filename, incrementalNewTree.filename, "newTree.filename !== incrementalNewTree.filename"); + assert.equal(newTree.text, incrementalNewTree.text, "newTree.filename !== incrementalNewTree.filename"); + if (expectedReusedElements !== -1) { var actualReusedCount = reusedElements(oldTree, incrementalNewTree); assert.equal(actualReusedCount, expectedReusedElements, actualReusedCount + " !== " + expectedReusedElements); @@ -110,7 +138,7 @@ module ts { var semicolonIndex = source.indexOf(";"); var newTextAndChange = withInsert(oldText, semicolonIndex, " + 1"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 8); }); it('Deleting from method',() => { @@ -126,7 +154,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withDelete(oldText, index, "+ 1".length); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 8); }); it('Regular expression 1',() => { @@ -146,7 +174,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withInsert(oldText, semicolonIndex, "/"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); }); it('Comment 1',() => { @@ -184,7 +212,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withInsert(oldText, index, "*"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); }); it('Parameter 1',() => { @@ -199,7 +227,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withInsert(oldText, semicolonIndex, " + 1"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 8); }); it('Type member 1',() => { @@ -210,7 +238,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withInsert(oldText, index, "?"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 14); }); it('Enum element 1',() => { @@ -221,7 +249,7 @@ module ts { var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withChange(oldText, index, 2, "+"); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 21); }); it('Strict mode 1',() => { @@ -518,7 +546,7 @@ module ts { var index = source.lastIndexOf(";"); var newTextAndChange = withDelete(oldText, index, 1); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); }); it('Edit after empty type parameter list',() => { @@ -552,7 +580,7 @@ var o2 = { set Foo(val:number) { } };"; var index = source.indexOf("set"); var newTextAndChange = withInsert(oldText, index, "public "); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 6); }); it('Insert parameter ahead of parameter',() => { @@ -568,7 +596,7 @@ constructor(name) { }\ var index = source.indexOf("100"); var newTextAndChange = withInsert(oldText, index, "'1', "); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 5); }); it('Insert declare modifier before module',() => { @@ -581,7 +609,7 @@ module m3 { }\ var index = 0; var newTextAndChange = withInsert(oldText, index, "declare "); - compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 3); }); it('Insert function above arrow function with comment',() => { @@ -637,9 +665,100 @@ module m3 { }\ var oldText = ScriptSnapshot.fromString(source); var newTextAndChange = withInsert(oldText, 0, ""); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 7); + }); + + it('Class to interface',() => { + var source = "class A { public M1() { } public M2() { } public M3() { } p1 = 0; p2 = 0; p3 = 0 }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "class".length, "interface"); + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); }); + it('Interface to class',() => { + var source = "interface A { M1?(); M2?(); M3?(); p1?; p2?; p3? }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "interface".length, "class"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + }); + + it('Surrounding function declarations with block',() => { + debugger; + var source = "declare function F1() { } export function F2() { } declare export function F3() { }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withInsert(oldText, 0, "{"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 9); + }); + + it('Removing block around function declarations',() => { + var source = "{ declare function F1() { } export function F2() { } declare export function F3() { }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withDelete(oldText, 0, "{".length); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + }); + + it('Moving methods from class to object literal',() => { + var source = "class C { public A() { } public B() { } public C() { } }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "class C".length, "var v ="); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + }); + + it('Moving methods from object literal to class',() => { + var source = "var v = { public A() { } public B() { } public C() { } }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "var v =".length, "class C"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); + }); + + it('Moving index signatures from class to interface',() => { + var source = "class C { public [a: number]: string; public [a: number]: string; public [a: number]: string }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "class".length, "interface"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 18); + }); + + it('Moving index signatures from interface to class',() => { + var source = "interface C { public [a: number]: string; public [a: number]: string; public [a: number]: string }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "interface".length, "class"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 18); + }); + + it('Moving accessors from class to object literal',() => { + var source = "class C { public get A() { } public get B() { } public get C() { } }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "class C".length, "var v ="); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 0); + }); + + it('Moving accessors from object literal to class',() => { + var source = "var v = { public get A() { } public get B() { } public get C() { } }" + + var oldText = ScriptSnapshot.fromString(source); + var newTextAndChange = withChange(oldText, 0, "var v =".length, "class C"); + + compareTrees(oldText, newTextAndChange.text, newTextAndChange.textChangeRange, 4); + }); + // Simulated typing tests. it('Type extends clause 1',() => { diff --git a/tests/cases/unittests/services/colorization.ts b/tests/cases/unittests/services/colorization.ts index 44804e4f9f..20038800a3 100644 --- a/tests/cases/unittests/services/colorization.ts +++ b/tests/cases/unittests/services/colorization.ts @@ -21,7 +21,7 @@ describe('Colorization', function () { var mytypescriptLS = new Harness.LanguageService.TypeScriptLS(); var myclassifier = mytypescriptLS.getClassifier(); - function getClassifications(code: string, initialEndOfLineState: ts.EndOfLineState = ts.EndOfLineState.Start): ClassiferResult { + function getLexicalClassifications(code: string, initialEndOfLineState: ts.EndOfLineState = ts.EndOfLineState.Start): ClassiferResult { var classResult = myclassifier.getClassificationsForLine(code, initialEndOfLineState).split('\n'); var tuples: Classification[] = []; var i = 0; @@ -71,8 +71,8 @@ describe('Colorization', function () { function regExpLiteral(text: string) { return { value: text, class: ts.TokenClass.RegExpLiteral }; } function finalEndOfLineState(value: number) { return { value: value, class: undefined }; } - function test(text: string, initialEndOfLineState: ts.EndOfLineState, ...expectedEntries: ClassificationEntry[]): void { - var result = getClassifications(text, initialEndOfLineState); + function testLexicalClassification(text: string, initialEndOfLineState: ts.EndOfLineState, ...expectedEntries: ClassificationEntry[]): void { + var result = getLexicalClassifications(text, initialEndOfLineState); for (var i = 0, n = expectedEntries.length; i < n; i++) { var expectedEntry = expectedEntries[i]; @@ -95,7 +95,7 @@ describe('Colorization', function () { describe("test getClassifications", function () { it("Returns correct token classes", function () { - test("var x: string = \"foo\"; //Hello", + testLexicalClassification("var x: string = \"foo\"; //Hello", ts.EndOfLineState.Start, keyword("var"), whitespace(" "), @@ -109,7 +109,7 @@ describe('Colorization', function () { }); it("correctly classifies a comment after a divide operator", function () { - test("1 / 2 // comment", + testLexicalClassification("1 / 2 // comment", ts.EndOfLineState.Start, numberLiteral("1"), whitespace(" "), @@ -119,7 +119,7 @@ describe('Colorization', function () { }); it("correctly classifies a literal after a divide operator", function () { - test("1 / 2, 3 / 4", + testLexicalClassification("1 / 2, 3 / 4", ts.EndOfLineState.Start, numberLiteral("1"), whitespace(" "), @@ -131,131 +131,131 @@ describe('Colorization', function () { }); it("correctly classifies a multi-line string with one backslash", function () { - test("'line1\\", + testLexicalClassification("'line1\\", ts.EndOfLineState.Start, stringLiteral("'line1\\"), finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); }); it("correctly classifies a multi-line string with three backslashes", function () { - test("'line1\\\\\\", + testLexicalClassification("'line1\\\\\\", ts.EndOfLineState.Start, stringLiteral("'line1\\\\\\"), finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral)); }); it("correctly classifies an unterminated single-line string with no backslashes", function () { - test("'line1", + testLexicalClassification("'line1", ts.EndOfLineState.Start, stringLiteral("'line1"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies an unterminated single-line string with two backslashes", function () { - test("'line1\\\\", + testLexicalClassification("'line1\\\\", ts.EndOfLineState.Start, stringLiteral("'line1\\\\"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies an unterminated single-line string with four backslashes", function () { - test("'line1\\\\\\\\", + testLexicalClassification("'line1\\\\\\\\", ts.EndOfLineState.Start, stringLiteral("'line1\\\\\\\\"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies the continuing line of a multi-line string ending in one backslash", function () { - test("\\", + testLexicalClassification("\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\"), finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); }); it("correctly classifies the continuing line of a multi-line string ending in three backslashes", function () { - test("\\", + testLexicalClassification("\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\"), finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral)); }); it("correctly classifies the last line of an unterminated multi-line string ending in no backslashes", function () { - test(" ", + testLexicalClassification(" ", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral(" "), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies the last line of an unterminated multi-line string ending in two backslashes", function () { - test("\\\\", + testLexicalClassification("\\\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\\\"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies the last line of an unterminated multi-line string ending in four backslashes", function () { - test("\\\\\\\\", + testLexicalClassification("\\\\\\\\", ts.EndOfLineState.InDoubleQuoteStringLiteral, stringLiteral("\\\\\\\\"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies the last line of a multi-line string", function () { - test("'", + testLexicalClassification("'", ts.EndOfLineState.InSingleQuoteStringLiteral, stringLiteral("'"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies an unterminated multiline comment", function () { - test("/*", + testLexicalClassification("/*", ts.EndOfLineState.Start, comment("/*"), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies the termination of a multiline comment", function () { - test(" */ ", + testLexicalClassification(" */ ", ts.EndOfLineState.InMultiLineCommentTrivia, comment(" */"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("correctly classifies the continuation of a multiline comment", function () { - test("LOREM IPSUM DOLOR ", + testLexicalClassification("LOREM IPSUM DOLOR ", ts.EndOfLineState.InMultiLineCommentTrivia, comment("LOREM IPSUM DOLOR "), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies an unterminated multiline comment on a line ending in '/*/'", function () { - test(" /*/", + testLexicalClassification(" /*/", ts.EndOfLineState.Start, comment("/*/"), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies an unterminated multiline comment with trailing space", function () { - test("/* ", + testLexicalClassification("/* ", ts.EndOfLineState.Start, comment("/* "), finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia)); }); it("correctly classifies a keyword after a dot", function () { - test("a.var", + testLexicalClassification("a.var", ts.EndOfLineState.Start, identifier("var")); }); it("correctly classifies a string literal after a dot", function () { - test("a.\"var\"", + testLexicalClassification("a.\"var\"", ts.EndOfLineState.Start, stringLiteral("\"var\"")); }); it("correctly classifies a keyword after a dot separated by comment trivia", function () { - test("a./*hello world*/ var", + testLexicalClassification("a./*hello world*/ var", ts.EndOfLineState.Start, identifier("a"), punctuation("."), @@ -264,27 +264,27 @@ describe('Colorization', function () { }); it("classifies a property access with whitespace around the dot", function () { - test(" x .\tfoo ()", + testLexicalClassification(" x .\tfoo ()", ts.EndOfLineState.Start, identifier("x"), identifier("foo")); }); it("classifies a keyword after a dot on previous line", function () { - test("var", + testLexicalClassification("var", ts.EndOfLineState.Start, keyword("var"), finalEndOfLineState(ts.EndOfLineState.Start)); }); it("classifies multiple keywords properly", function () { - test("public static", + testLexicalClassification("public static", ts.EndOfLineState.Start, keyword("public"), keyword("static"), finalEndOfLineState(ts.EndOfLineState.Start)); - test("public var", + testLexicalClassification("public var", ts.EndOfLineState.Start, keyword("public"), identifier("var"), @@ -292,7 +292,7 @@ describe('Colorization', function () { }); it("classifies partially written generics correctly.", function () { - test("Foo { - // no longer in something that looks generic. - test("Foo number", - ts.EndOfLineState.Start, - identifier("Foo"), - operator("<"), - identifier("Foo"), - operator(">"), - keyword("number"), - finalEndOfLineState(ts.EndOfLineState.Start)); + it("LexicallyClassifiesConflictTokens", () => { + debugger; // Test conflict markers. - test( + testLexicalClassification( "class C {\r\n\ <<<<<<< HEAD\r\n\ v = 1;\r\n\ @@ -348,14 +340,26 @@ describe('Colorization', function () { operator("="), numberLiteral("1"), punctuation(";"), - comment("======="), - identifier("v"), - operator("="), - numberLiteral("2"), - punctuation(";"), + comment("=======\r\n v = 2;\r\n"), comment(">>>>>>> Branch - a"), punctuation("}"), finalEndOfLineState(ts.EndOfLineState.Start)); + + testLexicalClassification( +"<<<<<<< HEAD\r\n\ +class C { }\r\n\ +=======\r\n\ +class D { }\r\n\ +>>>>>>> Branch - a\r\n", + ts.EndOfLineState.Start, + comment("<<<<<<< HEAD"), + keyword("class"), + identifier("C"), + punctuation("{"), + punctuation("}"), + comment("=======\r\nclass D { }\r\n"), + comment(">>>>>>> Branch - a"), + finalEndOfLineState(ts.EndOfLineState.Start)); }); }); }); \ No newline at end of file