diff --git a/Jakefile.js b/Jakefile.js index 2640f8a1225..14bf047cf21 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -859,6 +859,7 @@ var tslintRuleDir = "scripts/tslint"; var tslintRules = ([ "nextLineRule", "noNullRule", + "preferConstRule", "booleanTriviaRule", "typeOperatorSpacingRule" ]); diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts new file mode 100644 index 00000000000..29160a9c634 --- /dev/null +++ b/scripts/tslint/preferConstRule.ts @@ -0,0 +1,228 @@ +/// +/// + + +export class Rule extends Lint.Rules.AbstractRule { + public static FAILURE_STRING_FACTORY = (identifier: string) => `Identifier '${identifier}' never appears on the LHS of an assignment - use const instead of let for its declaration.`; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new PreferConstWalker(sourceFile, this.getOptions())); + } +} + +function isBindingPattern(node: ts.Node): node is ts.BindingPattern { + return !!node && (node.kind === ts.SyntaxKind.ArrayBindingPattern || node.kind === ts.SyntaxKind.ObjectBindingPattern); +} + +function walkUpBindingElementsAndPatterns(node: ts.Node): ts.Node { + while (node && (node.kind === ts.SyntaxKind.BindingElement || isBindingPattern(node))) { + node = node.parent; + } + + return node; +} + +function getCombinedNodeFlags(node: ts.Node): ts.NodeFlags { + node = walkUpBindingElementsAndPatterns(node); + + let flags = node.flags; + if (node.kind === ts.SyntaxKind.VariableDeclaration) { + node = node.parent; + } + + if (node && node.kind === ts.SyntaxKind.VariableDeclarationList) { + flags |= node.flags; + node = node.parent; + } + + if (node && node.kind === ts.SyntaxKind.VariableStatement) { + flags |= node.flags; + } + + return flags; +} + +function isLet(node: ts.Node) { + return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Let); +} + +function isExported(node: ts.Node) { + return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Export); +} + +function isAssignmentOperator(token: ts.SyntaxKind): boolean { + return token >= ts.SyntaxKind.FirstAssignment && token <= ts.SyntaxKind.LastAssignment; +} + +function isBindingLiteralExpression(node: ts.Node): node is (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) { + return (!!node) && (node.kind === ts.SyntaxKind.ObjectLiteralExpression || node.kind === ts.SyntaxKind.ArrayLiteralExpression); +} + +interface DeclarationUsages { + declaration: ts.VariableDeclaration; + usages: number; +} + +class PreferConstWalker extends Lint.RuleWalker { + private inScopeLetDeclarations: ts.Map[] = []; + private errors: Lint.RuleFailure[] = []; + private markAssignment(identifier: ts.Identifier) { + const name = identifier.text; + for (let i = this.inScopeLetDeclarations.length - 1; i >= 0; i--) { + const declarations = this.inScopeLetDeclarations[i]; + if (declarations[name]) { + declarations[name].usages++; + break; + } + } + } + + visitSourceFile(node: ts.SourceFile) { + super.visitSourceFile(node); + // Sort errors by position because tslint doesn't + this.errors.sort((a, b) => a.getStartPosition().getPosition() - b.getStartPosition().getPosition()).forEach(e => this.addFailure(e)); + } + + visitBinaryExpression(node: ts.BinaryExpression) { + if (isAssignmentOperator(node.operatorToken.kind)) { + this.visitLHSExpressions(node.left); + } + super.visitBinaryExpression(node); + } + + private visitLHSExpressions(node: ts.Expression) { + while (node.kind === ts.SyntaxKind.ParenthesizedExpression) { + node = (node as ts.ParenthesizedExpression).expression; + } + if (node.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(node as ts.Identifier); + } + else if (isBindingLiteralExpression(node)) { + this.visitBindingLiteralExpression(node as (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression)); + } + } + + private visitBindingLiteralExpression(node: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) { + if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + const pattern = node as ts.ObjectLiteralExpression; + for (const element of pattern.properties) { + if (element.name.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(element.name as ts.Identifier) + } + else if (isBindingPattern(element.name)) { + this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + } + } + } + else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { + const pattern = node as ts.ArrayLiteralExpression; + for (const element of pattern.elements) { + this.visitLHSExpressions(element); + } + } + } + + private visitBindingPatternIdentifiers(pattern: ts.BindingPattern) { + for (const element of pattern.elements) { + if (element.name.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(element.name as ts.Identifier); + } + else { + this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + } + } + } + + visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) { + this.visitAnyUnaryExpression(node); + super.visitPrefixUnaryExpression(node); + } + + visitPostfixUnaryExpression(node: ts.PostfixUnaryExpression) { + this.visitAnyUnaryExpression(node); + super.visitPostfixUnaryExpression(node); + } + + private visitAnyUnaryExpression(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression) { + if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) { + this.visitLHSExpressions(node.operand); + } + } + + visitModuleDeclaration(node: ts.ModuleDeclaration) { + if (node.body.kind === ts.SyntaxKind.ModuleBlock) { + // For some reason module blocks are left out of the visit block traversal + this.visitBlock(node.body as ts.ModuleBlock); + } + super.visitModuleDeclaration(node); + } + + visitForOfStatement(node: ts.ForOfStatement) { + this.visitAnyForStatement(node); + super.visitForOfStatement(node); + this.popDeclarations(); + } + + visitForInStatement(node: ts.ForInStatement) { + this.visitAnyForStatement(node); + super.visitForInStatement(node); + this.popDeclarations(); + } + + private visitAnyForStatement(node: ts.ForOfStatement | ts.ForInStatement) { + const names: ts.Map = {}; + if (isLet(node.initializer)) { + if (node.initializer.kind === ts.SyntaxKind.VariableDeclarationList) { + this.collectLetIdentifiers(node.initializer as ts.VariableDeclarationList, names); + } + } + this.inScopeLetDeclarations.push(names); + } + + private popDeclarations() { + const completed = this.inScopeLetDeclarations.pop(); + for (const name in completed) { + if (Object.hasOwnProperty.call(completed, name)) { + const element = completed[name]; + if (element.usages === 0) { + this.errors.push(this.createFailure(element.declaration.getStart(this.getSourceFile()), element.declaration.getWidth(this.getSourceFile()), Rule.FAILURE_STRING_FACTORY(name))); + } + } + } + } + + visitBlock(node: ts.Block) { + const names: ts.Map = {}; + for (const statement of node.statements) { + if (statement.kind === ts.SyntaxKind.VariableStatement) { + this.collectLetIdentifiers((statement as ts.VariableStatement).declarationList, names); + } + } + this.inScopeLetDeclarations.push(names); + super.visitBlock(node); + this.popDeclarations(); + } + + private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.Map) { + for (const node of list.declarations) { + if (isLet(node) && !isExported(node)) { + this.collectNameIdentifiers(node, node.name, ret); + } + } + } + + private collectNameIdentifiers(value: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) { + if (node.kind === ts.SyntaxKind.Identifier) { + table[(node as ts.Identifier).text] = {declaration: value, usages: 0}; + } + else { + this.collectBindingPatternIdentifiers(value, node as ts.BindingPattern, table); + } + } + + private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.Map) { + for (const element of pattern.elements) { + this.collectNameIdentifiers(value, element.name, table); + } + } +} diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 8a986d40435..2a5b7e4409c 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -95,7 +95,7 @@ namespace ts { const binder = createBinder(); export function bindSourceFile(file: SourceFile, options: CompilerOptions) { - let start = new Date().getTime(); + const start = new Date().getTime(); binder(file, options); bindTime += new Date().getTime() - start; } @@ -187,7 +187,7 @@ namespace ts { return `"${(node.name).text}"`; } if (node.name.kind === SyntaxKind.ComputedPropertyName) { - let nameExpression = (node.name).expression; + const nameExpression = (node.name).expression; // treat computed property names where expression is string/numeric literal as just string/numeric literal if (isStringOrNumericLiteral(nameExpression.kind)) { return (nameExpression).text; @@ -234,9 +234,9 @@ namespace ts { function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); - let isDefaultExport = node.flags & NodeFlags.Default; + const isDefaultExport = node.flags & NodeFlags.Default; // The exported symbol for an export default function/class node is always named "default" - let name = isDefaultExport && parent ? "default" : getDeclarationName(node); + const name = isDefaultExport && parent ? "default" : getDeclarationName(node); let symbol: Symbol; if (name !== undefined) { @@ -303,7 +303,7 @@ namespace ts { } function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - let hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; + const hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; if (symbolFlags & SymbolFlags.Alias) { if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -325,11 +325,11 @@ namespace ts { // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. if (hasExportModifier || container.flags & NodeFlags.ExportContext) { - let exportKind = + const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | (symbolFlags & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); - let local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + const local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; return local; @@ -347,9 +347,9 @@ namespace ts { // Before we recurse into a node's chilren, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. - let saveParent = parent; - let saveContainer = container; - let savedBlockScopeContainer = blockScopeContainer; + const saveParent = parent; + const saveContainer = container; + const savedBlockScopeContainer = blockScopeContainer; // This node will now be set as the parent of all of its children as we recurse into them. parent = node; @@ -371,7 +371,7 @@ namespace ts { // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidently move any stale data forward from // a previous compilation. - let containerFlags = getContainerFlags(node); + const containerFlags = getContainerFlags(node); if (containerFlags & ContainerFlags.IsContainer) { container = blockScopeContainer = node; @@ -403,7 +403,7 @@ namespace ts { seenThisKeyword = false; } - let saveState = kind === SyntaxKind.SourceFile || kind === SyntaxKind.ModuleBlock || isFunctionLikeKind(kind); + const saveState = kind === SyntaxKind.SourceFile || kind === SyntaxKind.ModuleBlock || isFunctionLikeKind(kind); if (saveState) { savedReachabilityState = currentReachabilityState; savedLabelStack = labelStack; @@ -638,7 +638,7 @@ namespace ts { function bindCaseBlock(n: CaseBlock): void { const startState = currentReachabilityState; - for (let clause of n.clauses) { + for (const clause of n.clauses) { currentReachabilityState = startState; bind(clause); if (clause.statements.length && currentReachabilityState === Reachability.Reachable && options.noFallthroughCasesInSwitch) { @@ -795,9 +795,9 @@ namespace ts { } function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean { - let body = node.kind === SyntaxKind.SourceFile ? node : (node).body; + const body = node.kind === SyntaxKind.SourceFile ? node : (node).body; if (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock) { - for (let stat of (body).statements) { + for (const stat of (body).statements) { if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) { return true; } @@ -823,7 +823,7 @@ namespace ts { declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); } else { - let state = getModuleInstanceState(node); + const state = getModuleInstanceState(node); if (state === ModuleInstanceState.NonInstantiated) { declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); } @@ -835,7 +835,7 @@ namespace ts { node.symbol.constEnumOnlyModule = false; } else { - let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; + const currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; if (node.symbol.constEnumOnlyModule === undefined) { // non-merged case - use the current state node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; @@ -856,10 +856,10 @@ namespace ts { // We do that by making an anonymous type literal symbol, and then setting the function // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. - let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); + const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); - let typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); + const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); typeLiteralSymbol.members = { [symbol.name]: symbol }; } @@ -871,14 +871,14 @@ namespace ts { } if (inStrictMode) { - let seen: Map = {}; + const seen: Map = {}; - for (let prop of node.properties) { + for (const prop of node.properties) { if (prop.name.kind !== SyntaxKind.Identifier) { continue; } - let identifier = prop.name; + const identifier = prop.name; // ECMA-262 11.1.5 Object Initialiser // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true @@ -888,18 +888,18 @@ namespace ts { // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - let currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration + const currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration ? ElementKind.Property : ElementKind.Accessor; - let existingKind = seen[identifier.text]; + const existingKind = seen[identifier.text]; if (!existingKind) { seen[identifier.text] = currentKind; continue; } if (currentKind === ElementKind.Property && existingKind === ElementKind.Property) { - let span = getErrorSpanForNode(file, identifier); + const span = getErrorSpanForNode(file, identifier); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } @@ -910,7 +910,7 @@ namespace ts { } function bindAnonymousDeclaration(node: Declaration, symbolFlags: SymbolFlags, name: string) { - let symbol = createSymbol(symbolFlags, name); + const symbol = createSymbol(symbolFlags, name); addDeclarationToSymbol(symbol, node, symbolFlags); } @@ -989,7 +989,7 @@ namespace ts { if (inStrictMode && node.expression.kind === SyntaxKind.Identifier) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name - let span = getErrorSpanForNode(file, node.expression); + const span = getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } @@ -1001,11 +1001,11 @@ namespace ts { function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { if (name && name.kind === SyntaxKind.Identifier) { - let identifier = name; + const identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. - let span = getErrorSpanForNode(file, name); + const span = getErrorSpanForNode(file, name); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } @@ -1066,7 +1066,7 @@ namespace ts { } function errorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { - let span = getSpanOfTokenAtPosition(file, node.pos); + const span = getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -1081,7 +1081,7 @@ namespace ts { node.parent = parent; - let savedInStrictMode = inStrictMode; + const savedInStrictMode = inStrictMode; if (!savedInStrictMode) { updateStrictMode(node); } @@ -1127,7 +1127,7 @@ namespace ts { } function updateStrictModeStatementList(statements: NodeArray) { - for (let statement of statements) { + for (const statement of statements) { if (!isPrologueDirective(statement)) { return; } @@ -1141,7 +1141,7 @@ namespace ts { /// Should be called only on prologue directives (isPrologueDirective(node) should be true) function isUseStrictPrologueDirective(node: ExpressionStatement): boolean { - let nodeText = getTextOfNodeFromSourceText(file.text, node.expression); + const nodeText = getTextOfNodeFromSourceText(file.text, node.expression); // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the // string to contain unicode escapes (as per ES5). @@ -1216,7 +1216,7 @@ namespace ts { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: checkStrictModeFunctionName(node); - let bindingName = (node).name ? (node).name.text : "__function"; + const bindingName = (node).name ? (node).name.text : "__function"; return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: @@ -1289,7 +1289,7 @@ namespace ts { bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); } else { - let bindingName = node.name ? node.name.text : "__class"; + const bindingName = node.name ? node.name.text : "__class"; bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName); // Add name of class expression into the map for semantic classifier if (node.name) { @@ -1297,7 +1297,7 @@ namespace ts { } } - let symbol = node.symbol; + const symbol = node.symbol; // TypeScript 1.0 spec (April 2014): 8.4 // Every class automatically contains a static property member named 'prototype', the @@ -1308,7 +1308,7 @@ namespace ts { // Note: we check for this here because this class may be merging into a module. The // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. - let prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); + const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); if (hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; @@ -1373,7 +1373,7 @@ namespace ts { node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent)) { - let classDeclaration = node.parent.parent; + const classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); } } @@ -1399,13 +1399,13 @@ namespace ts { function pushImplicitLabel(): number { initializeReachabilityStateIfNecessary(); - let index = labelStack.push(Reachability.Unintialized) - 1; + const index = labelStack.push(Reachability.Unintialized) - 1; implicitLabels.push(index); return index; } function popNamedLabel(label: Identifier, outerState: Reachability): void { - let index = labelIndexMap[label.text]; + const index = labelIndexMap[label.text]; Debug.assert(index !== undefined); Debug.assert(labelStack.length == index + 1); @@ -1419,7 +1419,7 @@ namespace ts { Debug.assert(false, `Label stack: ${labelStack.length}, index:${implicitLabelIndex}`); } - let i = implicitLabels.pop(); + const i = implicitLabels.pop(); if (implicitLabelIndex !== i) { Debug.assert(false, `i: ${i}, index: ${implicitLabelIndex}`); diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index dffb360fca8..cb15d6d9401 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -33,26 +33,26 @@ namespace ts { // they no longer need the information (for example, if the user started editing again). let cancellationToken: CancellationToken; - let Symbol = objectAllocator.getSymbolConstructor(); - let Type = objectAllocator.getTypeConstructor(); - let Signature = objectAllocator.getSignatureConstructor(); + const Symbol = objectAllocator.getSymbolConstructor(); + const Type = objectAllocator.getTypeConstructor(); + const Signature = objectAllocator.getSignatureConstructor(); let typeCount = 0; let symbolCount = 0; - let emptyArray: any[] = []; - let emptySymbols: SymbolTable = {}; + const emptyArray: any[] = []; + const emptySymbols: SymbolTable = {}; - let compilerOptions = host.getCompilerOptions(); - let languageVersion = compilerOptions.target || ScriptTarget.ES3; - let modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const compilerOptions = host.getCompilerOptions(); + const languageVersion = compilerOptions.target || ScriptTarget.ES3; + const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; - let emitResolver = createResolver(); + const emitResolver = createResolver(); - let undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); - let argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); + const undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); + const argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); - let checker: TypeChecker = { + const checker: TypeChecker = { getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"), getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"), getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount") + symbolCount, @@ -97,35 +97,35 @@ namespace ts { isOptionalParameter }; - let unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); - let resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); + const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); + const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); - let anyType = createIntrinsicType(TypeFlags.Any, "any"); - let stringType = createIntrinsicType(TypeFlags.String, "string"); - let numberType = createIntrinsicType(TypeFlags.Number, "number"); - let booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); - let esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); - let voidType = createIntrinsicType(TypeFlags.Void, "void"); - let undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); - let nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); - let unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); - let circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); + const anyType = createIntrinsicType(TypeFlags.Any, "any"); + const stringType = createIntrinsicType(TypeFlags.String, "string"); + const numberType = createIntrinsicType(TypeFlags.Number, "number"); + const booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); + const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); + const voidType = createIntrinsicType(TypeFlags.Void, "void"); + const undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); + const nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); + const unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); + const circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); - let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - let emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; - let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= TypeFlags.ContainsAnyFunctionType; - let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - let anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + const anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - let globals: SymbolTable = {}; + const globals: SymbolTable = {}; let globalESSymbolConstructorSymbol: Symbol; @@ -162,29 +162,29 @@ namespace ts { let jsxElementClassType: Type; - let tupleTypes: Map = {}; - let unionTypes: Map = {}; - let intersectionTypes: Map = {}; - let stringLiteralTypes: Map = {}; + const tupleTypes: Map = {}; + const unionTypes: Map = {}; + const intersectionTypes: Map = {}; + const stringLiteralTypes: Map = {}; let emitExtends = false; let emitDecorate = false; let emitParam = false; let emitAwaiter = false; - let emitGenerator = false; + const emitGenerator = false; - let resolutionTargets: TypeSystemEntity[] = []; - let resolutionResults: boolean[] = []; - let resolutionPropertyNames: TypeSystemPropertyName[] = []; + const resolutionTargets: TypeSystemEntity[] = []; + const resolutionResults: boolean[] = []; + const resolutionPropertyNames: TypeSystemPropertyName[] = []; - let mergedSymbols: Symbol[] = []; - let symbolLinks: SymbolLinks[] = []; - let nodeLinks: NodeLinks[] = []; - let potentialThisCollisions: Node[] = []; - let awaitedTypeStack: number[] = []; + const mergedSymbols: Symbol[] = []; + const symbolLinks: SymbolLinks[] = []; + const nodeLinks: NodeLinks[] = []; + const potentialThisCollisions: Node[] = []; + const awaitedTypeStack: number[] = []; - let diagnostics = createDiagnosticCollection(); + const diagnostics = createDiagnosticCollection(); - let primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { + const primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { "string": { type: stringType, flags: TypeFlags.StringLike @@ -211,9 +211,9 @@ namespace ts { Element: "Element" }; - let subtypeRelation: Map = {}; - let assignableRelation: Map = {}; - let identityRelation: Map = {}; + const subtypeRelation: Map = {}; + const assignableRelation: Map = {}; + const identityRelation: Map = {}; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. let _displayBuilder: SymbolDisplayBuilder; @@ -239,7 +239,7 @@ namespace ts { } function error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void { - let diagnostic = location + const diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2) : createCompilerDiagnostic(message, arg0, arg1, arg2); diagnostics.add(diagnostic); @@ -277,7 +277,7 @@ namespace ts { } function cloneSymbol(symbol: Symbol): Symbol { - let result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name); + const result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -310,7 +310,7 @@ namespace ts { recordMergedSymbol(target, source); } else { - let message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable + const message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(source.declarations, node => { error(node.name ? node.name : node, message, symbolToString(source)); @@ -322,8 +322,8 @@ namespace ts { } function cloneSymbolTable(symbolTable: SymbolTable): SymbolTable { - let result: SymbolTable = {}; - for (let id in symbolTable) { + const result: SymbolTable = {}; + for (const id in symbolTable) { if (hasProperty(symbolTable, id)) { result[id] = symbolTable[id]; } @@ -332,7 +332,7 @@ namespace ts { } function mergeSymbolTable(target: SymbolTable, source: SymbolTable) { - for (let id in source) { + for (const id in source) { if (hasProperty(source, id)) { if (!hasProperty(target, id)) { target[id] = source[id]; @@ -350,12 +350,12 @@ namespace ts { function getSymbolLinks(symbol: Symbol): SymbolLinks { if (symbol.flags & SymbolFlags.Transient) return symbol; - let id = getSymbolId(symbol); + const id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); } function getNodeLinks(node: Node): NodeLinks { - let nodeId = getNodeId(node); + const nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } @@ -369,13 +369,13 @@ namespace ts { function getSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags): Symbol { if (meaning && hasProperty(symbols, name)) { - let symbol = symbols[name]; + const symbol = symbols[name]; Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } if (symbol.flags & SymbolFlags.Alias) { - let target = resolveAlias(symbol); + const target = resolveAlias(symbol); // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors if (target === unknownSymbol || target.flags & meaning) { return symbol; @@ -421,7 +421,7 @@ namespace ts { else if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement || declaration.parent.parent.kind === SyntaxKind.ForInStatement) { // ForIn/ForOf case - use site should not be used in expression part - let expression = (declaration.parent.parent).expression; + const expression = (declaration.parent.parent).expression; return isSameScopeDescendentOf(usage, expression, container); } } @@ -460,7 +460,7 @@ namespace ts { let result: Symbol; let lastLocation: Node; let propertyWithInvalidInitializer: Node; - let errorLocation = location; + const errorLocation = location; let grandparent: Node; loop: while (location) { @@ -482,7 +482,7 @@ namespace ts { case SyntaxKind.SourceFile: if (!isExternalModule(location)) break; case SyntaxKind.ModuleDeclaration: - let moduleExports = getSymbolOfNode(location).exports; + const moduleExports = getSymbolOfNode(location).exports; if (location.kind === SyntaxKind.SourceFile || (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { @@ -504,7 +504,7 @@ namespace ts { } result = moduleExports["default"]; - let localSymbol = getLocalSymbolForExportDefault(result); + const localSymbol = getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } @@ -529,7 +529,7 @@ namespace ts { // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if (isClassLike(location.parent) && !(location.flags & NodeFlags.Static)) { - let ctor = findConstructorDeclaration(location.parent); + const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error @@ -552,7 +552,7 @@ namespace ts { break loop; } if (location.kind === SyntaxKind.ClassExpression && meaning & SymbolFlags.Class) { - let className = (location).name; + const className = (location).name; if (className && name === className.text) { result = location.symbol; break loop; @@ -597,7 +597,7 @@ namespace ts { } if (meaning & SymbolFlags.Function) { - let functionName = (location).name; + const functionName = (location).name; if (functionName && name === functionName.text) { result = location.symbol; break loop; @@ -647,7 +647,7 @@ namespace ts { if (propertyWithInvalidInitializer) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. - let propertyName = (propertyWithInvalidInitializer).name; + const propertyName = (propertyWithInvalidInitializer).name; error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); return undefined; @@ -659,7 +659,7 @@ namespace ts { // declare module foo { // interface bar {} // } - // let foo/*1*/: foo/*2*/.bar; + // const foo/*1*/: foo/*2*/.bar; // The foo at /*1*/ and /*2*/ will share same symbol with two meaning // block - scope variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, @@ -677,7 +677,7 @@ namespace ts { function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0); // Block-scoped variables cannot be used before their definition - let declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); + const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); @@ -727,9 +727,9 @@ namespace ts { } function getTargetOfImportClause(node: ImportClause): Symbol { - let moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); if (moduleSymbol) { - let exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); + const exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol) { error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -738,13 +738,13 @@ namespace ts { } function getTargetOfNamespaceImport(node: NamespaceImport): Symbol { - let moduleSpecifier = (node.parent.parent).moduleSpecifier; + const moduleSpecifier = (node.parent.parent).moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function getMemberOfModuleVariable(moduleSymbol: Symbol, name: string): Symbol { if (moduleSymbol.flags & SymbolFlags.Variable) { - let typeAnnotation = (moduleSymbol.valueDeclaration).type; + const typeAnnotation = (moduleSymbol.valueDeclaration).type; if (typeAnnotation) { return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); } @@ -773,7 +773,7 @@ namespace ts { if (valueSymbol.flags & (SymbolFlags.Type | SymbolFlags.Namespace)) { return valueSymbol; } - let result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); + const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); result.declarations = concatenate(valueSymbol.declarations, typeSymbol.declarations); result.parent = valueSymbol.parent || typeSymbol.parent; if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; @@ -784,7 +784,7 @@ namespace ts { function getExportOfModule(symbol: Symbol, name: string): Symbol { if (symbol.flags & SymbolFlags.Module) { - let exports = getExportsOfSymbol(symbol); + const exports = getExportsOfSymbol(symbol); if (hasProperty(exports, name)) { return resolveSymbol(exports[name]); } @@ -793,7 +793,7 @@ namespace ts { function getPropertyOfVariable(symbol: Symbol, name: string): Symbol { if (symbol.flags & SymbolFlags.Variable) { - let typeAnnotation = (symbol.valueDeclaration).type; + const typeAnnotation = (symbol.valueDeclaration).type; if (typeAnnotation) { return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } @@ -801,14 +801,14 @@ namespace ts { } function getExternalModuleMember(node: ImportDeclaration | ExportDeclaration, specifier: ImportOrExportSpecifier): Symbol { - let moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - let targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + const targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - let name = specifier.propertyName || specifier.name; + const name = specifier.propertyName || specifier.name; if (name.text) { - let symbolFromModule = getExportOfModule(targetSymbol, name.text); - let symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - let symbol = symbolFromModule && symbolFromVariable ? + const symbolFromModule = getExportOfModule(targetSymbol, name.text); + const symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); + const symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { @@ -856,11 +856,11 @@ namespace ts { function resolveAlias(symbol: Symbol): Symbol { Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here."); - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.target) { links.target = resolvingSymbol; - let node = getDeclarationOfAliasSymbol(symbol); - let target = getTargetOfAliasDeclaration(node); + const node = getDeclarationOfAliasSymbol(symbol); + const target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; } @@ -875,10 +875,10 @@ namespace ts { } function markExportAsReferenced(node: ImportEqualsDeclaration | ExportAssignment | ExportSpecifier) { - let symbol = getSymbolOfNode(node); - let target = resolveAlias(symbol); + const symbol = getSymbolOfNode(node); + const target = resolveAlias(symbol); if (target) { - let markAlias = + const markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & SymbolFlags.Value) && !isConstEnumOrConstEnumOnlyModule(target)); @@ -892,10 +892,10 @@ namespace ts { // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of // the alias as an expression (which recursively takes us back here if the target references another alias). function markAliasSymbolAsReferenced(symbol: Symbol) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.referenced) { links.referenced = true; - let node = getDeclarationOfAliasSymbol(symbol); + const node = getDeclarationOfAliasSymbol(symbol); if (node.kind === SyntaxKind.ExportAssignment) { // export default checkExpressionCached((node).expression); @@ -950,7 +950,7 @@ namespace ts { let symbol: Symbol; if (name.kind === SyntaxKind.Identifier) { - let message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; + const message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; symbol = resolveName(name, (name).text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { @@ -958,10 +958,10 @@ namespace ts { } } else if (name.kind === SyntaxKind.QualifiedName || name.kind === SyntaxKind.PropertyAccessExpression) { - let left = name.kind === SyntaxKind.QualifiedName ? (name).left : (name).expression; - let right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; + const left = name.kind === SyntaxKind.QualifiedName ? (name).left : (name).expression; + const right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; - let namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); + const namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); if (!namespace || namespace === unknownSymbol || nodeIsMissing(right)) { return undefined; } @@ -985,26 +985,26 @@ namespace ts { return; } - let moduleReferenceLiteral = moduleReferenceExpression; - let searchPath = getDirectoryPath(getSourceFile(location).fileName); + const moduleReferenceLiteral = moduleReferenceExpression; + const searchPath = getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. - let moduleName = escapeIdentifier(moduleReferenceLiteral.text); + const moduleName = escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - let isRelative = isExternalModuleNameRelative(moduleName); + const isRelative = isExternalModuleNameRelative(moduleName); if (!isRelative) { - let symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule); + const symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule); if (symbol) { return symbol; } } - let resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); - let sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + const resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + const sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return sourceFile.symbol; @@ -1046,12 +1046,12 @@ namespace ts { } function getExportsOfModule(moduleSymbol: Symbol): SymbolTable { - let links = getSymbolLinks(moduleSymbol); + const links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } function extendExportSymbols(target: SymbolTable, source: SymbolTable) { - for (let id in source) { + for (const id in source) { if (id !== "default" && !hasProperty(target, id)) { target[id] = source[id]; } @@ -1060,7 +1060,7 @@ namespace ts { function getExportsForModule(moduleSymbol: Symbol): SymbolTable { let result: SymbolTable; - let visitedSymbols: Symbol[] = []; + const visitedSymbols: Symbol[] = []; visit(moduleSymbol); return result || moduleSymbol.exports; @@ -1076,9 +1076,9 @@ namespace ts { extendExportSymbols(result, symbol.exports); } // All export * declarations are collected in an __export symbol by the binder - let exportStars = symbol.exports["__export"]; + const exportStars = symbol.exports["__export"]; if (exportStars) { - for (let node of exportStars.declarations) { + for (const node of exportStars.declarations) { visit(resolveExternalModuleName(node, (node).moduleSpecifier)); } } @@ -1126,8 +1126,8 @@ namespace ts { } function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration { - let members = node.members; - for (let member of members) { + const members = node.members; + for (const member of members) { if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; } @@ -1135,19 +1135,19 @@ namespace ts { } function createType(flags: TypeFlags): Type { - let result = new Type(checker, flags); + const result = new Type(checker, flags); result.id = typeCount++; return result; } function createIntrinsicType(kind: TypeFlags, intrinsicName: string): IntrinsicType { - let type = createType(kind); + const type = createType(kind); type.intrinsicName = intrinsicName; return type; } function createObjectType(kind: TypeFlags, symbol?: Symbol): ObjectType { - let type = createType(kind); + const type = createType(kind); type.symbol = symbol; return type; } @@ -1165,11 +1165,11 @@ namespace ts { function getNamedMembers(members: SymbolTable): Symbol[] { let result: Symbol[]; - for (let id in members) { + for (const id in members) { if (hasProperty(members, id)) { if (!isReservedMemberName(id)) { if (!result) result = []; - let symbol = members[id]; + const symbol = members[id]; if (symbolIsValue(symbol)) { result.push(symbol); } @@ -1239,7 +1239,7 @@ namespace ts { } // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - let accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + const accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); return !!accessibleParent; } @@ -1267,14 +1267,14 @@ namespace ts { // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { - let resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - let accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + const accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -1319,13 +1319,13 @@ namespace ts { function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { - let initialSymbol = symbol; + const initialSymbol = symbol; let meaningToLook = meaning; while (symbol) { // Symbol is accessible if it by itself is accessible - let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - let hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); if (!hasAccessibleDeclarations) { return { accessibility: SymbolAccessibility.NotAccessible, @@ -1343,7 +1343,7 @@ namespace ts { // export class c { // } // } - // let x: typeof m.c + // const x: typeof m.c // In the above example when we start with checking if typeof m.c symbol is accessible, // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible @@ -1354,9 +1354,9 @@ namespace 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 - let symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); + const symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { - let enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { @@ -1402,7 +1402,7 @@ namespace ts { // Mark the unexported alias as visible if its parent is visible // because these kind of aliases can be used to name types in declaration file - let anyImportSyntax = getAnyImportSyntax(declaration); + const anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && !(anyImportSyntax.flags & NodeFlags.Export) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { @@ -1444,8 +1444,8 @@ namespace ts { meaning = SymbolFlags.Type; } - let firstIdentifier = getFirstIdentifier(entityName); - let symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + const firstIdentifier = getFirstIdentifier(entityName); + const symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol)) || { @@ -1468,30 +1468,30 @@ namespace ts { } function symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - let result = writer.string(); + const result = writer.string(); releaseStringWriter(writer); return result; } function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - let result = writer.string(); + const result = writer.string(); releaseStringWriter(writer); return result; } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); let result = writer.string(); releaseStringWriter(writer); - let maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; + const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; if (maxLength && result.length >= maxLength) { result = result.substr(0, maxLength - "...".length) + "..."; } @@ -1515,7 +1515,7 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { if (symbol.declarations && symbol.declarations.length) { - let declaration = symbol.declarations[0]; + const declaration = symbol.declarations[0]; if (declaration.name) { return declarationNameToString(declaration.name); } @@ -1562,7 +1562,7 @@ namespace ts { appendSymbolNameOnly(symbol, writer); } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // const the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -1572,7 +1572,7 @@ namespace ts { writer.trackSymbol(symbol, enclosingDeclaration, meaning); function walkSymbol(symbol: Symbol, meaning: SymbolFlags): void { if (symbol) { - let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -1584,7 +1584,7 @@ namespace ts { } if (accessibleSymbolChain) { - for (let accessibleSymbol of accessibleSymbolChain) { + for (const accessibleSymbol of accessibleSymbolChain) { appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -1607,8 +1607,8 @@ namespace ts { // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically // asked for it - let isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - let typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; + const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; + const typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { walkSymbol(symbol, meaning); return; @@ -1618,7 +1618,7 @@ namespace ts { } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { - let globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; + const globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; let inObjectTypeLiteral = false; return writeType(type, globalFlags); @@ -1697,7 +1697,7 @@ namespace ts { } function writeTypeReference(type: TypeReference, flags: TypeFormatFlags) { - let typeArguments = type.typeArguments || emptyArray; + const typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & TypeFormatFlags.WriteArrayAsGenericType)) { writeType(typeArguments[0], TypeFormatFlags.InElementType); writePunctuation(writer, SyntaxKind.OpenBracketToken); @@ -1707,14 +1707,14 @@ namespace ts { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those // type parameters. - let outerTypeParameters = type.target.outerTypeParameters; + const outerTypeParameters = type.target.outerTypeParameters; let i = 0; if (outerTypeParameters) { - let length = outerTypeParameters.length; + const length = outerTypeParameters.length; while (i < length) { // Find group of type arguments for type parameters with the same declaring container. - let start = i; - let parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + const start = i; + const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; } while (i < length && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); @@ -1726,7 +1726,7 @@ namespace ts { } } } - let typeParameterCount = (type.target.typeParameters || emptyArray).length; + const typeParameterCount = (type.target.typeParameters || emptyArray).length; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } @@ -1748,7 +1748,7 @@ namespace ts { } function writeAnonymousType(type: ObjectType, flags: TypeFormatFlags) { - let symbol = type.symbol; + const symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { @@ -1759,7 +1759,7 @@ namespace ts { } else if (contains(symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name - let typeAlias = getTypeAliasForTypeLiteral(type); + const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); @@ -1786,9 +1786,9 @@ namespace ts { } function shouldWriteTypeOfFunctionSymbol() { - let isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method + const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method forEach(symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); - let isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && + const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && (symbol.parent || // is exported function symbol forEach(symbol.declarations, declaration => declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); @@ -1807,7 +1807,7 @@ namespace ts { } function getIndexerParameterName(type: ObjectType, indexKind: IndexKind, fallbackName: string): string { - let declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); + const declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); if (!declaration) { // declaration might not be found if indexer was added from the contextual type. // in this case use fallback name @@ -1818,7 +1818,7 @@ namespace ts { } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, SyntaxKind.OpenBraceToken); @@ -1850,17 +1850,17 @@ namespace ts { } } - let saveInObjectTypeLiteral = inObjectTypeLiteral; + const saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; writePunctuation(writer, SyntaxKind.OpenBraceToken); writer.writeLine(); writer.increaseIndent(); - for (let signature of resolved.callSignatures) { + for (const signature of resolved.callSignatures) { buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (let signature of resolved.constructSignatures) { + for (const signature of resolved.constructSignatures) { writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); @@ -1896,11 +1896,11 @@ namespace ts { writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (let p of resolved.properties) { - let t = getTypeOfSymbol(p); + for (const p of resolved.properties) { + const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { - let signatures = getSignaturesOfType(t, SignatureKind.Call); - for (let signature of signatures) { + const signatures = getSignaturesOfType(t, SignatureKind.Call); + for (const signature of signatures) { buildSymbolDisplay(p, writer); if (p.flags & SymbolFlags.Optional) { writePunctuation(writer, SyntaxKind.QuestionToken); @@ -1929,7 +1929,7 @@ namespace ts { } function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { - let targetSymbol = getTargetSymbol(symbol); + const targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface || targetSymbol.flags & SymbolFlags.TypeAlias) { buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } @@ -1937,7 +1937,7 @@ namespace ts { function buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { appendSymbolNameOnly(tp.symbol, writer); - let constraint = getConstraintOfTypeParameter(tp); + const constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, SyntaxKind.ExtendsKeyword); @@ -1947,7 +1947,7 @@ namespace ts { } function buildParameterDisplay(p: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { - let parameterNode = p.valueDeclaration; + const parameterNode = p.valueDeclaration; if (isRestParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.DotDotDotToken); } @@ -2069,14 +2069,14 @@ namespace ts { function isUsedInExportAssignment(node: Node) { // Get source File and see if it is external module and has export assigned symbol - let externalModule = getContainingExternalModule(node); + const externalModule = getContainingExternalModule(node); let exportAssignmentSymbol: Symbol; let resolvedExportSymbol: Symbol; if (externalModule) { // This is export assigned symbol node - let externalModuleSymbol = getSymbolOfNode(externalModule); + const externalModuleSymbol = getSymbolOfNode(externalModule); exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - let symbolOfNode = getSymbolOfNode(node); + const symbolOfNode = getSymbolOfNode(node); if (isSymbolUsedInExportAssignment(symbolOfNode)) { return true; } @@ -2131,7 +2131,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ImportEqualsDeclaration: - let parent = getDeclarationContainer(node); + const parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(getCombinedNodeFlags(node) & NodeFlags.Export) && !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) { @@ -2150,7 +2150,7 @@ namespace ts { // Private/protected properties/methods are not visible return false; } - // Public properties/methods are visible if its parents are visible, so let it fall into next case statement + // Public properties/methods are visible if its parents are visible, so const it fall into next case statement case SyntaxKind.Constructor: case SyntaxKind.ConstructSignature: @@ -2192,7 +2192,7 @@ namespace ts { } if (node) { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (links.isVisible === undefined) { links.isVisible = !!determineIfDeclarationIsVisible(); } @@ -2206,12 +2206,12 @@ namespace ts { exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { - let exportSpecifier = node.parent; + const exportSpecifier = node.parent; exportSymbol = (exportSpecifier.parent.parent).moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } - let result: Node[] = []; + const result: Node[] = []; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } @@ -2220,16 +2220,16 @@ namespace ts { function buildVisibleNodeList(declarations: Declaration[]) { forEach(declarations, declaration => { getNodeLinks(declaration).isVisible = true; - let resultNode = getAnyImportSyntax(declaration) || declaration; + const resultNode = getAnyImportSyntax(declaration) || declaration; if (!contains(result, resultNode)) { result.push(resultNode); } if (isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible - let internalModuleReference = (declaration).moduleReference; - let firstIdentifier = getFirstIdentifier(internalModuleReference); - let importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, + const internalModuleReference = (declaration).moduleReference; + const firstIdentifier = getFirstIdentifier(internalModuleReference); + const importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, firstIdentifier); buildVisibleNodeList(importSymbol.declarations); } @@ -2249,10 +2249,10 @@ namespace ts { * @param propertyName The property name that should be used to query the target for its type */ function pushTypeResolution(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): boolean { - let resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - let { length } = resolutionTargets; + const { length } = resolutionTargets; for (let i = resolutionCycleStartIndex; i < length; i++) { resolutionResults[i] = false; } @@ -2316,13 +2316,13 @@ namespace ts { // Every class automatically contains a static property member named 'prototype', // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. // It is an error to explicitly declare a static property member with the name 'prototype'. - let classType = getDeclaredTypeOfSymbol(prototype.parent); + const classType = getDeclaredTypeOfSymbol(prototype.parent); return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, _ => anyType)) : classType; } // Return the type of the given property in the given type, or undefined if no such property exists function getTypeOfPropertyOfType(type: Type, name: string): Type { - let prop = getPropertyOfType(type, name); + const prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } @@ -2333,7 +2333,7 @@ namespace ts { // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node: VariableLikeDeclaration) { - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } @@ -2359,8 +2359,8 @@ namespace ts { // Return the inferred type for a binding element function getTypeForBindingElement(declaration: BindingElement): Type { - let pattern = declaration.parent; - let parentType = getTypeForBindingElementParent(pattern.parent); + const pattern = declaration.parent; + const parentType = getTypeForBindingElementParent(pattern.parent); // If parent has the unknown (error) type, then so does this binding element if (parentType === unknownType) { return unknownType; @@ -2378,7 +2378,7 @@ namespace ts { let type: Type; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - let name = declaration.propertyName || declaration.name; + const name = declaration.propertyName || declaration.name; if (isComputedNonLiteralName(name)) { // computed properties with non-literal names are treated as 'any' return anyType; @@ -2386,7 +2386,7 @@ namespace ts { // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. - let text = getTextOfPropertyName(name); + const text = getTextOfPropertyName(name); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, IndexKind.Number) || @@ -2400,10 +2400,10 @@ namespace ts { // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - let elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); + const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); if (!declaration.dotDotDotToken) { // Use specific property type when parent is a tuple or numeric index type when parent is an array - let propName = "" + indexOf(pattern.elements, declaration); + const propName = "" + indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -2450,16 +2450,16 @@ namespace ts { } if (declaration.kind === SyntaxKind.Parameter) { - let func = declaration.parent; + const func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { - let getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } } // Use contextual parameter type if one is available - let type = getContextuallyTypedParameterType(declaration); + const type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -2499,23 +2499,22 @@ namespace ts { // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type { - let members: SymbolTable = {}; + const members: SymbolTable = {}; forEach(pattern.elements, e => { - let name = e.propertyName || e.name; + const name = e.propertyName || e.name; if (isComputedNonLiteralName(name)) { // do not include computed properties in the implied type return; } - let text = getTextOfPropertyName(name); - let flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); - - let symbol = createSymbol(flags, text); + const text = getTextOfPropertyName(name); + const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); + const symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); - let result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + const result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); if (includePatternInType) { result.pattern = pattern; } @@ -2524,14 +2523,14 @@ namespace ts { // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type { - let elements = pattern.elements; + const elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - let elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType)); + const elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType)); if (includePatternInType) { - let result = createNewTupleType(elementTypes); + const result = createNewTupleType(elementTypes); result.pattern = pattern; return result; } @@ -2577,7 +2576,7 @@ namespace ts { // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { - let root = getRootDeclaration(declaration); + const root = getRootDeclaration(declaration); if (!isPrivateWithinAmbient(root) && !(root.kind === SyntaxKind.Parameter && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } @@ -2586,14 +2585,14 @@ namespace ts { } function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { // Handle prototype property if (symbol.flags & SymbolFlags.Prototype) { return links.type = getTypeOfPrototypeProperty(symbol); } // Handle catch clause variables - let declaration = symbol.valueDeclaration; + const declaration = symbol.valueDeclaration; if (declaration.parent.kind === SyntaxKind.CatchClause) { return links.type = anyType; } @@ -2633,7 +2632,7 @@ namespace ts { return accessor.type && getTypeFromTypeNode(accessor.type); } else { - let setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); + const setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); } } @@ -2641,22 +2640,22 @@ namespace ts { } function getTypeOfAccessors(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } - let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - let setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); let type: Type; // First try to see if the user specified a return type on the get-accessor. - let getterReturnType = getAnnotatedAccessorType(getter); + const getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { type = getterReturnType; } else { // If the user didn't specify a return type, try to use the set-accessor's parameter type. - let setterParameterType = getAnnotatedAccessorType(setter); + const setterParameterType = getAnnotatedAccessorType(setter); if (setterParameterType) { type = setterParameterType; } @@ -2677,7 +2676,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -2687,7 +2686,7 @@ namespace ts { } function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = createObjectType(TypeFlags.Anonymous, symbol); } @@ -2695,7 +2694,7 @@ namespace ts { } function getTypeOfEnumMember(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); } @@ -2703,9 +2702,9 @@ namespace ts { } function getTypeOfAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { - let targetSymbol = resolveAlias(symbol); + const targetSymbol = resolveAlias(symbol); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a @@ -2720,7 +2719,7 @@ namespace ts { } function getTypeOfInstantiatedSymbol(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); } @@ -2756,7 +2755,7 @@ namespace ts { function hasBaseType(type: InterfaceType, checkBase: InterfaceType) { return check(type); function check(type: InterfaceType): boolean { - let target = getTargetType(type); + const target = getTargetType(type); return target === checkBase || forEach(getBaseTypes(target), check); } } @@ -2765,8 +2764,8 @@ namespace ts { // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters: TypeParameter[], declarations: TypeParameterDeclaration[]): TypeParameter[] { - for (let declaration of declarations) { - let tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + for (const declaration of declarations) { + const tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; } @@ -2789,7 +2788,7 @@ namespace ts { if (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.ArrowFunction) { - let declarations = (node).typeParameters; + const declarations = (node).typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); } @@ -2799,7 +2798,7 @@ namespace ts { // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - let declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); return appendOuterTypeParameters(undefined, declaration); } @@ -2807,10 +2806,10 @@ namespace ts { // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): TypeParameter[] { let result: TypeParameter[]; - for (let node of symbol.declarations) { + for (const node of symbol.declarations) { if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.TypeAliasDeclaration) { - let declaration = node; + const declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); } @@ -2834,7 +2833,7 @@ namespace ts { } function getConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { - let typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + const typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount); } @@ -2842,7 +2841,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - let typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments)); } return signatures; @@ -2855,14 +2854,14 @@ namespace ts { // an object type with at least one construct signature. function getBaseConstructorTypeOfClass(type: InterfaceType): ObjectType { if (!type.resolvedBaseConstructorType) { - let baseTypeNode = getBaseTypeNodeOfClass(type); + const baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } if (!pushTypeResolution(type, TypeSystemPropertyName.ResolvedBaseConstructorType)) { return unknownType; } - let baseConstructorType = checkExpression(baseTypeNode.expression); + const baseConstructorType = checkExpression(baseTypeNode.expression); if (baseConstructorType.flags & TypeFlags.ObjectType) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. @@ -2886,8 +2885,8 @@ namespace ts { } function getBaseTypes(type: InterfaceType): ObjectType[] { - let isClass = type.symbol.flags & SymbolFlags.Class; - let isInterface = type.symbol.flags & SymbolFlags.Interface; + const isClass = type.symbol.flags & SymbolFlags.Class; + const isInterface = type.symbol.flags & SymbolFlags.Interface; if (!type.resolvedBaseTypes) { if (!isClass && !isInterface) { Debug.fail("type must be class or interface"); @@ -2904,11 +2903,11 @@ namespace ts { function resolveBaseTypesOfClass(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - let baseContructorType = getBaseConstructorTypeOfClass(type); + const baseContructorType = getBaseConstructorTypeOfClass(type); if (!(baseContructorType.flags & TypeFlags.ObjectType)) { return; } - let baseTypeNode = getBaseTypeNodeOfClass(type); + const baseTypeNode = getBaseTypeNodeOfClass(type); let baseType: Type; if (baseContructorType.symbol && baseContructorType.symbol.flags & SymbolFlags.Class) { // When base constructor type is a class we know that the constructors all have the same type parameters as the @@ -2920,7 +2919,7 @@ namespace ts { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere // we check that all instantiated signatures return the same type. - let constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + const constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -2949,10 +2948,10 @@ namespace ts { function resolveBaseTypesOfInterface(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (let declaration of type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { - for (let node of getInterfaceBaseTypeNodes(declaration)) { - let baseType = getTypeFromTypeNode(node); + for (const node of getInterfaceBaseTypeNodes(declaration)) { + const baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -2980,16 +2979,16 @@ namespace ts { // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, // and if none of the base interfaces have a "this" type. function isIndependentInterface(symbol: Symbol): boolean { - for (let declaration of symbol.declarations) { + for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration) { if (declaration.flags & NodeFlags.ContainsThis) { return false; } - let baseTypeNodes = getInterfaceBaseTypeNodes(declaration); + const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (let node of baseTypeNodes) { + for (const node of baseTypeNodes) { if (isSupportedExpressionWithTypeArguments(node)) { - let baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true); + const baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & SymbolFlags.Interface) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -3002,12 +3001,12 @@ namespace ts { } function getDeclaredTypeOfClassOrInterface(symbol: Symbol): InterfaceType { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; - let type = links.declaredType = createObjectType(kind, symbol); - let outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - let localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + const kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; + const type = links.declaredType = createObjectType(kind, symbol); + const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, // property types inferred from initializers and method return types inferred from return statements are very hard @@ -3031,14 +3030,14 @@ namespace ts { } function getDeclaredTypeOfTypeAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique // identity for resolution of the 'type' property in SymbolLinks. if (!pushTypeResolution(symbol, TypeSystemPropertyName.DeclaredType)) { return unknownType; } - let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + const declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); let type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -3059,9 +3058,9 @@ namespace ts { } function getDeclaredTypeOfEnum(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let type = createType(TypeFlags.Enum); + const type = createType(TypeFlags.Enum); type.symbol = symbol; links.declaredType = type; } @@ -3069,9 +3068,9 @@ namespace ts { } function getDeclaredTypeOfTypeParameter(symbol: Symbol): TypeParameter { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let type = createType(TypeFlags.TypeParameter); + const type = createType(TypeFlags.TypeParameter); type.symbol = symbol; if (!(getDeclarationOfKind(symbol, SyntaxKind.TypeParameter)).constraint) { type.constraint = noConstraintType; @@ -3082,7 +3081,7 @@ namespace ts { } function getDeclaredTypeOfAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); } @@ -3112,7 +3111,7 @@ namespace ts { // A type reference is considered independent if each type argument is considered independent. function isIndependentTypeReference(node: TypeReferenceNode): boolean { if (node.typeArguments) { - for (let typeNode of node.typeArguments) { + for (const typeNode of node.typeArguments) { if (!isIndependentType(typeNode)) { return false; } @@ -3154,7 +3153,7 @@ namespace ts { if (node.kind !== SyntaxKind.Constructor && (!node.type || !isIndependentType(node.type))) { return false; } - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { if (!isIndependentVariableLikeDeclaration(parameter)) { return false; } @@ -3169,7 +3168,7 @@ namespace ts { // assumed not to be free of "this" references. function isIndependentMember(symbol: Symbol): boolean { if (symbol.declarations && symbol.declarations.length === 1) { - let declaration = symbol.declarations[0]; + const declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: @@ -3186,8 +3185,8 @@ namespace ts { } function createSymbolTable(symbols: Symbol[]): SymbolTable { - let result: SymbolTable = {}; - for (let symbol of symbols) { + const result: SymbolTable = {}; + for (const symbol of symbols) { result[symbol.name] = symbol; } return result; @@ -3196,15 +3195,15 @@ namespace ts { // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper, mappingThisOnly: boolean): SymbolTable { - let result: SymbolTable = {}; - for (let symbol of symbols) { + const result: SymbolTable = {}; + for (const symbol of symbols) { result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols: SymbolTable, baseSymbols: Symbol[]) { - for (let s of baseSymbols) { + for (const s of baseSymbols) { if (!hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -3213,7 +3212,7 @@ namespace ts { function addInheritedSignatures(signatures: Signature[], baseSignatures: Signature[]) { if (baseSignatures) { - for (let signature of baseSignatures) { + for (const signature of baseSignatures) { signatures.push(signature); } } @@ -3221,7 +3220,7 @@ namespace ts { function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { if (!(type).declaredProperties) { - let symbol = type.symbol; + const symbol = type.symbol; (type).declaredProperties = getNamedMembers(symbol.members); (type).declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); (type).declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); @@ -3254,14 +3253,14 @@ namespace ts { stringIndexType = instantiateType(source.declaredStringIndexType, mapper); numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); } - let baseTypes = getBaseTypes(source); + const baseTypes = getBaseTypes(source); if (baseTypes.length) { if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } - let thisArgument = lastOrUndefined(typeArguments); - for (let baseType of baseTypes) { - let instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + const thisArgument = lastOrUndefined(typeArguments); + for (const baseType of baseTypes) { + const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct)); @@ -3277,16 +3276,16 @@ namespace ts { } function resolveTypeReferenceMembers(type: TypeReference): void { - let source = resolveDeclaredMembers(type.target); - let typeParameters = concatenate(source.typeParameters, [source.thisType]); - let typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + const source = resolveDeclaredMembers(type.target); + const typeParameters = concatenate(source.typeParameters, [source.thisType]); + const typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? type.typeArguments : concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { - let sig = new Signature(checker); + const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -3307,16 +3306,16 @@ namespace ts { if (!hasClassBaseType(classType)) { return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - let baseConstructorType = getBaseConstructorTypeOfClass(classType); - let baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); - let baseTypeNode = getBaseTypeNodeOfClass(classType); - let typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); - let typeArgCount = typeArguments ? typeArguments.length : 0; - let result: Signature[] = []; - for (let baseSig of baseSignatures) { - let typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + const baseConstructorType = getBaseConstructorTypeOfClass(classType); + const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); + const baseTypeNode = getBaseTypeNodeOfClass(classType); + const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + const typeArgCount = typeArguments ? typeArguments.length : 0; + const result: Signature[] = []; + for (const baseSig of baseSignatures) { + const typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - let sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + const sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -3326,9 +3325,9 @@ namespace ts { } function createTupleTypeMemberSymbols(memberTypes: Type[]): SymbolTable { - let members: SymbolTable = {}; + const members: SymbolTable = {}; for (let i = 0; i < memberTypes.length; i++) { - let symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); + const symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); symbol.type = memberTypes[i]; members[i] = symbol; } @@ -3336,16 +3335,16 @@ namespace ts { } function resolveTupleTypeMembers(type: TupleType) { - let arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); + const arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); // Make the tuple type itself the 'this' type by including an extra type argument - let arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - let members = createTupleTypeMemberSymbols(type.elementTypes); + const arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + const members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreReturnTypes: boolean): Signature { - for (let s of signatureList) { + for (const s of signatureList) { if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -3369,7 +3368,7 @@ namespace ts { let result: Signature[] = undefined; for (let i = 0; i < signatureLists.length; i++) { // Allow matching non-generic signatures to have excess parameters and different return types - let match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true); + const match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true); if (!match) { return undefined; } @@ -3385,13 +3384,13 @@ namespace ts { // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { - let signatureLists = map(types, t => getSignaturesOfType(t, kind)); + const signatureLists = map(types, t => getSignaturesOfType(t, kind)); let result: Signature[] = undefined; for (let i = 0; i < signatureLists.length; i++) { - for (let signature of signatureLists[i]) { + for (const signature of signatureLists[i]) { // Only process signatures with parameter lists that aren't already in the result list if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) { - let unionSignatures = findMatchingSignatures(signatureLists, signature, i); + const unionSignatures = findMatchingSignatures(signatureLists, signature, i); if (unionSignatures) { let s = signature; // Union the result types when more than one signature matches @@ -3410,9 +3409,9 @@ namespace ts { } function getUnionIndexType(types: Type[], kind: IndexKind): Type { - let indexTypes: Type[] = []; - for (let type of types) { - let indexType = getIndexTypeOfType(type, kind); + const indexTypes: Type[] = []; + for (const type of types) { + const indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; } @@ -3424,10 +3423,10 @@ namespace ts { function resolveUnionTypeMembers(type: UnionType) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - let callSignatures = getUnionSignatures(type.types, SignatureKind.Call); - let constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); - let stringIndexType = getUnionIndexType(type.types, IndexKind.String); - let numberIndexType = getUnionIndexType(type.types, IndexKind.Number); + const callSignatures = getUnionSignatures(type.types, SignatureKind.Call); + const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); + const stringIndexType = getUnionIndexType(type.types, IndexKind.String); + const numberIndexType = getUnionIndexType(type.types, IndexKind.Number); setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); } @@ -3442,7 +3441,7 @@ namespace ts { let constructSignatures: Signature[] = emptyArray; let stringIndexType: Type = undefined; let numberIndexType: Type = undefined; - for (let t of type.types) { + for (const t of type.types) { callSignatures = concatenate(callSignatures, getSignaturesOfType(t, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(t, SignatureKind.Construct)); stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, IndexKind.String)); @@ -3452,7 +3451,7 @@ namespace ts { } function resolveAnonymousTypeMembers(type: AnonymousType) { - let symbol = type.symbol; + const symbol = type.symbol; let members: SymbolTable; let callSignatures: Signature[]; let constructSignatures: Signature[]; @@ -3485,12 +3484,12 @@ namespace ts { callSignatures = getSignaturesOfSymbol(symbol); } if (symbol.flags & SymbolFlags.Class) { - let classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - let baseConstructorType = getBaseConstructorTypeOfClass(classType); + const baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & TypeFlags.ObjectType) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); @@ -3538,9 +3537,9 @@ namespace ts { // return the symbol for that property.Otherwise return undefined. function getPropertyOfObjectType(type: Type, name: string): Symbol { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (hasProperty(resolved.members, name)) { - let symbol = resolved.members[name]; + const symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } @@ -3549,8 +3548,8 @@ namespace ts { } function getPropertiesOfUnionOrIntersectionType(type: UnionOrIntersectionType): Symbol[] { - for (let current of type.types) { - for (let prop of getPropertiesOfType(current)) { + for (const current of type.types) { + for (const prop of getPropertiesOfType(current)) { getPropertyOfUnionOrIntersectionType(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so @@ -3597,12 +3596,12 @@ namespace ts { } function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { - let types = containingType.types; + const types = containingType.types; let props: Symbol[]; - for (let current of types) { - let type = getApparentType(current); + for (const current of types) { + const type = getApparentType(current); if (type !== unknownType) { - let prop = getPropertyOfType(type, name); + const prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (NodeFlags.Private | NodeFlags.Protected))) { if (!props) { props = [prop]; @@ -3623,15 +3622,15 @@ namespace ts { if (props.length === 1) { return props[0]; } - let propTypes: Type[] = []; - let declarations: Declaration[] = []; - for (let prop of props) { + const propTypes: Type[] = []; + const declarations: Declaration[] = []; + for (const prop of props) { if (prop.declarations) { addRange(declarations, prop.declarations); } propTypes.push(getTypeOfSymbol(prop)); } - let result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty, name); + const result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -3639,11 +3638,11 @@ namespace ts { } function getPropertyOfUnionOrIntersectionType(type: UnionOrIntersectionType, name: string): Symbol { - let properties = type.resolvedProperties || (type.resolvedProperties = {}); + const properties = type.resolvedProperties || (type.resolvedProperties = {}); if (hasProperty(properties, name)) { return properties[name]; } - let property = createUnionOrIntersectionProperty(type, name); + const property = createUnionOrIntersectionProperty(type, name); if (property) { properties[name] = property; } @@ -3656,15 +3655,15 @@ namespace ts { function getPropertyOfType(type: Type, name: string): Symbol { type = getApparentType(type); if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (hasProperty(resolved.members, name)) { - let symbol = resolved.members[name]; + const symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - let symbol = getPropertyOfObjectType(globalFunctionType, name); + const symbol = getPropertyOfObjectType(globalFunctionType, name); if (symbol) { return symbol; } @@ -3679,7 +3678,7 @@ namespace ts { function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): Signature[] { if (type.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures; } return emptyArray; @@ -3694,18 +3693,18 @@ namespace ts { } function typeHasConstructSignatures(type: Type): boolean { - let apparentType = getApparentType(type); + const apparentType = getApparentType(type); if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Union)) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return resolved.constructSignatures.length > 0; } return false; } function typeHasCallOrConstructSignatures(type: Type): boolean { - let apparentType = getApparentType(type); + const apparentType = getApparentType(type); if (apparentType.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; } return false; @@ -3713,7 +3712,7 @@ namespace ts { function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type { if (type.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return kind === IndexKind.String ? resolved.stringIndexType : resolved.numberIndexType; } } @@ -3727,9 +3726,9 @@ namespace ts { // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations: TypeParameterDeclaration[]): TypeParameter[] { - let result: TypeParameter[] = []; + const result: TypeParameter[] = []; forEach(typeParameterDeclarations, node => { - let tp = getDeclaredTypeOfTypeParameter(node.symbol); + const tp = getDeclaredTypeOfTypeParameter(node.symbol); if (!contains(result, tp)) { result.push(tp); } @@ -3738,8 +3737,8 @@ namespace ts { } function symbolsToArray(symbols: SymbolTable): Symbol[] { - let result: Symbol[] = []; - for (let id in symbols) { + const result: Symbol[] = []; + for (const id in symbols) { if (!isReservedMemberName(id)) { result.push(symbols[id]); } @@ -3753,9 +3752,9 @@ namespace ts { } if (node.initializer) { - let signatureDeclaration = node.parent; - let signature = getSignatureFromDeclaration(signatureDeclaration); - let parameterIndex = signatureDeclaration.parameters.indexOf(node); + const signatureDeclaration = node.parent; + const signature = getSignatureFromDeclaration(signatureDeclaration); + const parameterIndex = signatureDeclaration.parameters.indexOf(node); Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -3764,18 +3763,18 @@ namespace ts { } function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { - let links = getNodeLinks(declaration); + const links = getNodeLinks(declaration); if (!links.resolvedSignature) { - let classType = declaration.kind === SyntaxKind.Constructor ? + const classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; - let typeParameters = classType ? classType.localTypeParameters : + const typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; - let parameters: Symbol[] = []; + const parameters: Symbol[] = []; let hasStringLiterals = false; let minArgumentCount = -1; for (let i = 0, n = declaration.parameters.length; i < n; i++) { - let param = declaration.parameters[i]; + const param = declaration.parameters[i]; parameters.push(param.symbol); if (param.type && param.type.kind === SyntaxKind.StringLiteral) { hasStringLiterals = true; @@ -3804,7 +3803,7 @@ namespace ts { else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); if (declaration.type.kind === SyntaxKind.TypePredicate) { - let typePredicateNode = declaration.type; + const typePredicateNode = declaration.type; typePredicate = { parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, @@ -3816,7 +3815,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. if (declaration.kind === SyntaxKind.GetAccessor && !hasDynamicName(declaration)) { - let setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); + const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); returnType = getAnnotatedAccessorType(setter); } @@ -3833,9 +3832,9 @@ namespace ts { function getSignaturesOfSymbol(symbol: Symbol): Signature[] { if (!symbol) return emptyArray; - let result: Signature[] = []; + const result: Signature[] = []; for (let i = 0, len = symbol.declarations.length; i < len; i++) { - let node = symbol.declarations[i]; + const node = symbol.declarations[i]; switch (node.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -3854,7 +3853,7 @@ namespace ts { // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). if (i > 0 && (node).body) { - let previous = symbol.declarations[i - 1]; + const previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { break; } @@ -3883,7 +3882,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - let declaration = signature.declaration; + const declaration = signature.declaration; if (declaration.name) { error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); } @@ -3899,7 +3898,7 @@ namespace ts { function getRestTypeOfSignature(signature: Signature): Type { if (signature.hasRestParameter) { - let type = getTypeOfSymbol(lastOrUndefined(signature.parameters)); + const type = getTypeOfSymbol(lastOrUndefined(signature.parameters)); if (type.flags & TypeFlags.Reference && (type).target === globalArrayType) { return (type).typeArguments[0]; } @@ -3930,8 +3929,8 @@ namespace ts { // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - let isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; - let type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); + const isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; + const type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -3947,13 +3946,13 @@ namespace ts { } function getIndexDeclarationOfSymbol(symbol: Symbol, kind: IndexKind): SignatureDeclaration { - let syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; - let indexSymbol = getIndexSymbol(symbol); + const syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; + const indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { - for (let decl of indexSymbol.declarations) { - let node = decl; + for (const decl of indexSymbol.declarations) { + const node = decl; if (node.parameters.length === 1) { - let parameter = node.parameters[0]; + const parameter = node.parameters[0]; if (parameter && parameter.type && parameter.type.kind === syntaxKind) { return node; } @@ -3965,7 +3964,7 @@ namespace ts { } function getIndexTypeOfSymbol(symbol: Symbol, kind: IndexKind): Type { - let declaration = getIndexDeclarationOfSymbol(symbol, kind); + const declaration = getIndexDeclarationOfSymbol(symbol, kind); return declaration ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; @@ -3974,7 +3973,7 @@ namespace ts { function getConstraintOfTypeParameter(type: TypeParameter): Type { if (!type.constraint) { if (type.target) { - let targetConstraint = getConstraintOfTypeParameter(type.target); + const targetConstraint = getConstraintOfTypeParameter(type.target); type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { @@ -4015,17 +4014,17 @@ namespace ts { // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types: Type[]): TypeFlags { let result: TypeFlags = 0; - for (let type of types) { + for (const type of types) { result |= type.flags; } return result & TypeFlags.PropagatingFlags; } function createTypeReference(target: GenericType, typeArguments: Type[]): TypeReference { - let id = getTypeListId(typeArguments); + const id = getTypeListId(typeArguments); let type = target.instantiations[id]; if (!type) { - let flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); + const flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -4034,7 +4033,7 @@ namespace ts { } function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode | ExpressionWithTypeArguments, typeParameterSymbol: Symbol): boolean { - let links = getNodeLinks(typeReferenceNode); + const links = getNodeLinks(typeReferenceNode); if (links.isIllegalTypeReferenceInConstraint !== undefined) { return links.isIllegalTypeReferenceInConstraint; } @@ -4054,9 +4053,9 @@ namespace ts { let typeParameterSymbol: Symbol; function check(n: Node): void { if (n.kind === SyntaxKind.TypeReference && (n).typeName.kind === SyntaxKind.Identifier) { - let links = getNodeLinks(n); + const links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { - let symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + const symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol.flags & SymbolFlags.TypeParameter)) { // TypeScript 1.0 spec (April 2014): 3.4.1 // Type parameters declared in a particular type parameter list @@ -4084,8 +4083,8 @@ namespace ts { // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { - let type = getDeclaredTypeOfSymbol(symbol); - let typeParameters = type.localTypeParameters; + const type = getDeclaredTypeOfSymbol(symbol); + const typeParameters = type.localTypeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType), typeParameters.length); @@ -4107,16 +4106,16 @@ namespace ts { // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { - let type = getDeclaredTypeOfSymbol(symbol); - let links = getSymbolLinks(symbol); - let typeParameters = links.typeParameters; + const type = getDeclaredTypeOfSymbol(symbol); + const links = getSymbolLinks(symbol); + const typeParameters = links.typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - let typeArguments = map(node.typeArguments, getTypeFromTypeNode); - let id = getTypeListId(typeArguments); + const typeArguments = map(node.typeArguments, getTypeFromTypeNode); + const id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } if (node.typeArguments) { @@ -4143,14 +4142,14 @@ namespace ts { } function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - let typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : + const typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : isSupportedExpressionWithTypeArguments(node) ? (node).expression : undefined; - let symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; - let type = symbol === unknownSymbol ? unknownType : + const symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; + const type = symbol === unknownSymbol ? unknownType : symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : getTypeFromNonGenericTypeReference(node, symbol); @@ -4163,7 +4162,7 @@ namespace ts { } function getTypeFromTypeQueryNode(node: TypeQueryNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // TypeScript 1.0 spec (April 2014): 3.6.3 // The expression is processed as an identifier expression (section 4.3) @@ -4177,8 +4176,8 @@ namespace ts { function getTypeOfGlobalSymbol(symbol: Symbol, arity: number): ObjectType { function getTypeDeclaration(symbol: Symbol): Declaration { - let declarations = symbol.declarations; - for (let declaration of declarations) { + const declarations = symbol.declarations; + for (const declaration of declarations) { switch (declaration.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: @@ -4191,7 +4190,7 @@ namespace ts { if (!symbol) { return arity ? emptyGenericType : emptyObjectType; } - let type = getDeclaredTypeOfSymbol(symbol); + const type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & TypeFlags.ObjectType)) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; @@ -4228,8 +4227,8 @@ namespace ts { * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace: string, name: string): Type { - let namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); - let typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); + const namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); + const typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } @@ -4241,7 +4240,7 @@ namespace ts { * Creates a TypeReference for a generic `TypedPropertyDescriptor`. */ function createTypedPropertyDescriptorType(propertyType: Type): Type { - let globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + const globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); return globalTypedPropertyDescriptorType !== emptyGenericType ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) : emptyObjectType; @@ -4267,7 +4266,7 @@ namespace ts { } function getTypeFromArrayTypeNode(node: ArrayTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); } @@ -4275,18 +4274,18 @@ namespace ts { } function createTupleType(elementTypes: Type[]) { - let id = getTypeListId(elementTypes); + const id = getTypeListId(elementTypes); return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); } function createNewTupleType(elementTypes: Type[]) { - let type = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); + const type = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; return type; } function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNode)); } @@ -4305,7 +4304,7 @@ namespace ts { // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToSet(typeSet: Type[], types: Type[], typeSetKind: TypeFlags) { - for (let type of types) { + for (const type of types) { addTypeToSet(typeSet, type, typeSetKind); } } @@ -4330,7 +4329,7 @@ namespace ts { } function containsTypeAny(types: Type[]): boolean { - for (let type of types) { + for (const type of types) { if (isTypeAny(type)) { return true; } @@ -4359,7 +4358,7 @@ namespace ts { if (types.length === 0) { return emptyObjectType; } - let typeSet: Type[] = []; + const typeSet: Type[] = []; addTypesToSet(typeSet, types, TypeFlags.Union); if (containsTypeAny(typeSet)) { return anyType; @@ -4374,7 +4373,7 @@ namespace ts { if (typeSet.length === 1) { return typeSet[0]; } - let id = getTypeListId(typeSet); + const id = getTypeListId(typeSet); let type = unionTypes[id]; if (!type) { type = unionTypes[id] = createObjectType(TypeFlags.Union | getPropagatingFlagsOfTypes(typeSet)); @@ -4384,7 +4383,7 @@ namespace ts { } function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); } @@ -4400,7 +4399,7 @@ namespace ts { if (types.length === 0) { return emptyObjectType; } - let typeSet: Type[] = []; + const typeSet: Type[] = []; addTypesToSet(typeSet, types, TypeFlags.Intersection); if (containsTypeAny(typeSet)) { return anyType; @@ -4408,7 +4407,7 @@ namespace ts { if (typeSet.length === 1) { return typeSet[0]; } - let id = getTypeListId(typeSet); + const id = getTypeListId(typeSet); let type = intersectionTypes[id]; if (!type) { type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getPropagatingFlagsOfTypes(typeSet)); @@ -4418,7 +4417,7 @@ namespace ts { } function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNode)); } @@ -4426,7 +4425,7 @@ namespace ts { } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node: Node): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers links.resolvedType = createObjectType(TypeFlags.Anonymous, node.symbol); @@ -4439,13 +4438,13 @@ namespace ts { return stringLiteralTypes[node.text]; } - let type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); + const type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); type.text = getTextOfNode(node); return type; } function getTypeFromStringLiteral(node: StringLiteral): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getStringLiteralType(node); } @@ -4453,8 +4452,8 @@ namespace ts { } function getThisType(node: TypeNode): Type { - let container = getThisContainer(node, /*includeArrowFunctions*/ false); - let parent = container && container.parent; + const container = getThisContainer(node, /*includeArrowFunctions*/ false); + const parent = container && container.parent; if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) { if (!(container.flags & NodeFlags.Static) && (container.kind !== SyntaxKind.Constructor || isNodeDescendentOf(node, (container).body))) { @@ -4466,7 +4465,7 @@ namespace ts { } function getTypeFromThisTypeNode(node: TypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getThisType(node); } @@ -4517,7 +4516,7 @@ namespace ts { // Callers should first ensure this by calling isTypeNode case SyntaxKind.Identifier: case SyntaxKind.QualifiedName: - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: return unknownType; @@ -4526,8 +4525,8 @@ namespace ts { function instantiateList(items: T[], mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): T[] { if (items && items.length) { - let result: T[] = []; - for (let v of items) { + const result: T[] = []; + for (const v of items) { result.push(instantiator(v, mapper)); } return result; @@ -4572,7 +4571,7 @@ namespace ts { case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return t => { - for (let source of sources) { + for (const source of sources) { if (t === source) { return anyType; } @@ -4582,7 +4581,7 @@ namespace ts { } function createInferenceMapper(context: InferenceContext): TypeMapper { - let mapper: TypeMapper = t => { + const mapper: TypeMapper = t => { for (let i = 0; i < context.typeParameters.length; i++) { if (t === context.typeParameters[i]) { context.inferences[i].isFixed = true; @@ -4605,7 +4604,7 @@ namespace ts { } function instantiateTypeParameter(typeParameter: TypeParameter, mapper: TypeMapper): TypeParameter { - let result = createType(TypeFlags.TypeParameter); + const result = createType(TypeFlags.TypeParameter); result.symbol = typeParameter.symbol; if (typeParameter.constraint) { result.constraint = instantiateType(typeParameter.constraint, mapper); @@ -4631,7 +4630,7 @@ namespace ts { type: instantiateType(signature.typePredicate.type, mapper) }; } - let result = createSignature(signature.declaration, freshTypeParameters, + const result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, @@ -4643,7 +4642,7 @@ namespace ts { function instantiateSymbol(symbol: Symbol, mapper: TypeMapper): Symbol { if (symbol.flags & SymbolFlags.Instantiated) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases // always reference a non-aliases. @@ -4653,7 +4652,7 @@ namespace ts { // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - let result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); + const result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -4667,7 +4666,7 @@ namespace ts { function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper): ObjectType { if (mapper.instantiations) { - let cachedType = mapper.instantiations[type.id]; + const cachedType = mapper.instantiations[type.id]; if (cachedType) { return cachedType; } @@ -4676,7 +4675,7 @@ namespace ts { mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - let result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); + const result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); result.target = type; result.mapper = mapper; mapper.instantiations[type.id] = result; @@ -4744,9 +4743,9 @@ namespace ts { function getTypeWithoutSignatures(type: Type): Type { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - let result = createObjectType(TypeFlags.Anonymous, type.symbol); + const result = createObjectType(TypeFlags.Anonymous, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -4784,8 +4783,8 @@ namespace ts { } function isSignatureAssignableTo(source: Signature, target: Signature): boolean { - let sourceType = getOrCreateTypeFromSignature(source); - let targetType = getOrCreateTypeFromSignature(target); + const sourceType = getOrCreateTypeFromSignature(source); + const targetType = getOrCreateTypeFromSignature(target); return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); } @@ -4818,7 +4817,7 @@ namespace ts { Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - let result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + const result = isRelatedTo(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } @@ -4892,7 +4891,7 @@ namespace ts { } } - let saveErrorInfo = errorInfo; + const saveErrorInfo = errorInfo; // Note that the "each" checks must precede the "some" checks to produce the correct results if (source.flags & TypeFlags.Union) { @@ -4928,7 +4927,7 @@ namespace ts { constraint = emptyObjectType; } // Report constraint errors only if the constraint is not the empty object type - let reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + const reportConstraintErrors = reportErrors && constraint !== emptyObjectType; if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; @@ -4943,13 +4942,13 @@ namespace ts { } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - let apparentType = getApparentType(source); + const apparentType = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) { // Report structural errors only if we haven't reported any errors yet - let reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; + const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -5001,7 +5000,7 @@ namespace ts { } } else if (type.flags & TypeFlags.UnionOrIntersection) { - for (let t of (type).types) { + for (const t of (type).types) { if (isKnownProperty(t, name)) { return true; } @@ -5012,7 +5011,7 @@ namespace ts { function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { if (someConstituentTypeHasKind(target, TypeFlags.ObjectType)) { - for (let prop of getPropertiesOfObjectType(source)) { + for (const prop of getPropertiesOfObjectType(source)) { if (!isKnownProperty(target, prop.name)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -5031,9 +5030,9 @@ namespace ts { function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { let result = Ternary.True; - let sourceTypes = source.types; - for (let sourceType of sourceTypes) { - let related = typeRelatedToSomeType(sourceType, target, false); + const sourceTypes = source.types; + for (const sourceType of sourceTypes) { + const related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return Ternary.False; } @@ -5043,9 +5042,9 @@ namespace ts { } function typeRelatedToSomeType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { - let targetTypes = target.types; + const targetTypes = target.types; for (let i = 0, len = targetTypes.length; i < len; i++) { - let related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + const related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { return related; } @@ -5055,9 +5054,9 @@ namespace ts { function typeRelatedToEachType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { let result = Ternary.True; - let targetTypes = target.types; - for (let targetType of targetTypes) { - let related = isRelatedTo(source, targetType, reportErrors); + const targetTypes = target.types; + for (const targetType of targetTypes) { + const related = isRelatedTo(source, targetType, reportErrors); if (!related) { return Ternary.False; } @@ -5067,9 +5066,9 @@ namespace ts { } function someTypeRelatedToType(source: UnionOrIntersectionType, target: Type, reportErrors: boolean): Ternary { - let sourceTypes = source.types; + const sourceTypes = source.types; for (let i = 0, len = sourceTypes.length; i < len; i++) { - let related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + const related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -5079,9 +5078,9 @@ namespace ts { function eachTypeRelatedToType(source: UnionOrIntersectionType, target: Type, reportErrors: boolean): Ternary { let result = Ternary.True; - let sourceTypes = source.types; - for (let sourceType of sourceTypes) { - let related = isRelatedTo(sourceType, target, reportErrors); + const sourceTypes = source.types; + for (const sourceType of sourceTypes) { + const related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return Ternary.False; } @@ -5091,14 +5090,14 @@ namespace ts { } function typeArgumentsRelatedTo(source: TypeReference, target: TypeReference, reportErrors: boolean): Ternary { - let sources = source.typeArguments || emptyArray; - let targets = target.typeArguments || emptyArray; + const sources = source.typeArguments || emptyArray; + const targets = target.typeArguments || emptyArray; if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } let result = Ternary.True; for (let i = 0; i < targets.length; i++) { - let related = isRelatedTo(sources[i], targets[i], reportErrors); + const related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return Ternary.False; } @@ -5130,8 +5129,8 @@ namespace ts { if (overflow) { return Ternary.False; } - let id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; - let related = relation[id]; + const id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + const related = relation[id]; if (related !== undefined) { // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate // errors, we can use the cached value. Otherwise, recompute the relation @@ -5162,7 +5161,7 @@ namespace ts { maybeStack[depth] = {}; maybeStack[depth][id] = RelationComparisonResult.Succeeded; depth++; - let saveExpandingFlags = expandingFlags; + const saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; let result: Ternary; @@ -5187,9 +5186,9 @@ namespace ts { expandingFlags = saveExpandingFlags; depth--; if (result) { - let maybeCache = maybeStack[depth]; + const maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up - let destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; + const destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; copyMap(maybeCache, destinationCache); } else { @@ -5205,10 +5204,10 @@ namespace ts { return propertiesIdenticalTo(source, target); } let result = Ternary.True; - let properties = getPropertiesOfObjectType(target); - let requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); - for (let targetProp of properties) { - let sourceProp = getPropertyOfType(source, targetProp.name); + const properties = getPropertiesOfObjectType(target); + const requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); + for (const targetProp of properties) { + const sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -5220,8 +5219,8 @@ namespace ts { } } else if (!(targetProp.flags & SymbolFlags.Prototype)) { - let sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - let targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + const sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); + const targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); if (sourcePropFlags & NodeFlags.Private || targetPropFlags & NodeFlags.Private) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -5238,9 +5237,9 @@ namespace ts { } } else if (targetPropFlags & NodeFlags.Protected) { - let sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; - let sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - let targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; + const sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; + const targetClass = getDeclaredTypeOfSymbol(targetProp.parent); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, @@ -5256,7 +5255,7 @@ namespace ts { } return Ternary.False; } - let related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + const related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); @@ -5288,18 +5287,18 @@ namespace ts { if (!(source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType)) { return Ternary.False; } - let sourceProperties = getPropertiesOfObjectType(source); - let targetProperties = getPropertiesOfObjectType(target); + const sourceProperties = getPropertiesOfObjectType(source); + const targetProperties = getPropertiesOfObjectType(target); if (sourceProperties.length !== targetProperties.length) { return Ternary.False; } let result = Ternary.True; - for (let sourceProp of sourceProperties) { - let targetProp = getPropertyOfObjectType(target, sourceProp.name); + for (const sourceProp of sourceProperties) { + const targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return Ternary.False; } - let related = compareProperties(sourceProp, targetProp, isRelatedTo); + const related = compareProperties(sourceProp, targetProp, isRelatedTo); if (!related) { return Ternary.False; } @@ -5315,10 +5314,10 @@ namespace ts { if (target === anyFunctionType || source === anyFunctionType) { return Ternary.True; } - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); let result = Ternary.True; - let saveErrorInfo = errorInfo; + const saveErrorInfo = errorInfo; @@ -5332,8 +5331,8 @@ namespace ts { // sourceSig and targetSig are (possibly) undefined. // // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - let sourceSig = sourceSignatures[0]; - let targetSig = targetSignatures[0]; + const sourceSig = sourceSignatures[0]; + const targetSig = targetSignatures[0]; result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); if (result !== Ternary.True) { @@ -5341,13 +5340,13 @@ namespace ts { } } - outer: for (let t of targetSignatures) { + outer: for (const t of targetSignatures) { if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { let localErrors = reportErrors; - let checkedAbstractAssignability = false; - for (let s of sourceSignatures) { + const checkedAbstractAssignability = false; + for (const s of sourceSignatures) { if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) { - let related = signatureRelatedTo(s, t, localErrors); + const related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; errorInfo = saveErrorInfo; @@ -5365,8 +5364,8 @@ namespace ts { function abstractSignatureRelatedTo(source: Type, sourceSig: Signature, target: Type, targetSig: Signature) { if (sourceSig && targetSig) { - let sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - let targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); + const sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); + const targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); if (!sourceDecl) { // If the source object isn't itself a class declaration, it can be freely assigned, regardless @@ -5374,16 +5373,16 @@ namespace ts { return Ternary.True; } - let sourceErasedSignature = getErasedSignature(sourceSig); - let targetErasedSignature = getErasedSignature(targetSig); + const sourceErasedSignature = getErasedSignature(sourceSig); + const targetErasedSignature = getErasedSignature(targetSig); - let sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - let targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + const sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + const targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - let sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - let targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - let sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract; - let targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract; + const sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); + const targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); + const sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract; + const targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. @@ -5429,9 +5428,9 @@ namespace ts { target = getErasedSignature(target); let result = Ternary.True; for (let i = 0; i < checkCount; i++) { - let s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - let t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - let saveErrorInfo = errorInfo; + const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + const saveErrorInfo = errorInfo; let related = isRelatedTo(s, t, reportErrors); if (!related) { related = isRelatedTo(t, s, false); @@ -5449,16 +5448,16 @@ namespace ts { } if (source.typePredicate && target.typePredicate) { - let hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + const hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; let hasDifferentTypes: boolean; if (hasDifferentParameterIndex || (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { if (reportErrors) { - let sourceParamText = source.typePredicate.parameterName; - let targetParamText = target.typePredicate.parameterName; - let sourceTypeText = typeToString(source.typePredicate.type); - let targetTypeText = typeToString(target.typePredicate.type); + const sourceParamText = source.typePredicate.parameterName; + const targetParamText = target.typePredicate.parameterName; + const sourceTypeText = typeToString(source.typePredicate.type); + const targetTypeText = typeToString(target.typePredicate.type); if (hasDifferentParameterIndex) { reportError(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, @@ -5485,22 +5484,22 @@ namespace ts { return Ternary.False; } - let targetReturnType = getReturnTypeOfSignature(target); + const targetReturnType = getReturnTypeOfSignature(target); if (targetReturnType === voidType) return result; - let sourceReturnType = getReturnTypeOfSignature(source); + const sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source: Type, target: Type, kind: SignatureKind): Ternary { - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); if (sourceSignatures.length !== targetSignatures.length) { return Ternary.False; } let result = Ternary.True; for (let i = 0, len = sourceSignatures.length; i < len; ++i) { - let related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + const related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return Ternary.False; } @@ -5513,21 +5512,21 @@ namespace ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.String, source, target); } - let targetType = getIndexTypeOfType(target, IndexKind.String); + const targetType = getIndexTypeOfType(target, IndexKind.String); if (targetType) { if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: string]: any } = { property: 12 };` return Ternary.True; } - let sourceType = getIndexTypeOfType(source, IndexKind.String); + const sourceType = getIndexTypeOfType(source, IndexKind.String); if (!sourceType) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return Ternary.False; } - let related = isRelatedTo(sourceType, targetType, reportErrors); + const related = isRelatedTo(sourceType, targetType, reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Index_signatures_are_incompatible); @@ -5543,15 +5542,15 @@ namespace ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.Number, source, target); } - let targetType = getIndexTypeOfType(target, IndexKind.Number); + const targetType = getIndexTypeOfType(target, IndexKind.Number); if (targetType) { if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: number]: any } = { property: 12 };` return Ternary.True; } - let sourceStringType = getIndexTypeOfType(source, IndexKind.String); - let sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); + const sourceStringType = getIndexTypeOfType(source, IndexKind.String); + const sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); if (!(sourceStringType || sourceNumberType)) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); @@ -5578,8 +5577,8 @@ namespace ts { } function indexTypesIdenticalTo(indexKind: IndexKind, source: Type, target: Type): Ternary { - let targetType = getIndexTypeOfType(target, indexKind); - let sourceType = getIndexTypeOfType(source, indexKind); + const targetType = getIndexTypeOfType(target, indexKind); + const sourceType = getIndexTypeOfType(source, indexKind); if (!sourceType && !targetType) { return Ternary.True; } @@ -5598,10 +5597,10 @@ namespace ts { function isDeeplyNestedGeneric(type: Type, stack: Type[], depth: number): boolean { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) if (type.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && depth >= 5) { - let symbol = type.symbol; + const symbol = type.symbol; let count = 0; for (let i = 0; i < depth; i++) { - let t = stack[i]; + const t = stack[i]; if (t.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -5622,8 +5621,8 @@ namespace ts { if (sourceProp === targetProp) { return Ternary.True; } - let sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); - let targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); + const sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); + const targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); if (sourcePropAccessibility !== targetPropAccessibility) { return Ternary.False; } @@ -5659,7 +5658,7 @@ namespace ts { return Ternary.False; } for (let i = 0, len = source.typeParameters.length; i < len; ++i) { - let related = compareTypes(source.typeParameters[i], target.typeParameters[i]); + const related = compareTypes(source.typeParameters[i], target.typeParameters[i]); if (!related) { return Ternary.False; } @@ -5673,11 +5672,11 @@ namespace ts { // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); - let targetLen = target.parameters.length; + const targetLen = target.parameters.length; for (let i = 0; i < targetLen; i++) { - let s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); - let t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); - let related = compareTypes(s, t); + const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); + const t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + const related = compareTypes(s, t); if (!related) { return Ternary.False; } @@ -5694,7 +5693,7 @@ namespace ts { } function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { - for (let type of types) { + for (const type of types) { if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } return true; @@ -5786,13 +5785,13 @@ namespace ts { } function getWidenedTypeOfObjectLiteral(type: Type): Type { - let properties = getPropertiesOfObjectType(type); - let members: SymbolTable = {}; + const properties = getPropertiesOfObjectType(type); + const members: SymbolTable = {}; forEach(properties, p => { - let propType = getTypeOfSymbol(p); - let widenedType = getWidenedType(propType); + const propType = getTypeOfSymbol(p); + const widenedType = getWidenedType(propType); if (propType !== widenedType) { - let symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); + const symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); symbol.declarations = p.declarations; symbol.parent = p.parent; symbol.type = widenedType; @@ -5844,7 +5843,7 @@ namespace ts { function reportWideningErrorsInType(type: Type): boolean { let errorReported = false; if (type.flags & TypeFlags.Union) { - for (let t of (type).types) { + for (const t of (type).types) { if (reportWideningErrorsInType(t)) { errorReported = true; } @@ -5854,15 +5853,15 @@ namespace ts { return reportWideningErrorsInType((type).typeArguments[0]); } if (isTupleType(type)) { - for (let t of type.elementTypes) { + for (const t of type.elementTypes) { if (reportWideningErrorsInType(t)) { errorReported = true; } } } if (type.flags & TypeFlags.ObjectLiteral) { - for (let p of getPropertiesOfObjectType(type)) { - let t = getTypeOfSymbol(p); + for (const p of getPropertiesOfObjectType(type)) { + const t = getTypeOfSymbol(p); if (t.flags & TypeFlags.ContainsUndefinedOrNull) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); @@ -5875,7 +5874,7 @@ namespace ts { } function reportImplicitAnyError(declaration: Declaration, type: Type) { - let typeAsString = typeToString(getWidenedType(type)); + const typeAsString = typeToString(getWidenedType(type)); let diagnostic: DiagnosticMessage; switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: @@ -5936,15 +5935,15 @@ namespace ts { count = sourceMax < targetMax ? sourceMax : targetMax; } for (let i = 0; i < count; i++) { - let s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - let t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); callback(s, t); } } function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { - let inferences: TypeInferences[] = []; - for (let unused of typeParameters) { + const inferences: TypeInferences[] = []; + for (const unused of typeParameters) { inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -5985,10 +5984,10 @@ namespace ts { return; } - let typeParameters = context.typeParameters; + const typeParameters = context.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { - let inferences = context.inferences[i]; + const inferences = context.inferences[i]; if (!inferences.isFixed) { // Any inferences that are made to a type parameter in a union type are inferior // to inferences made to a flat (non-union) type. This is because if we infer to @@ -5996,7 +5995,7 @@ namespace ts { // the correct constituent on the target side could be string[]). Therefore, we put // such inferior inferences into a secondary bucket, and only use them if the primary // bucket is empty. - let candidates = inferiority ? + const candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : inferences.primary || (inferences.primary = []); if (!contains(candidates, source)) { @@ -6009,27 +6008,27 @@ namespace ts { } else if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments - let sourceTypes = (source).typeArguments || emptyArray; - let targetTypes = (target).typeArguments || emptyArray; - let count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + const sourceTypes = (source).typeArguments || emptyArray; + const targetTypes = (target).typeArguments || emptyArray; + const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; for (let i = 0; i < count; i++) { inferFromTypes(sourceTypes[i], targetTypes[i]); } } else if (source.flags & TypeFlags.Tuple && target.flags & TypeFlags.Tuple && (source).elementTypes.length === (target).elementTypes.length) { // If source and target are tuples of the same size, infer from element types - let sourceTypes = (source).elementTypes; - let targetTypes = (target).elementTypes; + const sourceTypes = (source).elementTypes; + const targetTypes = (target).elementTypes; for (let i = 0; i < sourceTypes.length; i++) { inferFromTypes(sourceTypes[i], targetTypes[i]); } } else if (target.flags & TypeFlags.UnionOrIntersection) { - let targetTypes = (target).types; + const targetTypes = (target).types; let typeParameterCount = 0; let typeParameter: TypeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (let t of targetTypes) { + for (const t of targetTypes) { if (t.flags & TypeFlags.TypeParameter && contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -6050,8 +6049,8 @@ namespace ts { } else if (source.flags & TypeFlags.UnionOrIntersection) { // Source is a union or intersection type, infer from each consituent type - let sourceTypes = (source).types; - for (let sourceType of sourceTypes) { + const sourceTypes = (source).types; + for (const sourceType of sourceTypes) { inferFromTypes(sourceType, target); } } @@ -6086,9 +6085,9 @@ namespace ts { } function inferFromProperties(source: Type, target: Type) { - let properties = getPropertiesOfObjectType(target); - for (let targetProp of properties) { - let sourceProp = getPropertyOfObjectType(source, targetProp.name); + const properties = getPropertiesOfObjectType(target); + for (const targetProp of properties) { + const sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -6096,11 +6095,11 @@ namespace ts { } function inferFromSignatures(source: Type, target: Type, kind: SignatureKind) { - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); - let sourceLen = sourceSignatures.length; - let targetLen = targetSignatures.length; - let len = sourceLen < targetLen ? sourceLen : targetLen; + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); + const sourceLen = sourceSignatures.length; + const targetLen = targetSignatures.length; + const len = sourceLen < targetLen ? sourceLen : targetLen; for (let i = 0; i < len; i++) { inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } @@ -6122,9 +6121,9 @@ namespace ts { } function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { - let targetIndexType = getIndexTypeOfType(target, targetKind); + const targetIndexType = getIndexTypeOfType(target, targetKind); if (targetIndexType) { - let sourceIndexType = getIndexTypeOfType(source, sourceKind); + const sourceIndexType = getIndexTypeOfType(source, sourceKind); if (sourceIndexType) { inferFromTypes(sourceIndexType, targetIndexType); } @@ -6133,7 +6132,7 @@ namespace ts { } function getInferenceCandidates(context: InferenceContext, index: number): Type[] { - let inferences = context.inferences[index]; + const inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } @@ -6141,10 +6140,10 @@ namespace ts { let inferredType = context.inferredTypes[index]; let inferenceSucceeded: boolean; if (!inferredType) { - let inferences = getInferenceCandidates(context, index); + const inferences = getInferenceCandidates(context, index); if (inferences.length) { // Infer widened union or supertype, or the unknown type for no common supertype - let unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + const unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -6159,7 +6158,7 @@ namespace ts { // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { - let constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + const constraint = getConstraintOfTypeParameter(context.typeParameters[index]); inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { @@ -6188,7 +6187,7 @@ namespace ts { // EXPRESSION TYPE CHECKING function getResolvedSymbol(node: Identifier): Symbol { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = (!nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node)) || unknownSymbol; } @@ -6218,10 +6217,10 @@ namespace ts { // or not of the given type kind (when isOfTypeKind is false) function removeTypesFromUnionType(type: Type, typeKind: TypeFlags, isOfTypeKind: boolean, allowEmptyUnionResult: boolean): Type { if (type.flags & TypeFlags.Union) { - let types = (type).types; + const types = (type).types; if (forEach(types, t => !!(t.flags & typeKind) === isOfTypeKind)) { // Above we checked if we have anything to remove, now use the opposite test to do the removal - let narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); + const narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { return narrowedType; } @@ -6241,9 +6240,9 @@ namespace ts { // Check if a given variable is assigned within a given syntax node function isVariableAssignedWithin(symbol: Symbol, node: Node): boolean { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (links.assignmentChecks) { - let cachedResult = links.assignmentChecks[symbol.id]; + const cachedResult = links.assignmentChecks[symbol.id]; if (cachedResult !== undefined) { return cachedResult; } @@ -6337,7 +6336,7 @@ namespace ts { if (node && symbol.flags & SymbolFlags.Variable) { if (isTypeAny(type) || type.flags & (TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { loop: while (node.parent) { - let child = node; + const child = node; node = node.parent; let narrowedType = type; switch (node.kind) { @@ -6393,12 +6392,12 @@ namespace ts { if (expr.left.kind !== SyntaxKind.TypeOfExpression || expr.right.kind !== SyntaxKind.StringLiteral) { return type; } - let left = expr.left; - let right = expr.right; + const left = expr.left; + const right = expr.right; if (left.expression.kind !== SyntaxKind.Identifier || getResolvedSymbol(left.expression) !== symbol) { return type; } - let typeInfo = primitiveTypeInfo[right.text]; + const typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === SyntaxKind.ExclamationEqualsEqualsToken) { assumeTrue = !assumeTrue; } @@ -6462,16 +6461,16 @@ namespace ts { return type; } // Check that right operand is a function type with a prototype property - let rightType = checkExpression(expr.right); + const rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } let targetType: Type; - let prototypeProperty = getPropertyOfType(rightType, "prototype"); + const prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { // Target type is type of the prototype property - let prototypePropertyType = getTypeOfSymbol(prototypeProperty); + const prototypePropertyType = getTypeOfSymbol(prototypeProperty); if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } @@ -6502,7 +6501,7 @@ namespace ts { // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & TypeFlags.Union) { - let assignableConstituents = filter((originalType).types, t => isTypeAssignableTo(t, narrowedTypeCandidate)); + const assignableConstituents = filter((originalType).types, t => isTypeAssignableTo(t, narrowedTypeCandidate)); if (assignableConstituents.length) { return getUnionType(assignableConstituents); } @@ -6520,7 +6519,7 @@ namespace ts { if (type.flags & TypeFlags.Any) { return type; } - let signature = getResolvedSignature(expr); + const signature = getResolvedSignature(expr); if (signature.typePredicate && expr.arguments[signature.typePredicate.parameterIndex] && @@ -6546,7 +6545,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return narrowType(type, (expr).expression, assumeTrue); case SyntaxKind.BinaryExpression: - let operator = (expr).operatorToken.kind; + const operator = (expr).operatorToken.kind; if (operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { return narrowTypeByEquality(type, expr, assumeTrue); } @@ -6571,7 +6570,7 @@ namespace ts { } function checkIdentifier(node: Identifier): Type { - let symbol = getResolvedSymbol(node); + const symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -6580,7 +6579,7 @@ namespace ts { // To avoid that we will give an error to users if they use arguments objects in arrow function so that they // can explicitly bound arguments objects if (symbol === argumentsSymbol) { - let container = getContainingFunction(node); + const container = getContainingFunction(node); if (container.kind === SyntaxKind.ArrowFunction) { if (languageVersion < ScriptTarget.ES6) { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); @@ -6648,7 +6647,7 @@ namespace ts { } } - let inFunction = isInsideFunction(node.parent, container); + const inFunction = isInsideFunction(node.parent, container); let current = container; while (current && !nodeStartsNewLexicalEnvironment(current)) { @@ -6667,7 +6666,7 @@ namespace ts { function captureLexicalThis(node: Node, container: Node): void { getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis; if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) { - let classNode = container.parent; + const classNode = container.parent; getNodeLinks(classNode).flags |= NodeCheckFlags.CaptureThis; } else { @@ -6721,7 +6720,7 @@ namespace ts { } if (isClassLike(container.parent)) { - let symbol = getSymbolOfNode(container.parent); + const symbol = getSymbolOfNode(container.parent); return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; } return anyType; @@ -6737,10 +6736,10 @@ namespace ts { } function checkSuperExpression(node: Node): Type { - let isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - let classDeclaration = getContainingClass(node); - let classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - let baseClassType = classType && getBaseTypes(classType)[0]; + const isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; + const classDeclaration = getContainingClass(node); + const classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + const baseClassType = classType && getBaseTypes(classType)[0]; let container = getSuperContainer(node, /*includeFunctions*/ true); let needToCaptureLexicalThis = false; @@ -6753,7 +6752,7 @@ namespace ts { } } - let canUseSuperExpression = isLegalUsageOfSuperExpression(container); + const canUseSuperExpression = isLegalUsageOfSuperExpression(container); let nodeCheckFlag: NodeCheckFlags = 0; // always set NodeCheckFlags for 'super' expression node @@ -6848,15 +6847,15 @@ namespace ts { // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type { - let func = parameter.parent; + const func = parameter.parent; if (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) { if (isContextSensitive(func)) { - let contextualSignature = getContextualSignature(func); + const contextualSignature = getContextualSignature(func); if (contextualSignature) { - let funcHasRestParameters = hasRestParameter(func); - let len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - let indexOfParameter = indexOf(func.parameters, parameter); + const funcHasRestParameters = hasRestParameter(func); + const len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + const indexOfParameter = indexOf(func.parameters, parameter); if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -6879,13 +6878,13 @@ namespace ts { // of the parameter. Otherwise, in a variable or parameter declaration with a binding pattern name, the contextual // type of an initializer expression is the type implied by the binding pattern. function getContextualTypeForInitializerExpression(node: Expression): Type { - let declaration = node.parent; + const declaration = node.parent; if (node === declaration.initializer) { if (declaration.type) { return getTypeFromTypeNode(declaration.type); } if (declaration.kind === SyntaxKind.Parameter) { - let type = getContextuallyTypedParameterType(declaration); + const type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -6898,7 +6897,7 @@ namespace ts { } function getContextualTypeForReturnExpression(node: Expression): Type { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func && !func.asteriskToken) { return getContextualReturnType(func); } @@ -6907,9 +6906,9 @@ namespace ts { } function getContextualTypeForYieldOperand(node: YieldExpression): Type { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func) { - let contextualReturnType = getContextualReturnType(func); + const contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { return node.asteriskToken ? contextualReturnType @@ -6943,7 +6942,7 @@ namespace ts { // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - let signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); if (signature) { return getReturnTypeOfSignature(signature); } @@ -6953,10 +6952,10 @@ namespace ts { // 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 { - let args = getEffectiveCallArguments(callTarget); - let argIndex = indexOf(args, arg); + const args = getEffectiveCallArguments(callTarget); + const argIndex = indexOf(args, arg); if (argIndex >= 0) { - let signature = getResolvedSignature(callTarget); + const signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; @@ -6971,8 +6970,8 @@ namespace ts { } function getContextualTypeForBinaryOperand(node: Expression): Type { - let binaryExpression = node.parent; - let operator = binaryExpression.operatorToken.kind; + const binaryExpression = node.parent; + const operator = binaryExpression.operatorToken.kind; if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { @@ -6998,11 +6997,11 @@ namespace ts { if (!(type.flags & TypeFlags.Union)) { return mapper(type); } - let types = (type).types; + const types = (type).types; let mappedType: Type; let mappedTypes: Type[]; - for (let current of types) { - let t = mapper(current); + for (const current of types) { + const t = mapper(current); if (t) { if (!mappedType) { mappedType = t; @@ -7020,7 +7019,7 @@ namespace ts { function getTypeOfPropertyOfContextualType(type: Type, name: string) { return applyToContextualType(type, t => { - let prop = t.flags & TypeFlags.StructuredType ? getPropertyOfType(t, name) : undefined; + const prop = t.flags & TypeFlags.StructuredType ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -7053,15 +7052,15 @@ namespace ts { } function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElement) { - let objectLiteral = element.parent; - let type = getContextualType(objectLiteral); + const objectLiteral = element.parent; + const type = getContextualType(objectLiteral); if (type) { if (!hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - let symbolName = getSymbolOfNode(element).name; - let propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + const symbolName = getSymbolOfNode(element).name; + const propertyType = getTypeOfPropertyOfContextualType(type, symbolName); if (propertyType) { return propertyType; } @@ -7079,10 +7078,10 @@ namespace ts { // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated // type of T. function getContextualTypeForElementExpression(node: Expression): Type { - let arrayLiteral = node.parent; - let type = getContextualType(arrayLiteral); + const arrayLiteral = node.parent; + const type = getContextualType(arrayLiteral); if (type) { - let index = indexOf(arrayLiteral.elements, node); + const index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); @@ -7092,15 +7091,15 @@ namespace ts { // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node: Expression): Type { - let conditional = node.parent; + const conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } function getContextualTypeForJsxExpression(expr: JsxExpression | JsxSpreadAttribute): Type { // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) if (expr.parent.kind === SyntaxKind.JsxAttribute) { - let attrib = expr.parent; - let attrsType = getJsxElementAttributesType(attrib.parent); + const attrib = expr.parent; + const attrsType = getJsxElementAttributesType(attrib.parent); if (!attrsType || isTypeAny(attrsType)) { return undefined; } @@ -7119,7 +7118,7 @@ namespace ts { // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getContextualType(node: Expression): Type { - let type = getContextualTypeWorker(node); + const type = getContextualTypeWorker(node); return type && getApparentType(type); } @@ -7131,7 +7130,7 @@ namespace ts { if (node.contextualType) { return node.contextualType; } - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: @@ -7173,9 +7172,9 @@ namespace ts { // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type: Type): Signature { - let signatures = getSignaturesOfStructuredType(type, SignatureKind.Call); + const signatures = getSignaturesOfStructuredType(type, SignatureKind.Call); if (signatures.length === 1) { - let signature = signatures[0]; + const signature = signatures[0]; if (!signature.typeParameters) { return signature; } @@ -7200,7 +7199,7 @@ namespace ts { // union type of return types from these signatures function getContextualSignature(node: FunctionExpression | MethodDeclaration): Signature { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - let type = isObjectLiteralMethod(node) + const type = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); if (!type) { @@ -7210,9 +7209,9 @@ namespace ts { return getNonGenericSignature(type); } let signatureList: Signature[]; - let types = (type).types; - for (let current of types) { - let signature = getNonGenericSignature(current); + const types = (type).types; + for (const current of types) { + const signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -7263,7 +7262,7 @@ namespace ts { // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node: Node): boolean { - let parent = node.parent; + const parent = node.parent; if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node) { return true; } @@ -7283,7 +7282,7 @@ namespace ts { // with this type. It is neither affected by it, nor does it propagate it to its operand. // So the fact that contextualMapper is passed is not important, because the operand of a spread // element is not contextually typed. - let arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + const arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } @@ -7293,11 +7292,11 @@ namespace ts { } function checkArrayLiteral(node: ArrayLiteralExpression, contextualMapper?: TypeMapper): Type { - let elements = node.elements; + const elements = node.elements; let hasSpreadElement = false; - let elementTypes: Type[] = []; - let inDestructuringPattern = isAssignmentTarget(node); - for (let e of elements) { + const elementTypes: Type[] = []; + const inDestructuringPattern = isAssignmentTarget(node); + for (const e of elements) { if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElementExpression) { // Given the following situation: // var c: {}; @@ -7311,15 +7310,15 @@ namespace ts { // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - let restArrayType = checkExpression((e).expression, contextualMapper); - let restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || + const restArrayType = checkExpression((e).expression, contextualMapper); + const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } } else { - let type = checkExpression(e, contextualMapper); + const type = checkExpression(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression; @@ -7328,19 +7327,19 @@ namespace ts { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - let type = createNewTupleType(elementTypes); + const type = createNewTupleType(elementTypes); type.pattern = node; return type; } - let contextualType = getContextualType(node); + const contextualType = getContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - let pattern = contextualType.pattern; + const pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. if (pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { - let patternElements = (pattern).elements; + const patternElements = (pattern).elements; for (let i = elementTypes.length; i < patternElements.length; i++) { - let patternElement = patternElements[i]; + const patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { elementTypes.push((contextualType).elementTypes[i]); } @@ -7400,7 +7399,7 @@ namespace ts { } function checkComputedPropertyName(node: ComputedPropertyName): Type { - let links = getNodeLinks(node.expression); + const links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); @@ -7418,18 +7417,18 @@ namespace ts { } function checkObjectLiteral(node: ObjectLiteralExpression, contextualMapper?: TypeMapper): Type { - let inDestructuringPattern = isAssignmentTarget(node); + const inDestructuringPattern = isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - let propertiesTable: SymbolTable = {}; - let propertiesArray: Symbol[] = []; - let contextualType = getContextualType(node); - let contextualTypeHasPattern = contextualType && contextualType.pattern && + const propertiesTable: SymbolTable = {}; + const propertiesArray: Symbol[] = []; + const contextualType = getContextualType(node); + const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); let typeFlags: TypeFlags = 0; - for (let memberDecl of node.properties) { + for (const memberDecl of node.properties) { let member = memberDecl.symbol; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || @@ -7446,7 +7445,7 @@ namespace ts { type = checkExpression((memberDecl).name, contextualMapper); } typeFlags |= type.flags; - let prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); + const prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. @@ -7460,7 +7459,7 @@ namespace ts { else if (contextualTypeHasPattern) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. - let impliedProp = getPropertyOfType(contextualType, member.name); + const impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & SymbolFlags.Optional; } @@ -7498,7 +7497,7 @@ namespace ts { // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { - for (let prop of getPropertiesOfType(contextualType)) { + for (const prop of getPropertiesOfType(contextualType)) { if (!hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & SymbolFlags.Optional)) { error(prop.valueDeclaration || (prop).bindingElement, @@ -7510,10 +7509,10 @@ namespace ts { } } - let stringIndexType = getIndexType(IndexKind.String); - let numberIndexType = getIndexType(IndexKind.Number); - let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - let freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral; + const stringIndexType = getIndexType(IndexKind.String); + const numberIndexType = getIndexType(IndexKind.Number); + const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral; result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); if (inDestructuringPattern) { result.pattern = node; @@ -7522,21 +7521,21 @@ namespace ts { function getIndexType(kind: IndexKind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - let propTypes: Type[] = []; + const propTypes: Type[] = []; for (let i = 0; i < propertiesArray.length; i++) { - let propertyDecl = node.properties[i]; + const propertyDecl = node.properties[i]; if (kind === IndexKind.String || isNumericName(propertyDecl.name)) { // Do not call getSymbolOfNode(propertyDecl), as that will get the // original symbol for the node. We actually want to get the symbol // created by checkObjectLiteral, since that will be appropriately // contextually typed and resolved. - let type = getTypeOfSymbol(propertiesArray[i]); + const type = getTypeOfSymbol(propertiesArray[i]); if (!contains(propTypes, type)) { propTypes.push(type); } } } - let result = propTypes.length ? getUnionType(propTypes) : undefinedType; + const result = propTypes.length ? getUnionType(propTypes) : undefinedType; typeFlags |= result.flags; return result; } @@ -7576,7 +7575,7 @@ namespace ts { } // Check children - for (let child of node.children) { + for (const child of node.children) { switch (child.kind) { case SyntaxKind.JsxExpression: checkJsxExpression(child); @@ -7622,11 +7621,11 @@ namespace ts { error(node.parent, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else if (elementAttributesType && !isTypeAny(elementAttributesType)) { - let correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); + const correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { // Maybe there's a string indexer? - let indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String); + const indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String); if (indexerType) { correspondingPropType = indexerType; } @@ -7658,15 +7657,15 @@ namespace ts { } function checkJsxSpreadAttribute(node: JsxSpreadAttribute, elementAttributesType: Type, nameTable: Map) { - let type = checkExpression(node.expression); - let props = getPropertiesOfType(type); - for (let prop of props) { + const type = checkExpression(node.expression); + const props = getPropertiesOfType(type); + for (const prop of props) { // Is there a corresponding property in the element attributes type? Skip checking of properties // that have already been assigned to, as these are not actually pushed into the resulting type if (!nameTable[prop.name]) { - let targetPropSym = getPropertyOfType(elementAttributesType, prop.name); + const targetPropSym = getPropertyOfType(elementAttributesType, prop.name); if (targetPropSym) { - let msg = chainDiagnosticMessages(undefined, Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name); + const msg = chainDiagnosticMessages(undefined, Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name); checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(targetPropSym), node, undefined, msg); } @@ -7691,8 +7690,8 @@ namespace ts { /// type or factory function. /// Otherwise, returns unknownSymbol. function getJsxElementTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let flags: JsxFlags = JsxFlags.UnknownElement; - let links = getNodeLinks(node); + const flags: JsxFlags = JsxFlags.UnknownElement; + const links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { links.resolvedSymbol = lookupIntrinsicTag(node); @@ -7704,17 +7703,17 @@ namespace ts { return links.resolvedSymbol; function lookupIntrinsicTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let intrinsicElementsType = getJsxIntrinsicElementsType(); + const intrinsicElementsType = getJsxIntrinsicElementsType(); if (intrinsicElementsType !== unknownType) { // Property case - let intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); + const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); if (intrinsicProp) { links.jsxFlags |= JsxFlags.IntrinsicNamedElement; return intrinsicProp; } // Intrinsic string indexer case - let indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); + const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); if (indexSignatureType) { links.jsxFlags |= JsxFlags.IntrinsicIndexedElement; return intrinsicElementsType.symbol; @@ -7732,7 +7731,7 @@ namespace ts { } function lookupClassTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let valueSymbol: Symbol = resolveJsxTagName(node); + const valueSymbol: Symbol = resolveJsxTagName(node); // Look up the value in the current scope if (valueSymbol && valueSymbol !== unknownSymbol) { @@ -7747,8 +7746,8 @@ namespace ts { function resolveJsxTagName(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { if (node.tagName.kind === SyntaxKind.Identifier) { - let tag = node.tagName; - let sym = getResolvedSymbol(tag); + const tag = node.tagName; + const sym = getResolvedSymbol(tag); return sym.exportSymbol || sym; } else { @@ -7767,13 +7766,13 @@ namespace ts { // line shouldn't be hit. Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), "Should not call getJsxElementInstanceType on non-class Element"); - let classSymbol = getJsxElementTagSymbol(node); + const classSymbol = getJsxElementTagSymbol(node); if (classSymbol === unknownSymbol) { // Couldn't find the class instance type. Error has already been issued return anyType; } - let valueType = getTypeOfSymbol(classSymbol); + const valueType = getTypeOfSymbol(classSymbol); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -7792,10 +7791,10 @@ namespace ts { } } - let returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); + const returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); // Issue an error if this return type isn't assignable to JSX.ElementClass - let elemClassType = getJsxGlobalElementClassType(); + const elemClassType = getJsxGlobalElementClassType(); if (elemClassType) { checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } @@ -7810,13 +7809,13 @@ namespace ts { /// non-instrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - let jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); + const jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); // JSX.ElementAttributesProperty [symbol] - let attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); + const attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); // JSX.ElementAttributesProperty [type] - let attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); + const attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properites of JSX.ElementAttributesProperty - let attribProperties = attribPropType && getPropertiesOfType(attribPropType); + const attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { // Element Attributes has zero properties, so the element attributes type will be the class instance type @@ -7845,18 +7844,18 @@ namespace ts { * us which attributes are valid on a given element. */ function getJsxElementAttributesType(node: JsxOpeningLikeElement): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedJsxType) { - let sym = getJsxElementTagSymbol(node); + const sym = getJsxElementTagSymbol(node); if (links.jsxFlags & JsxFlags.ClassElement) { - let elemInstanceType = getJsxElementInstanceType(node); + const elemInstanceType = getJsxElementInstanceType(node); if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } - let propsName = getJsxElementPropertiesName(); + const propsName = getJsxElementPropertiesName(); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return links.resolvedJsxType = anyType; @@ -7866,7 +7865,7 @@ namespace ts { return links.resolvedJsxType = elemInstanceType; } else { - let attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + const attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); if (!attributesType) { // There is no property named 'props' on this instance type @@ -7905,8 +7904,8 @@ namespace ts { * that have no matching element attributes type property. */ function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { - let attributesType = getJsxElementAttributesType(attrib.parent); - let prop = getPropertyOfType(attributesType, attrib.name.text); + const attributesType = getJsxElementAttributesType(attrib.parent); + const prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } @@ -7919,7 +7918,7 @@ namespace ts { /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames(): Symbol[] { - let intrinsics = getJsxIntrinsicElementsType(); + const intrinsics = getJsxIntrinsicElementsType(); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } @@ -7944,15 +7943,15 @@ namespace ts { // be marked as 'used' so we don't incorrectly elide its import. And if there // is no 'React' symbol in scope, we should issue an error. if (compilerOptions.jsx === JsxEmit.React) { - let reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React"); + const reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React"); if (reactSym) { getSymbolLinks(reactSym).referenced = true; } } - let targetAttributesType = getJsxElementAttributesType(node); + const targetAttributesType = getJsxElementAttributesType(node); - let nameTable: Map = {}; + const nameTable: Map = {}; // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -7963,7 +7962,7 @@ namespace ts { } else { Debug.assert(node.attributes[i].kind === SyntaxKind.JsxSpreadAttribute); - let spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); + const spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; } @@ -7973,7 +7972,7 @@ namespace ts { // Check that all required properties have been provided. If an 'any' // was spreaded in, though, assume that it provided all required properties if (targetAttributesType && !sawSpreadedAny) { - let targetProperties = getPropertiesOfType(targetAttributesType); + const targetProperties = getPropertiesOfType(targetAttributesType); for (let i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & SymbolFlags.Optional) && nameTable[targetProperties[i].name] === undefined) { @@ -8012,11 +8011,11 @@ namespace ts { * @param prop The symbol for the right hand side of the property access. */ function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { - let flags = getDeclarationFlagsFromSymbol(prop); - let declaringClass = getDeclaredTypeOfSymbol(prop.parent); + const flags = getDeclarationFlagsFromSymbol(prop); + const declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === SyntaxKind.SuperKeyword) { - let errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? + const errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? (node).name : (node).right; @@ -8053,9 +8052,9 @@ namespace ts { // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - let enclosingClassDeclaration = getContainingClass(node); + const enclosingClassDeclaration = getContainingClass(node); - let enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; + const enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same if (flags & NodeFlags.Private) { @@ -8104,17 +8103,17 @@ namespace ts { } function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - let type = checkExpression(left); + const type = checkExpression(left); if (isTypeAny(type)) { return type; } - let apparentType = getApparentType(getWidenedType(type)); + const apparentType = getApparentType(getWidenedType(type)); if (apparentType === unknownType) { // handle cases when type is Type parameter with invalid constraint return unknownType; } - let prop = getPropertyOfType(apparentType, right.text); + const prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text) { error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type.flags & TypeFlags.ThisType ? apparentType : type)); @@ -8131,13 +8130,13 @@ namespace ts { } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { - let left = node.kind === SyntaxKind.PropertyAccessExpression + const left = node.kind === SyntaxKind.PropertyAccessExpression ? (node).expression : (node).left; - let type = checkExpression(left); + const type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { - let prop = getPropertyOfType(getWidenedType(type), propertyName); + const prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) { return checkClassPropertyAccess(node, left, type, prop); } @@ -8148,28 +8147,28 @@ namespace ts { function checkIndexedAccess(node: ElementAccessExpression): Type { // Grammar checking if (!node.argumentExpression) { - let sourceFile = getSourceFile(node); + const sourceFile = getSourceFile(node); if (node.parent.kind === SyntaxKind.NewExpression && (node.parent).expression === node) { - let start = skipTrivia(sourceFile.text, node.expression.end); - let end = node.end; + const start = skipTrivia(sourceFile.text, node.expression.end); + const end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); } else { - let start = node.end - "]".length; - let end = node.end; + const start = node.end - "]".length; + const end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Expression_expected); } } // Obtain base constraint such that we can bail out if the constraint is an unknown type - let objectType = getApparentType(checkExpression(node.expression)); - let indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + const objectType = getApparentType(checkExpression(node.expression)); + const indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; if (objectType === unknownType) { return unknownType; } - let isConstEnum = isConstEnumObjectType(objectType); + const isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && (!node.argumentExpression || node.argumentExpression.kind !== SyntaxKind.StringLiteral)) { error(node.argumentExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); @@ -8187,9 +8186,9 @@ namespace ts { // See if we can index as a property. if (node.argumentExpression) { - let name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + const name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); if (name !== undefined) { - let prop = getPropertyOfType(objectType, name); + const prop = getPropertyOfType(objectType, name); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); @@ -8206,14 +8205,14 @@ namespace ts { // Try to use a number indexer. if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike)) { - let numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); + const numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); if (numberIndexType) { return numberIndexType; } } // Try to use string indexing. - let stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); + const stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); if (stringIndexType) { return stringIndexType; } @@ -8244,13 +8243,13 @@ namespace ts { return (indexArgumentExpression).text; } if (indexArgumentExpression.kind === SyntaxKind.ElementAccessExpression || indexArgumentExpression.kind === SyntaxKind.PropertyAccessExpression) { - let value = getConstantValue(indexArgumentExpression); + const value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); } } if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - let rightHandSideName = ((indexArgumentExpression).name).text; + const rightHandSideName = ((indexArgumentExpression).name).text; return getPropertyNameForKnownSymbolName(rightHandSideName); } @@ -8284,13 +8283,13 @@ namespace ts { // The name is Symbol., so make sure Symbol actually resolves to the // global Symbol object - let leftHandSide = (expression).expression; - let leftHandSideSymbol = getResolvedSymbol(leftHandSide); + const leftHandSide = (expression).expression; + const leftHandSideSymbol = getResolvedSymbol(leftHandSide); if (!leftHandSideSymbol) { return false; } - let globalESSymbol = getGlobalESSymbolConstructorSymbol(); + const globalESSymbol = getGlobalESSymbolConstructorSymbol(); if (!globalESSymbol) { // Already errored when we tried to look up the symbol return false; @@ -8329,7 +8328,7 @@ namespace ts { // so order how inherited signatures are processed is still preserved. // interface A { (x: string): void } // interface B extends A { (x: 'foo'): string } - // let b: B; + // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures: Signature[], result: Signature[]): void { let lastParent: Node; @@ -8339,9 +8338,9 @@ namespace ts { let specializedIndex = -1; let spliceIndex: number; Debug.assert(!result.length); - for (let signature of signatures) { - let symbol = signature.declaration && getSymbolOfNode(signature.declaration); - let parent = signature.declaration && signature.declaration.parent; + for (const signature of signatures) { + const symbol = signature.declaration && getSymbolOfNode(signature.declaration); + const parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { index++; @@ -8379,7 +8378,7 @@ namespace ts { function getSpreadArgumentIndex(args: Expression[]): number { for (let i = 0; i < args.length; i++) { - let arg = args[i]; + const arg = args[i]; if (arg && arg.kind === SyntaxKind.SpreadElementExpression) { return i; } @@ -8395,7 +8394,7 @@ namespace ts { let spreadArgIndex = -1; if (node.kind === SyntaxKind.TaggedTemplateExpression) { - let tagExpression = node; + const tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length @@ -8405,8 +8404,8 @@ namespace ts { if (tagExpression.template.kind === SyntaxKind.TemplateExpression) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - let templateExpression = tagExpression.template; - let lastSpan = lastOrUndefined(templateExpression.templateSpans); + const templateExpression = tagExpression.template; + const lastSpan = lastOrUndefined(templateExpression.templateSpans); Debug.assert(lastSpan !== undefined); // we should always have at least one span. callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } @@ -8414,7 +8413,7 @@ namespace ts { // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. - let templateLiteral = tagExpression.template; + const templateLiteral = tagExpression.template; Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral); callIsIncomplete = !!templateLiteral.isUnterminated; } @@ -8425,7 +8424,7 @@ namespace ts { adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { - let callExpression = node; + const callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' Debug.assert(callExpression.kind === SyntaxKind.NewExpression); @@ -8445,7 +8444,7 @@ namespace ts { // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. - let hasRightNumberOfTypeArgs = !typeArguments || + const hasRightNumberOfTypeArgs = !typeArguments || (signature.typeParameters && typeArguments.length === signature.typeParameters.length); if (!hasRightNumberOfTypeArgs) { return false; @@ -8463,14 +8462,14 @@ namespace ts { } // If the call is incomplete, we should skip the lower bound check. - let hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; + const hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type: Type): Signature { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { return resolved.callSignatures[0]; @@ -8481,7 +8480,7 @@ namespace ts { // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature: Signature, contextualSignature: Signature, contextualMapper: TypeMapper): Signature { - let context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + const context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, (source, target) => { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context, instantiateType(source, contextualMapper), target); @@ -8490,8 +8489,8 @@ namespace ts { } function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void { - let typeParameters = signature.typeParameters; - let inferenceMapper = createInferenceMapper(context); + const typeParameters = signature.typeParameters; + const inferenceMapper = createInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (let i = 0; i < typeParameters.length; i++) { @@ -8517,12 +8516,12 @@ namespace ts { // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - let argCount = getEffectiveArgumentCount(node, args, signature); + const argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { - let arg = getEffectiveArgument(node, args, i); + const arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { - let paramType = getTypeAtPosition(signature, i); + const paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -8530,7 +8529,7 @@ namespace ts { if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards - let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + const mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } @@ -8547,8 +8546,8 @@ namespace ts { for (let i = 0; i < argCount; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { - let arg = args[i]; - let paramType = getTypeAtPosition(signature, i); + const arg = args[i]; + const paramType = getTypeAtPosition(signature, i); inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } @@ -8558,15 +8557,15 @@ namespace ts { } function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean { - let typeParameters = signature.typeParameters; + const typeParameters = signature.typeParameters; let typeArgumentsAreAssignable = true; for (let i = 0; i < typeParameters.length; i++) { - let typeArgNode = typeArguments[i]; - let typeArgument = getTypeFromTypeNode(typeArgNode); + const typeArgNode = typeArguments[i]; + const typeArgument = getTypeFromTypeNode(typeArgNode); // Do not push on this array! It has a preallocated length typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { - let constraint = getConstraintOfTypeParameter(typeParameters[i]); + const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { let errorInfo: DiagnosticMessageChain; let typeArgumentHeadMessage = Diagnostics.Type_0_does_not_satisfy_the_constraint_1; @@ -8589,13 +8588,13 @@ namespace ts { } function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { - let argCount = getEffectiveArgumentCount(node, args, signature); + const argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { - let arg = getEffectiveArgument(node, args, i); + const arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - let paramType = getTypeAtPosition(signature, i); + const paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -8607,8 +8606,8 @@ namespace ts { } // Use argument expression as error location when reporting errors - let errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - let headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + const errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } @@ -8630,7 +8629,7 @@ namespace ts { function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { let args: Expression[]; if (node.kind === SyntaxKind.TaggedTemplateExpression) { - let template = (node).template; + const template = (node).template; args = [undefined]; if (template.kind === SyntaxKind.TemplateExpression) { forEach((template).templateSpans, span => { @@ -8722,7 +8721,7 @@ namespace ts { if (node.kind === SyntaxKind.ClassDeclaration) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) - let classSymbol = getSymbolOfNode(node); + const classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } @@ -8731,7 +8730,7 @@ namespace ts { // parameter's containing method. node = node.parent; if (node.kind === SyntaxKind.Constructor) { - let classSymbol = getSymbolOfNode(node); + const classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } @@ -8792,7 +8791,7 @@ namespace ts { // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. - let element = node; + const element = node; switch (element.name.kind) { case SyntaxKind.Identifier: case SyntaxKind.NumericLiteral: @@ -8800,7 +8799,7 @@ namespace ts { return getStringLiteralType(element.name); case SyntaxKind.ComputedPropertyName: - let nameType = checkComputedPropertyName(element.name); + const nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { return nameType; } @@ -8848,7 +8847,7 @@ namespace ts { node.kind === SyntaxKind.SetAccessor) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - let propertyType = getTypeOfNode(node); + const propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -8924,8 +8923,8 @@ namespace ts { } function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], headMessage?: DiagnosticMessage): Signature { - let isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; - let isDecorator = node.kind === SyntaxKind.Decorator; + const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; + const isDecorator = node.kind === SyntaxKind.Decorator; let typeArguments: TypeNode[]; @@ -8938,7 +8937,7 @@ namespace ts { } } - let candidates = candidatesOutArray || []; + const candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { @@ -8946,7 +8945,7 @@ namespace ts { return resolveErrorCall(node); } - let args = getEffectiveCallArguments(node); + const args = getEffectiveCallArguments(node); // The following applies to any value of 'excludeArgument[i]': // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. @@ -9044,8 +9043,8 @@ namespace ts { } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - let failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - let inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); + const failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + const inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, @@ -9091,14 +9090,14 @@ namespace ts { } function chooseOverload(candidates: Signature[], relation: Map) { - for (let originalCandidate of candidates) { + for (const originalCandidate of candidates) { if (!hasCorrectArity(node, args, originalCandidate)) { continue; } let candidate: Signature; let typeArgumentsAreValid: boolean; - let inferenceContext = originalCandidate.typeParameters + const inferenceContext = originalCandidate.typeParameters ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) : undefined; @@ -9123,7 +9122,7 @@ namespace ts { if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { break; } - let index = excludeArgument ? indexOf(excludeArgument, true) : -1; + const index = excludeArgument ? indexOf(excludeArgument, true) : -1; if (index < 0) { return candidate; } @@ -9136,7 +9135,7 @@ namespace ts { // report an error based on the arguments. If there was an issue with type // arguments, then we can only report an error based on the type arguments. if (originalCandidate.typeParameters) { - let instantiatedCandidate = candidate; + const instantiatedCandidate = candidate; if (typeArgumentsAreValid) { candidateForArgumentError = instantiatedCandidate; } @@ -9160,19 +9159,19 @@ namespace ts { function resolveCallExpression(node: CallExpression, candidatesOutArray: Signature[]): Signature { if (node.expression.kind === SyntaxKind.SuperKeyword) { - let superType = checkSuperExpression(node.expression); + const superType = checkSuperExpression(node.expression); if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - let baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); - let baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + const baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); + const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } - let funcType = checkExpression(node.expression); - let apparentType = getApparentType(funcType); + const funcType = checkExpression(node.expression); + const apparentType = getApparentType(funcType); if (apparentType === unknownType) { // Another error has already been reported @@ -9183,9 +9182,9 @@ namespace ts { // but we are not including call signatures that may have been added to the Object or // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - let constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); // TS 1.0 spec: 4.12 // If FuncExpr is of type Any, or of an object type that has no call or construct signatures // but is a subtype of the Function interface, the call is an untyped function call. In an @@ -9218,7 +9217,7 @@ namespace ts { function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[]): Signature { if (node.arguments && languageVersion < ScriptTarget.ES5) { - let spreadIndex = getSpreadArgumentIndex(node.arguments); + const spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { error(node.arguments[spreadIndex], Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } @@ -9241,7 +9240,7 @@ namespace ts { // Note, only class declarations can be declared abstract. // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. - let valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && valueDecl.flags & NodeFlags.Abstract) { error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); return resolveErrorCall(node); @@ -9261,7 +9260,7 @@ namespace ts { // but we are not including construct signatures that may have been added to the Object or // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. - let constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); + const constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); if (constructSignatures.length) { return resolveCall(node, constructSignatures, candidatesOutArray); } @@ -9270,9 +9269,9 @@ namespace ts { // one or more call signatures, the expression is processed as a function call. A compile-time // error occurs if the result of the function call is not Void. The type of the result of the // operation is Any. - let callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); if (callSignatures.length) { - let signature = resolveCall(node, callSignatures, candidatesOutArray); + const signature = resolveCall(node, callSignatures, candidatesOutArray); if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } @@ -9284,15 +9283,15 @@ namespace ts { } function resolveTaggedTemplateExpression(node: TaggedTemplateExpression, candidatesOutArray: Signature[]): Signature { - let tagType = checkExpression(node.tag); - let apparentType = getApparentType(tagType); + const tagType = checkExpression(node.tag); + const apparentType = getApparentType(tagType); if (apparentType === unknownType) { // Another error has already been reported return resolveErrorCall(node); } - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & TypeFlags.Union) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); @@ -9332,18 +9331,18 @@ namespace ts { * Resolves a decorator as if it were a call expression. */ function resolveDecorator(node: Decorator, candidatesOutArray: Signature[]): Signature { - let funcType = checkExpression(node.expression); - let apparentType = getApparentType(funcType); + const funcType = checkExpression(node.expression); + const apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); if (funcType === anyType || (!callSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } - let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { let errorInfo: DiagnosticMessageChain; errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); @@ -9358,7 +9357,7 @@ namespace ts { // candidatesOutArray is passed by signature help in the language service, and collectCandidates // must fill it up with the appropriate candidate signatures function getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature { - let links = getNodeLinks(node); + const links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work @@ -9394,12 +9393,12 @@ namespace ts { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - let signature = getResolvedSignature(node); + const signature = getResolvedSignature(node); if (node.expression.kind === SyntaxKind.SuperKeyword) { return voidType; } if (node.kind === SyntaxKind.NewExpression) { - let declaration = signature.declaration; + const declaration = signature.declaration; if (declaration && declaration.kind !== SyntaxKind.Constructor && @@ -9421,10 +9420,10 @@ namespace ts { } function checkAssertion(node: AssertionExpression) { - let exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); - let targetType = getTypeFromTypeNode(node.type); + const exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + const targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { - let widenedType = getWidenedType(exprType); + const widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } @@ -9439,15 +9438,15 @@ namespace ts { } function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { - let len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (let i = 0; i < len; i++) { - let parameter = signature.parameters[i]; - let contextualParameterType = getTypeAtPosition(context, i); + const parameter = signature.parameters[i]; + const contextualParameterType = getTypeAtPosition(context, i); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - let parameter = lastOrUndefined(signature.parameters); - let contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); + const parameter = lastOrUndefined(signature.parameters); + const contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); } } @@ -9456,7 +9455,7 @@ namespace ts { // the destructured type into the contained binding elements. function assignBindingElementTypes(node: VariableLikeDeclaration) { if (isBindingPattern(node.name)) { - for (let element of (node.name).elements) { + for (const element of (node.name).elements) { if (element.kind !== SyntaxKind.OmittedExpression) { if (element.name.kind === SyntaxKind.Identifier) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); @@ -9468,7 +9467,7 @@ namespace ts { } function assignTypeToParameterAndFixTypeParameters(parameter: Symbol, contextualType: Type, mapper: TypeMapper) { - let links = getSymbolLinks(parameter); + const links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); assignBindingElementTypes(parameter.valueDeclaration); @@ -9509,7 +9508,7 @@ namespace ts { function createPromiseType(promisedType: Type): Type { // creates a `Promise` type where `T` is the promisedType argument - let globalPromiseType = getGlobalPromiseType(); + const globalPromiseType = getGlobalPromiseType(); if (globalPromiseType !== emptyGenericType) { // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type promisedType = getAwaitedType(promisedType); @@ -9520,12 +9519,12 @@ namespace ts { } function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type { - let contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } - let isAsync = isAsyncFunctionLike(func); + const isAsync = isAsyncFunctionLike(func); let type: Type; if (func.body.kind !== SyntaxKind.Block) { type = checkExpressionCached(func.body, contextualMapper); @@ -9539,11 +9538,11 @@ namespace ts { } else { let types: Type[]; - let funcIsGenerator = !!func.asteriskToken; + const funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); if (types.length === 0) { - let iterableIteratorAny = createIterableIteratorType(anyType); + const iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { error(func.asteriskToken, Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); @@ -9556,7 +9555,7 @@ namespace ts { if (types.length === 0) { if (isAsync) { // For an async function, the return type will not be void, but rather a Promise for void. - let promiseType = createPromiseType(voidType); + const promiseType = createPromiseType(voidType); if (promiseType === emptyObjectType) { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; @@ -9591,12 +9590,12 @@ namespace ts { reportErrorsFromWidening(func, type); } - let widenedType = getWidenedType(type); + const widenedType = getWidenedType(type); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - let promiseType = createPromiseType(widenedType); + const promiseType = createPromiseType(widenedType); if (promiseType === emptyObjectType) { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; @@ -9610,10 +9609,10 @@ namespace ts { } function checkAndAggregateYieldOperandTypes(body: Block, contextualMapper?: TypeMapper): Type[] { - let aggregatedTypes: Type[] = []; + const aggregatedTypes: Type[] = []; forEachYieldExpression(body, yieldExpression => { - let expr = yieldExpression.expression; + const expr = yieldExpression.expression; if (expr) { let type = checkExpressionCached(expr, contextualMapper); @@ -9632,10 +9631,10 @@ namespace ts { } function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper, isAsync?: boolean): Type[] { - let aggregatedTypes: Type[] = []; + const aggregatedTypes: Type[] = []; forEachReturnStatement(body, returnStatement => { - let expr = returnStatement.expression; + const expr = returnStatement.expression; if (expr) { let type = checkExpressionCached(expr, contextualMapper); if (isAsync) { @@ -9690,7 +9689,7 @@ namespace ts { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); // Grammar checking - let hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + const hasGrammarError = checkGrammarFunctionLikeDeclaration(node); if (!hasGrammarError && node.kind === SyntaxKind.FunctionExpression) { checkGrammarForGenerator(node); } @@ -9700,34 +9699,34 @@ namespace ts { return anyFunctionType; } - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - let links = getNodeLinks(node); - let type = getTypeOfSymbol(node.symbol); - let contextSensitive = isContextSensitive(node); - let mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); + const links = getNodeLinks(node); + const type = getTypeOfSymbol(node.symbol); + const contextSensitive = isContextSensitive(node); + const mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); // Check if function expression is contextually typed and assign parameter types if so. // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to // check mightFixTypeParameters. if (mightFixTypeParameters || !(links.flags & NodeCheckFlags.ContextChecked)) { - let contextualSignature = getContextualSignature(node); + const contextualSignature = getContextualSignature(node); // If a type check is started at a function expression that is an argument of a function call, obtaining the // contextual type may recursively get back to here during overload resolution of the call. If so, we will have // already assigned contextual types. - let contextChecked = !!(links.flags & NodeCheckFlags.ContextChecked); + const contextChecked = !!(links.flags & NodeCheckFlags.ContextChecked); if (mightFixTypeParameters || !contextChecked) { links.flags |= NodeCheckFlags.ContextChecked; if (contextualSignature) { - let signature = getSignaturesOfType(type, SignatureKind.Call)[0]; + const signature = getSignaturesOfType(type, SignatureKind.Call)[0]; if (contextSensitive) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - let returnType = getReturnTypeFromBody(node, contextualMapper); + const returnType = getReturnTypeFromBody(node, contextualMapper); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } @@ -9751,12 +9750,12 @@ namespace ts { function checkFunctionExpressionOrObjectLiteralMethodBody(node: FunctionExpression | MethodDeclaration) { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - let returnType = node.type && getTypeFromTypeNode(node.type); + const returnType = node.type && getTypeFromTypeNode(node.type); let promisedType: Type; if (returnType && isAsync) { promisedType = checkAsyncFunctionReturnType(node); @@ -9785,10 +9784,10 @@ namespace ts { // should not be checking assignability of a promise to the return type. Instead, we need to // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. - let exprType = checkExpression(node.body); + const exprType = checkExpression(node.body); if (returnType) { if (isAsync) { - let awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); + const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); checkTypeAssignableTo(awaitedType, promisedType, node.body); } else { @@ -9811,7 +9810,7 @@ namespace ts { function checkReferenceExpression(n: Node, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { function findSymbol(n: Node): Symbol { - let symbol = getNodeLinks(n).resolvedSymbol; + const symbol = getNodeLinks(n).resolvedSymbol; // Because we got the symbol from the resolvedSymbol property, it might be of kind // SymbolFlags.ExportValue. In this case it is necessary to get the actual export // symbol, which will have the correct flags set on it. @@ -9827,14 +9826,14 @@ namespace ts { // All other expression constructs described in this chapter are classified as values. switch (n.kind) { case SyntaxKind.Identifier: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.3 // An identifier expression that references a variable or parameter is classified as a reference. // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & SymbolFlags.Variable) !== 0; } case SyntaxKind.PropertyAccessExpression: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed @@ -9854,15 +9853,15 @@ namespace ts { switch (n.kind) { case SyntaxKind.Identifier: case SyntaxKind.PropertyAccessExpression: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); return symbol && (symbol.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; } case SyntaxKind.ElementAccessExpression: { - let index = (n).argumentExpression; - let symbol = findSymbol((n).expression); + const index = (n).argumentExpression; + const symbol = findSymbol((n).expression); if (symbol && index && index.kind === SyntaxKind.StringLiteral) { - let name = (index).text; - let prop = getPropertyOfType(getTypeOfSymbol(symbol), name); + const name = (index).text; + const prop = getPropertyOfType(getTypeOfSymbol(symbol), name); return prop && (prop.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(prop) & NodeFlags.Const) !== 0; } return false; @@ -9914,12 +9913,12 @@ namespace ts { } } - let operandType = checkExpression(node.expression); + const operandType = checkExpression(node.expression); return checkAwaitedType(operandType, node); } function checkPrefixUnaryExpression(node: PrefixUnaryExpression): Type { - let operandType = checkExpression(node.operand); + const operandType = checkExpression(node.operand); switch (node.operator) { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: @@ -9932,7 +9931,7 @@ namespace ts { return booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: - let ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, @@ -9945,8 +9944,8 @@ namespace ts { } function checkPostfixUnaryExpression(node: PostfixUnaryExpression): Type { - let operandType = checkExpression(node.operand); - let ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const operandType = checkExpression(node.operand); + const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, @@ -9963,8 +9962,8 @@ namespace ts { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { - let types = (type).types; - for (let current of types) { + const types = (type).types; + for (const current of types) { if (current.flags & kind) { return true; } @@ -9980,8 +9979,8 @@ namespace ts { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { - let types = (type).types; - for (let current of types) { + const types = (type).types; + for (const current of types) { if (!(current.flags & kind)) { return false; } @@ -10030,10 +10029,10 @@ namespace ts { } function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, contextualMapper?: TypeMapper): Type { - let properties = node.properties; - for (let p of properties) { + const properties = node.properties; + for (const p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - let name = (p).name; + const name = (p).name; if (name.kind === SyntaxKind.ComputedPropertyName) { checkComputedPropertyName(name); } @@ -10041,8 +10040,8 @@ namespace ts { continue; } - let text = getTextOfPropertyName(name); - let type = isTypeAny(sourceType) + const text = getTextOfPropertyName(name); + const type = isTypeAny(sourceType) ? sourceType : getTypeOfPropertyOfType(sourceType, text) || isNumericLiteralName(text) && getIndexTypeOfType(sourceType, IndexKind.Number) || @@ -10071,14 +10070,14 @@ namespace ts { // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - let elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType; - let elements = node.elements; + const elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType; + const elements = node.elements; for (let i = 0; i < elements.length; i++) { - let e = elements[i]; + const e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { - let propName = "" + i; - let type = isTypeAny(sourceType) + const propName = "" + i; + const type = isTypeAny(sourceType) ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) @@ -10100,7 +10099,7 @@ namespace ts { error(e, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } else { - let restExpression = (e).expression; + const restExpression = (e).expression; if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -10141,7 +10140,7 @@ namespace ts { } function checkReferenceAssignment(target: Expression, sourceType: Type, contextualMapper?: TypeMapper): Type { - let targetType = checkExpression(target, contextualMapper); + const targetType = checkExpression(target, contextualMapper); if (checkReferenceExpression(target, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } @@ -10153,7 +10152,7 @@ namespace ts { } function checkBinaryLikeExpression(left: Expression, operatorToken: Node, right: Expression, contextualMapper?: TypeMapper, errorNode?: Node) { - let operator = operatorToken.kind; + const operator = operatorToken.kind; if (operator === SyntaxKind.EqualsToken && (left.kind === SyntaxKind.ObjectLiteralExpression || left.kind === SyntaxKind.ArrayLiteralExpression)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } @@ -10201,8 +10200,8 @@ namespace ts { } else { // otherwise just check each operand separately and report errors as normal - let leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - let rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); if (leftOk && rightOk) { checkAssignmentOperator(numberType); } @@ -10284,7 +10283,7 @@ namespace ts { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { - let offendingSymbolOperand = + const offendingSymbolOperand = someConstituentTypeHasKind(leftType, TypeFlags.ESSymbol) ? left : someConstituentTypeHasKind(rightType, TypeFlags.ESSymbol) ? right : undefined; @@ -10320,7 +10319,7 @@ namespace ts { // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - let ok = checkReferenceExpression(left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + const ok = checkReferenceExpression(left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); // Use default messages if (ok) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported @@ -10365,13 +10364,13 @@ namespace ts { } if (node.expression) { - let func = getContainingFunction(node); + const func = getContainingFunction(node); // If the user's code is syntactically correct, the func should always have a star. After all, // we are in a yield context. if (func && func.asteriskToken) { - let expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); + const expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); let expressionElementType: Type; - let nodeIsYieldStar = !!node.asteriskToken; + const nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); } @@ -10379,7 +10378,7 @@ namespace ts { // has no explicit return type because the return type is directly computed // from the yield expressions. if (func.type) { - let signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + const signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; if (nodeIsYieldStar) { checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, /*headMessage*/ undefined); } @@ -10396,8 +10395,8 @@ namespace ts { function checkConditionalExpression(node: ConditionalExpression, contextualMapper?: TypeMapper): Type { checkExpression(node.condition); - let type1 = checkExpression(node.whenTrue, contextualMapper); - let type2 = checkExpression(node.whenFalse, contextualMapper); + const type1 = checkExpression(node.whenTrue, contextualMapper); + const type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } @@ -10415,15 +10414,15 @@ namespace ts { } function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper?: TypeMapper): Type { - let saveContextualType = node.contextualType; + const saveContextualType = node.contextualType; node.contextualType = contextualType; - let result = checkExpression(node, contextualMapper); + const result = checkExpression(node, contextualMapper); node.contextualType = saveContextualType; return result; } function checkExpressionCached(node: Expression, contextualMapper?: TypeMapper): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = checkExpression(node, contextualMapper); } @@ -10452,17 +10451,17 @@ namespace ts { checkComputedPropertyName(node.name); } - let uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); + const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } function instantiateTypeWithSingleGenericCallSignature(node: Expression | MethodDeclaration, type: Type, contextualMapper?: TypeMapper) { if (isInferentialContext(contextualMapper)) { - let signature = getSingleCallSignature(type); + const signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - let contextualType = getContextualType(node); + const contextualType = getContextualType(node); if (contextualType) { - let contextualSignature = getSingleCallSignature(contextualType); + const contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper)); } @@ -10486,7 +10485,7 @@ namespace ts { type = checkQualifiedName(node); } else { - let uninstantiatedType = checkExpressionWorker(node, contextualMapper); + const uninstantiatedType = checkExpressionWorker(node, contextualMapper); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } @@ -10495,7 +10494,7 @@ namespace ts { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - let ok = + const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).expression === node) || (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).expression === node) || ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node)); @@ -10649,7 +10648,7 @@ namespace ts { function getTypePredicateParameterIndex(parameterList: NodeArray, parameter: Identifier): number { if (parameterList) { for (let i = 0; i < parameterList.length; i++) { - let param = parameterList[i]; + const param = parameterList[i]; if (param.name.kind === SyntaxKind.Identifier && (param.name).text === parameter.text) { @@ -10692,8 +10691,8 @@ namespace ts { if (node.type) { if (node.type.kind === SyntaxKind.TypePredicate) { - let typePredicate = getSignatureFromDeclaration(node).typePredicate; - let typePredicateNode = node.type; + const typePredicate = getSignatureFromDeclaration(node).typePredicate; + const typePredicateNode = node.type; if (isInLegalTypePredicatePosition(typePredicateNode)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { @@ -10716,7 +10715,7 @@ namespace ts { param.name.kind === SyntaxKind.ArrayBindingPattern) { (function checkBindingPattern(pattern: BindingPattern) { - for (let element of pattern.elements) { + for (const element of pattern.elements) { if (element.name.kind === SyntaxKind.Identifier && (element.name).text === typePredicate.parameterName) { @@ -10767,13 +10766,13 @@ namespace ts { if (node.type) { if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) { - let returnType = getTypeFromTypeNode(node.type); + const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { - let generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; - let iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + const generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + const iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); // Naively, one could check that IterableIterator is assignable to the return type annotation. // However, that would not catch the error in the following case. @@ -10792,7 +10791,7 @@ namespace ts { function checkTypeForDuplicateIndexSignatures(node: Node) { if (node.kind === SyntaxKind.InterfaceDeclaration) { - let nodeSymbol = getSymbolOfNode(node); + const nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { @@ -10803,12 +10802,12 @@ namespace ts { // TypeScript 1.0 spec (April 2014) // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration - let indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + const indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol) { let seenNumericIndexer = false; let seenStringIndexer = false; - for (let decl of indexSymbol.declarations) { - let declaration = decl; + for (const decl of indexSymbol.declarations) { + const declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: @@ -10862,8 +10861,8 @@ namespace ts { checkSourceElement(node.body); - let symbol = getSymbolOfNode(node); - let firstDeclaration = getDeclarationOfKind(symbol, node.kind); + const symbol = getSymbolOfNode(node); + const firstDeclaration = getDeclarationOfKind(symbol, node.kind); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(symbol); @@ -10917,11 +10916,11 @@ namespace ts { // TS 1.0 spec (April 2014): 8.3.2 // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. - let containingClassDecl = node.parent; + const containingClassDecl = node.parent; if (getClassExtendsHeritageClauseElement(containingClassDecl)) { - let containingClassSymbol = getSymbolOfNode(containingClassDecl); - let containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - let baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); + const containingClassSymbol = getSymbolOfNode(containingClassDecl); + const containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); + const baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); if (containsSuperCall(node.body)) { if (baseConstructorType === nullType) { @@ -10933,16 +10932,16 @@ namespace ts { // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - let superCallShouldBeFirst = + const superCallShouldBeFirst = forEach((node.parent).members, isInstancePropertyWithInitializer) || forEach(node.parameters, p => p.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { - let statements = (node.body).statements; + const statements = (node.body).statements; let superCallStatement: ExpressionStatement; - for (let statement of statements) { + for (const statement of statements) { if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((statement).expression)) { superCallStatement = statement; break; @@ -10987,15 +10986,15 @@ namespace ts { if (!hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - let otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - let otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; + const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & NodeFlags.AccessibilityModifier) !== (otherAccessor.flags & NodeFlags.AccessibilityModifier))) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - let currentAccessorType = getAnnotatedAccessorType(node); - let otherAccessorType = getAnnotatedAccessorType(otherAccessor); + const currentAccessorType = getAnnotatedAccessorType(node); + const otherAccessorType = getAnnotatedAccessorType(otherAccessor); // TypeScript 1.0 spec (April 2014): 4.5 // If both accessors include type annotations, the specified types must be identical. if (currentAccessorType && otherAccessorType) { @@ -11018,9 +11017,9 @@ namespace ts { function checkTypeArgumentConstraints(typeParameters: TypeParameter[], typeArguments: TypeNode[]): boolean { let result = true; for (let i = 0; i < typeParameters.length; i++) { - let constraint = getConstraintOfTypeParameter(typeParameters[i]); + const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - let typeArgument = typeArguments[i]; + const typeArgument = typeArguments[i]; result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } @@ -11029,13 +11028,13 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - let type = getTypeFromTypeReference(node); + const type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { - let symbol = getNodeLinks(node).resolvedSymbol; - let typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; + const symbol = getNodeLinks(node).resolvedSymbol; + const typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -11048,7 +11047,7 @@ namespace ts { function checkTypeLiteral(node: TypeLiteralNode) { forEach(node.members, checkSourceElement); if (produceDiagnostics) { - let type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -11060,7 +11059,7 @@ namespace ts { function checkTupleType(node: TupleTypeNode) { // Grammar checking - let hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + const hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { grammarErrorOnNode(node, Diagnostics.A_tuple_type_element_list_cannot_be_empty); } @@ -11080,7 +11079,7 @@ namespace ts { if (!produceDiagnostics) { return; } - let signature = getSignatureFromDeclaration(signatureDeclarationNode); + const signature = getSignatureFromDeclaration(signatureDeclarationNode); if (!signature.hasStringLiterals) { return; } @@ -11100,16 +11099,16 @@ namespace ts { // Use declaring type to obtain full list of signatures. if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === SyntaxKind.InterfaceDeclaration) { Debug.assert(signatureDeclarationNode.kind === SyntaxKind.CallSignature || signatureDeclarationNode.kind === SyntaxKind.ConstructSignature); - let signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; - let containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - let containingType = getDeclaredTypeOfSymbol(containingSymbol); + const signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; + const containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); + const containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); } else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (let otherSignature of signaturesToCheck) { + for (const otherSignature of signaturesToCheck) { if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -11148,19 +11147,19 @@ namespace ts { // The caveat is that if some overloads are defined in lib.d.ts, we don't want to // report the errors on those. To achieve this, we will say that the implementation is // the canonical signature only if it is in the same container as the first overload - let implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + const implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; } function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, flagsToCheck: NodeFlags, someOverloadFlags: NodeFlags, allOverloadFlags: NodeFlags): void { // Error if some overloads have a flag that is not shared by all overloads. To find the // deviations, we XOR someOverloadFlags with allOverloadFlags - let someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - let canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); forEach(overloads, o => { - let deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & NodeFlags.Export) { error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } @@ -11179,9 +11178,9 @@ namespace ts { function checkQuestionTokenAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, someHaveQuestionToken: boolean, allHaveQuestionToken: boolean): void { if (someHaveQuestionToken !== allHaveQuestionToken) { - let canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); + const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); forEach(overloads, o => { - let deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; + const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); } @@ -11189,7 +11188,7 @@ namespace ts { } } - let flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected | NodeFlags.Abstract; + const flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected | NodeFlags.Abstract; let someNodeFlags: NodeFlags = 0; let allNodeFlags = flagsToCheck; let someHaveQuestionToken = false; @@ -11199,8 +11198,8 @@ namespace ts { let lastSeenNonAmbientDeclaration: FunctionLikeDeclaration; let previousDeclaration: FunctionLikeDeclaration; - let declarations = symbol.declarations; - let isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; + const declarations = symbol.declarations; + const isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; function reportImplementationExpectedError(node: FunctionLikeDeclaration): void { if (node.name && nodeIsMissing(node.name)) { @@ -11208,7 +11207,7 @@ namespace ts { } let seen = false; - let subsequentNode = forEachChild(node.parent, c => { + const subsequentNode = forEachChild(node.parent, c => { if (seen) { return c; } @@ -11218,13 +11217,13 @@ namespace ts { }); if (subsequentNode) { if (subsequentNode.kind === node.kind) { - let errorNode: Node = (subsequentNode).name || subsequentNode; + const errorNode: Node = (subsequentNode).name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members Debug.assert(node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature); Debug.assert((node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static)); - let diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; error(errorNode, diagnostic); return; } @@ -11234,7 +11233,7 @@ namespace ts { } } } - let errorNode: Node = node.name || node; + const errorNode: Node = node.name || node; if (isConstructor) { error(errorNode, Diagnostics.Constructor_implementation_is_missing); } @@ -11252,13 +11251,13 @@ namespace ts { // when checking exported function declarations across modules check only duplicate implementations // names and consistency of modifiers are verified when we check local symbol - let isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; + const isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; let duplicateFunctionDeclaration = false; let multipleConstructorImplementation = false; - for (let current of declarations) { - let node = current; - let inAmbientContext = isInAmbientContext(node); - let inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; + for (const current of declarations) { + const node = current; + const inAmbientContext = isInAmbientContext(node); + const inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -11271,7 +11270,7 @@ namespace ts { } if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) { - let currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); @@ -11329,8 +11328,8 @@ namespace ts { checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); if (bodyDeclaration) { - let signatures = getSignaturesOfSymbol(symbol); - let bodySignature = getSignatureFromDeclaration(bodyDeclaration); + const signatures = getSignaturesOfSymbol(symbol); + const bodySignature = getSignatureFromDeclaration(bodyDeclaration); // If the implementation signature has string literals, we will have reported an error in // checkSpecializedSignatureDeclaration if (!bodySignature.hasStringLiterals) { @@ -11348,7 +11347,7 @@ namespace ts { // function g(x: string, y: string) { } // // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (let signature of signatures) { + for (const signature of signatures) { if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -11386,9 +11385,9 @@ namespace ts { let exportedDeclarationSpaces = SymbolFlags.None; let nonExportedDeclarationSpaces = SymbolFlags.None; let defaultExportedDeclarationSpaces = SymbolFlags.None; - for (let d of symbol.declarations) { - let declarationSpaces = getDeclarationSpaces(d); - let effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); + const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); if (effectiveDeclarationFlags & NodeFlags.Export) { if (effectiveDeclarationFlags & NodeFlags.Default) { @@ -11404,15 +11403,15 @@ namespace ts { } // Spaces for anyting not declared a 'default export'. - let nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - let commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - let commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + const commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { // declaration spaces for exported and non-exported declarations intersect - for (let d of symbol.declarations) { - let declarationSpaces = getDeclarationSpaces(d); + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); // Only error on the declarations that conributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { @@ -11437,7 +11436,7 @@ namespace ts { return SymbolFlags.ExportType | SymbolFlags.ExportValue; case SyntaxKind.ImportEqualsDeclaration: let result: SymbolFlags = 0; - let target = resolveAlias(getSymbolOfNode(d)); + const target = resolveAlias(getSymbolOfNode(d)); forEach(target.declarations, d => { result |= getDeclarationSpaces(d); }); return result; default: @@ -11487,32 +11486,32 @@ namespace ts { return (promise).typeArguments[0]; } - let globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); + const globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } - let thenFunction = getTypeOfPropertyOfType(promise, "then"); + const thenFunction = getTypeOfPropertyOfType(promise, "then"); if (thenFunction && (thenFunction.flags & TypeFlags.Any)) { return undefined; } - let thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; + const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; if (thenSignatures.length === 0) { return undefined; } - let onfulfilledParameterType = getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)); + const onfulfilledParameterType = getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)); if (onfulfilledParameterType.flags & TypeFlags.Any) { return undefined; } - let onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call); + const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - let valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + const valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); return valueParameterType; } @@ -11536,15 +11535,15 @@ namespace ts { function checkAwaitedTypeWorker(type: Type): Type { if (type.flags & TypeFlags.Union) { - let types: Type[] = []; - for (let constituentType of (type).types) { + const types: Type[] = []; + for (const constituentType of (type).types) { types.push(checkAwaitedTypeWorker(constituentType)); } return getUnionType(types); } else { - let promisedType = getPromisedType(type); + const promisedType = getPromisedType(type); if (promisedType === undefined) { // The type was not a PromiseLike, so it could not be unwrapped any further. // As long as the type does not have a callable "then" property, it is @@ -11611,7 +11610,7 @@ namespace ts { // Keep track of the type we're about to unwrap to avoid bad recursive promise types. // See the comments above for more information. awaitedTypeStack.push(type.id); - let awaitedType = checkAwaitedTypeWorker(promisedType); + const awaitedType = checkAwaitedTypeWorker(promisedType); awaitedTypeStack.pop(); return awaitedType; } @@ -11633,7 +11632,7 @@ namespace ts { * callable `then` signature. */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { - let globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. @@ -11667,16 +11666,16 @@ namespace ts { // When we get the type of the `Promise` symbol here, we get the type of the static // side of the `Promise` class, which would be `{ new (...): Promise }`. - let promiseType = getTypeFromTypeNode(node.type); + const promiseType = getTypeFromTypeNode(node.type); if (promiseType === unknownType && compilerOptions.isolatedModules) { // If we are compiling with isolatedModules, we may not be able to resolve the // type as a value. As such, we will just return unknownType; return unknownType; } - let promiseConstructor = getNodeLinks(node.type).resolvedSymbol; + const promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - let typeName = promiseConstructor + const typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); error(node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); @@ -11684,15 +11683,15 @@ namespace ts { } // Validate the promise constructor type. - let promiseConstructorType = getTypeOfSymbol(promiseConstructor); + const promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } // Verify there is no local declaration that could collide with the promise constructor. - let promiseName = getEntityNameFromTypeNode(node.type); - let root = getFirstIdentifier(promiseName); - let rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value); + const promiseName = getEntityNameFromTypeNode(node.type); + const root = getFirstIdentifier(promiseName); + const rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value); if (rootSymbol) { error(rootSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, @@ -11706,19 +11705,19 @@ namespace ts { /** Check a decorator */ function checkDecorator(node: Decorator): void { - let signature = getResolvedSignature(node); - let returnType = getReturnTypeOfSignature(signature); + const signature = getResolvedSignature(node); + const returnType = getReturnTypeOfSignature(signature); if (returnType.flags & TypeFlags.Any) { return; } let expectedReturnType: Type; - let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); let errorInfo: DiagnosticMessageChain; switch (node.parent.kind) { case SyntaxKind.ClassDeclaration: - let classSymbol = getSymbolOfNode(node.parent); - let classConstructorType = getTypeOfSymbol(classSymbol); + const classSymbol = getSymbolOfNode(node.parent); + const classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; @@ -11740,8 +11739,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - let methodType = getTypeOfNode(node.parent); - let descriptorType = createTypedPropertyDescriptorType(methodType); + const methodType = getTypeOfNode(node.parent); + const descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; } @@ -11760,13 +11759,13 @@ namespace ts { // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. if (node && node.kind === SyntaxKind.TypeReference) { - let root = getFirstIdentifier((node).typeName); - let meaning = root.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; + const root = getFirstIdentifier((node).typeName); + const meaning = root.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; // Resolve type so we know which symbol is referenced - let rootSymbol = resolveName(root, root.text, meaning | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + const rootSymbol = resolveName(root, root.text, meaning | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) { - let aliasTarget = resolveAlias(rootSymbol); + const aliasTarget = resolveAlias(rootSymbol); // If alias has value symbol - mark alias as referenced if (aliasTarget.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { markAliasSymbolAsReferenced(rootSymbol); @@ -11802,7 +11801,7 @@ namespace ts { /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node: FunctionLikeDeclaration) { // ensure all type annotations with a value declaration are checked as an expression - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { checkTypeAnnotationAsExpression(parameter); } } @@ -11827,7 +11826,7 @@ namespace ts { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { case SyntaxKind.ClassDeclaration: - let constructor = getFirstConstructorWithBody(node); + const constructor = getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } @@ -11867,7 +11866,7 @@ namespace ts { function checkFunctionLikeDeclaration(node: FunctionLikeDeclaration): void { checkDecorators(node); checkSignatureDeclaration(node); - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } @@ -11885,10 +11884,10 @@ namespace ts { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode - let symbol = getSymbolOfNode(node); - let localSymbol = node.localSymbol || symbol; + const symbol = getSymbolOfNode(node); + const localSymbol = node.localSymbol || symbol; - let firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); + const firstDeclaration = getDeclarationOfKind(localSymbol, node.kind); // Only type check the symbol once if (node === firstDeclaration) { checkFunctionOrConstructorSymbol(localSymbol); @@ -11905,7 +11904,7 @@ namespace ts { checkSourceElement(node.body); if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - let returnType = getTypeFromTypeNode(node.type); + const returnType = getTypeFromTypeNode(node.type); let promisedType: Type; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); @@ -11975,7 +11974,7 @@ namespace ts { return false; } - let root = getRootDeclaration(node); + const root = getRootDeclaration(node); if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent).body)) { // just an overload - no codegen impact return false; @@ -11995,7 +11994,7 @@ namespace ts { let current = node; while (current) { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { - let isDeclaration = node.kind !== SyntaxKind.Identifier; + const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -12014,14 +12013,14 @@ namespace ts { } // bubble up and find containing type - let enclosingClass = getContainingClass(node); + const enclosingClass = getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || isInAmbientContext(enclosingClass)) { return; } if (getClassExtendsHeritageClauseElement(enclosingClass)) { - let isDeclaration = node.kind !== SyntaxKind.Identifier; + const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error(node, Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -12042,7 +12041,7 @@ namespace ts { } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - let parent = getDeclarationContainer(node); + const parent = getDeclarationContainer(node); if (parent.kind === SyntaxKind.SourceFile && isExternalModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, @@ -12065,15 +12064,15 @@ namespace ts { // A non-initialized declaration is a no-op as the block declaration will resolve before the var // declaration. the problem is if the declaration has an initializer. this will act as a write to the // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized let declarations will not + // Only consider declarations with initializers, uninitialized const declarations will not // step on a let/const variable. - // Do not consider let and const declarations, as duplicate block-scoped declarations + // Do not consider const and const declarations, as duplicate block-scoped declarations // are handled by the binder. - // We are only looking for let declarations that step on let\const declarations from a + // We are only looking for const declarations that step on let\const declarations from a // different scope. e.g.: // { // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // let x = 0; // symbol for this declaration will be 'symbol' + // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters @@ -12088,22 +12087,22 @@ namespace ts { return; } - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { - let localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + const localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) { - let varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); - let container = + const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); + const container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - let namesShareScope = + const namesShareScope = container && (container.kind === SyntaxKind.Block && isFunctionLike(container.parent) || container.kind === SyntaxKind.ModuleBlock || @@ -12115,7 +12114,7 @@ namespace ts { // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - let name = symbolToString(localDeclarationSymbol); + const name = symbolToString(localDeclarationSymbol); error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } @@ -12129,12 +12128,12 @@ namespace ts { return; } - let func = getContainingFunction(node); + const func = getContainingFunction(node); visit(node.initializer); function visit(n: Node) { if (n.kind === SyntaxKind.Identifier) { - let referencedSymbol = getNodeLinks(n).resolvedSymbol; + const referencedSymbol = getNodeLinks(n).resolvedSymbol; // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name and if this entry matches the resolved symbol if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, SymbolFlags.Value) === referencedSymbol) { @@ -12197,9 +12196,8 @@ namespace ts { } return; } - - let symbol = getSymbolOfNode(node); - let type = getTypeOfVariableOrParameterOrProperty(symbol); + const symbol = getSymbolOfNode(node); + const type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer if (node.initializer) { @@ -12210,7 +12208,7 @@ namespace ts { else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - let declarationType = getWidenedTypeForVariableLikeDeclaration(node); + const declarationType = getWidenedTypeForVariableLikeDeclaration(node); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -12332,8 +12330,8 @@ namespace ts { checkForInOrForOfVariableDeclaration(node); } else { - let varExpr = node.initializer; - let iteratedType = checkRightHandSideOfForOf(node.expression); + const varExpr = node.initializer; + const iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { @@ -12343,7 +12341,7 @@ namespace ts { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { - let leftType = checkExpression(varExpr); + const leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ Diagnostics.Invalid_left_hand_side_in_for_of_statement, /*constantVariableMessage*/ Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); @@ -12370,7 +12368,7 @@ namespace ts { // 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.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variable = (node.initializer).declarations[0]; + const variable = (node.initializer).declarations[0]; if (variable && isBindingPattern(variable.name)) { error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } @@ -12382,8 +12380,8 @@ namespace ts { // 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. - let varExpr = node.initializer; - let leftType = checkExpression(varExpr); + const varExpr = node.initializer; + const leftType = checkExpression(varExpr); if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } @@ -12396,7 +12394,7 @@ namespace ts { } } - let rightType = checkExpression(node.expression); + const rightType = checkExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { @@ -12407,16 +12405,16 @@ namespace ts { } function checkForInOrForOfVariableDeclaration(iterationStatement: ForInStatement | ForOfStatement): void { - let variableDeclarationList = iterationStatement.initializer; + const variableDeclarationList = iterationStatement.initializer; // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. if (variableDeclarationList.declarations.length >= 1) { - let decl = variableDeclarationList.declarations[0]; + const decl = variableDeclarationList.declarations[0]; checkVariableDeclaration(decl); } } function checkRightHandSideOfForOf(rhsExpression: Expression): Type { - let expressionType = getTypeOfExpression(rhsExpression); + const expressionType = getTypeOfExpression(rhsExpression); return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true); } @@ -12434,7 +12432,7 @@ namespace ts { } if (isArrayLikeType(inputType)) { - let indexType = getIndexTypeOfType(inputType, IndexKind.Number); + const indexType = getIndexTypeOfType(inputType, IndexKind.Number); if (indexType) { return indexType; } @@ -12448,7 +12446,7 @@ namespace ts { * When errorNode is undefined, it means we should not report any errors. */ function checkElementTypeOfIterable(iterable: Type, errorNode: Node): Type { - let elementType = getElementTypeOfIterable(iterable, errorNode); + const elementType = getElementTypeOfIterable(iterable, errorNode); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. if (errorNode && elementType) { @@ -12484,7 +12482,7 @@ namespace ts { return undefined; } - let typeAsIterable = type; + const typeAsIterable = type; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. @@ -12492,12 +12490,12 @@ namespace ts { typeAsIterable.iterableElementType = (type).typeArguments[0]; } else { - let iteratorFunction = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")); + const iteratorFunction = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")); if (isTypeAny(iteratorFunction)) { return undefined; } - let iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; + const iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; if (iteratorFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); @@ -12530,7 +12528,7 @@ namespace ts { return undefined; } - let typeAsIterator = type; + const typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. @@ -12538,12 +12536,12 @@ namespace ts { typeAsIterator.iteratorElementType = (type).typeArguments[0]; } else { - let iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + const iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); if (isTypeAny(iteratorNextFunction)) { return undefined; } - let iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; + const iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; if (iteratorNextFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, Diagnostics.An_iterator_must_have_a_next_method); @@ -12551,12 +12549,12 @@ namespace ts { return undefined; } - let iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + const iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } - let iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + const iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); if (!iteratorNextValue) { if (errorNode) { error(errorNode, Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); @@ -12608,8 +12606,8 @@ namespace ts { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. - let arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); - let hasStringConstituent = arrayOrStringType !== arrayType; + const arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + const hasStringConstituent = arrayOrStringType !== arrayType; let reportedError = false; if (hasStringConstituent) { @@ -12631,7 +12629,7 @@ namespace ts { // if the input type is number | string, we want to say that number is not an array type. // But if the input was just number, we want to say that number is not an array type // or a string type. - let diagnostic = hasStringConstituent + const diagnostic = hasStringConstituent ? Diagnostics.Type_0_is_not_an_array_type : Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); @@ -12639,7 +12637,7 @@ namespace ts { return hasStringConstituent ? stringType : unknownType; } - let arrayElementType = getIndexTypeOfType(arrayType, IndexKind.Number) || unknownType; + const arrayElementType = getIndexTypeOfType(arrayType, IndexKind.Number) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] if (arrayElementType.flags & TypeFlags.StringLike) { @@ -12666,18 +12664,18 @@ namespace ts { function checkReturnStatement(node: ReturnStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - let functionBlock = getContainingFunction(node); + const functionBlock = getContainingFunction(node); if (!functionBlock) { grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); } } if (node.expression) { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func) { - let signature = getSignatureFromDeclaration(func); - let returnType = getReturnTypeOfSignature(signature); - let exprType = checkExpressionCached(node.expression); + const signature = getSignatureFromDeclaration(func); + const returnType = getReturnTypeOfSignature(signature); + const exprType = checkExpressionCached(node.expression); if (func.asteriskToken) { // A generator does not need its return expressions checked against its return type. @@ -12697,8 +12695,8 @@ namespace ts { } else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { if (isAsyncFunctionLike(func)) { - let promisedType = getPromisedType(returnType); - let awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + const promisedType = getPromisedType(returnType); + const awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); if (promisedType) { // If the function has a return type, but promisedType is // undefined, an error will be reported in checkAsyncFunctionReturnType @@ -12733,7 +12731,7 @@ namespace ts { let firstDefaultClause: CaseOrDefaultClause; let hasDuplicateDefaultClause = false; - let expressionType = checkExpression(node.expression); + const expressionType = checkExpression(node.expression); forEach(node.caseBlock.clauses, clause => { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) { @@ -12741,19 +12739,19 @@ namespace ts { firstDefaultClause = clause; } else { - let sourceFile = getSourceFileOfNode(node); - let start = skipTrivia(sourceFile.text, clause.pos); - let end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + const sourceFile = getSourceFileOfNode(node); + const start = skipTrivia(sourceFile.text, clause.pos); + const end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) { - let caseClause = clause; + const 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. - let caseType = checkExpression(caseClause.expression); + const caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); @@ -12772,7 +12770,7 @@ namespace ts { break; } if (current.kind === SyntaxKind.LabeledStatement && (current).label.text === node.label.text) { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; } @@ -12802,7 +12800,7 @@ namespace ts { checkGrammarStatementInAmbientContext(node); checkBlock(node.tryBlock); - let catchClause = node.catchClause; + const catchClause = node.catchClause; if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { @@ -12816,10 +12814,10 @@ namespace ts { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - let identifierName = (catchClause.variableDeclaration.name).text; - let locals = catchClause.block.locals; + const identifierName = (catchClause.variableDeclaration.name).text; + const locals = catchClause.block.locals; if (locals && hasProperty(locals, identifierName)) { - let localSymbol = locals[identifierName]; + const localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & SymbolFlags.BlockScopedVariable) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } @@ -12836,27 +12834,27 @@ namespace ts { } function checkIndexConstraints(type: Type) { - let declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); - let declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); + const declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); + const declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); - let stringIndexType = getIndexTypeOfType(type, IndexKind.String); - let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); + const stringIndexType = getIndexTypeOfType(type, IndexKind.String); + const numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType || numberIndexType) { forEach(getPropertiesOfObjectType(type), prop => { - let propType = getTypeOfSymbol(prop); + const propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); if (type.flags & TypeFlags.Class && isClassLike(type.symbol.valueDeclaration)) { - let classDeclaration = type.symbol.valueDeclaration; - for (let member of classDeclaration.members) { + const classDeclaration = type.symbol.valueDeclaration; + for (const member of classDeclaration.members) { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!(member.flags & NodeFlags.Static) && hasDynamicName(member)) { - let propType = getTypeOfSymbol(member.symbol); + const propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); } @@ -12869,7 +12867,7 @@ namespace ts { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (type.flags & TypeFlags.Interface)) { - let someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); + const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } @@ -12909,12 +12907,12 @@ namespace ts { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together - let someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); + const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - let errorMessage = + const errorMessage = indexKind === IndexKind.String ? Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; @@ -12941,7 +12939,7 @@ namespace ts { function checkTypeParameters(typeParameterDeclarations: TypeParameterDeclaration[]) { if (typeParameterDeclarations) { for (let i = 0, n = typeParameterDeclarations.length; i < n; i++) { - let node = typeParameterDeclarations[i]; + const node = typeParameterDeclarations[i]; checkTypeParameter(node); if (produceDiagnostics) { @@ -12979,22 +12977,22 @@ namespace ts { } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); - let type = getDeclaredTypeOfSymbol(symbol); - let typeWithThis = getTypeWithThisArgument(type); - let staticType = getTypeOfSymbol(symbol); + const symbol = getSymbolOfNode(node); + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); + const staticType = getTypeOfSymbol(symbol); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { emitExtends = emitExtends || !isInAmbientContext(node); - let baseTypes = getBaseTypes(type); + const baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { - let baseType = baseTypes[0]; - let staticBaseType = getBaseConstructorTypeOfClass(type); + const baseType = baseTypes[0]; + const staticBaseType = getBaseConstructorTypeOfClass(type); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { forEach(baseTypeNode.typeArguments, checkSourceElement); - for (let constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) { + for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) { if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { break; } @@ -13009,7 +13007,7 @@ namespace ts { // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). - let constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (forEach(constructors, sig => getReturnTypeOfSignature(sig) !== baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } @@ -13018,17 +13016,17 @@ namespace ts { } } - let implementedTypeNodes = getClassImplementsHeritageClauseElements(node); + const implementedTypeNodes = getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (let typeRefNode of implementedTypeNodes) { + for (const typeRefNode of implementedTypeNodes) { if (!isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - let t = getTypeFromTypeNode(typeRefNode); + const t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - let declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; + const declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1); } @@ -13073,16 +13071,16 @@ namespace ts { // derived class instance member variables and accessors, but not by other kinds of members. // NOTE: assignability is checked in checkClassDeclaration - let baseProperties = getPropertiesOfObjectType(baseType); - for (let baseProperty of baseProperties) { - let base = getTargetSymbol(baseProperty); + const baseProperties = getPropertiesOfObjectType(baseType); + for (const baseProperty of baseProperties) { + const base = getTargetSymbol(baseProperty); if (base.flags & SymbolFlags.Prototype) { continue; } - let derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - let baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + const derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); + const baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); @@ -13093,7 +13091,7 @@ namespace ts { if (derived === base) { // derived class inherits base without override/redeclaration - let derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), @@ -13111,7 +13109,7 @@ namespace ts { } else { // derived overrides base. - let derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + const derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); if ((baseDeclarationFlags & NodeFlags.Private) || (derivedDeclarationFlags & NodeFlags.Private)) { // either base or derived property is private - not override, skip it continue; @@ -13168,8 +13166,8 @@ namespace ts { // When a generic interface has multiple declarations, all declarations must have identical type parameter // lists, i.e. identical type parameter names with identical constraints in identical order. for (let i = 0, len = list1.length; i < len; i++) { - let tp1 = list1[i]; - let tp2 = list2[i]; + const tp1 = list1[i]; + const tp2 = list2[i]; if (tp1.name.text !== tp2.name.text) { return false; } @@ -13187,29 +13185,29 @@ namespace ts { } function checkInheritedPropertiesAreIdentical(type: InterfaceType, typeNode: Node): boolean { - let baseTypes = getBaseTypes(type); + const baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { return true; } - let seen: Map<{ prop: Symbol; containingType: Type }> = {}; + const seen: Map<{ prop: Symbol; containingType: Type }> = {}; forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen[p.name] = { prop: p, containingType: type }; }); let ok = true; - for (let base of baseTypes) { - let properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (let prop of properties) { + for (const base of baseTypes) { + const properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); + for (const prop of properties) { if (!hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { - let existing = seen[prop.name]; - let isInheritedProperty = existing.containingType !== type; + const existing = seen[prop.name]; + const isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; - let typeName1 = typeToString(existing.containingType); - let typeName2 = typeToString(base); + const typeName1 = typeToString(existing.containingType); + const typeName2 = typeToString(base); let errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); @@ -13231,8 +13229,8 @@ namespace ts { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); - let firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const symbol = getSymbolOfNode(node); + const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -13241,11 +13239,11 @@ namespace ts { // Only check this symbol once if (node === firstInterfaceDecl) { - let type = getDeclaredTypeOfSymbol(symbol); - let typeWithThis = getTypeWithThisArgument(type); + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); // run subsequent checks only if first set succeeded if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (let baseType of getBaseTypes(type)) { + for (const baseType of getBaseTypes(type)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1); } checkIndexConstraints(type); @@ -13275,21 +13273,21 @@ namespace ts { } function computeEnumMemberValues(node: EnumDeclaration) { - let nodeLinks = getNodeLinks(node); + const nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) { - let enumSymbol = getSymbolOfNode(node); - let enumType = getDeclaredTypeOfSymbol(enumSymbol); + const enumSymbol = getSymbolOfNode(node); + const enumType = getDeclaredTypeOfSymbol(enumSymbol); let autoValue = 0; // set to undefined when enum member is non-constant - let ambient = isInAmbientContext(node); - let enumIsConst = isConst(node); + const ambient = isInAmbientContext(node); + const enumIsConst = isConst(node); for (const member of node.members) { if (isComputedNonLiteralName(member.name)) { error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums); } else { - let text = getTextOfPropertyName(member.name); + const text = getTextOfPropertyName(member.name); if (isNumericLiteralName(text)) { error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name); } @@ -13297,7 +13295,7 @@ namespace ts { const previousEnumMemberIsNonConstant = autoValue === undefined; - let initializer = member.initializer; + const initializer = member.initializer; if (initializer) { autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); } @@ -13326,7 +13324,7 @@ namespace ts { // Controls if error should be reported after evaluation of constant value is completed // Can be false if another more precise error was already reported during evaluation. let reportError = true; - let value = evalConstant(initializer); + const value = evalConstant(initializer); if (reportError) { if (value === undefined) { @@ -13356,7 +13354,7 @@ namespace ts { function evalConstant(e: Node): number { switch (e.kind) { case SyntaxKind.PrefixUnaryExpression: - let value = evalConstant((e).operand); + const value = evalConstant((e).operand); if (value === undefined) { return undefined; } @@ -13367,11 +13365,11 @@ namespace ts { } return undefined; case SyntaxKind.BinaryExpression: - let left = evalConstant((e).left); + const left = evalConstant((e).left); if (left === undefined) { return undefined; } - let right = evalConstant((e).right); + const right = evalConstant((e).right); if (right === undefined) { return undefined; } @@ -13396,8 +13394,8 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: - let member = initializer.parent; - let currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); + const member = initializer.parent; + const currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); let enumType: Type; let propertyName: string; @@ -13447,12 +13445,12 @@ namespace ts { return undefined; } - let property = getPropertyOfObjectType(enumType, propertyName); + const property = getPropertyOfObjectType(enumType, propertyName); if (!property || !(property.flags & SymbolFlags.EnumMember)) { return undefined; } - let propertyDecl = property.valueDeclaration; + const propertyDecl = property.valueDeclaration; // self references are illegal if (member === propertyDecl) { return undefined; @@ -13486,7 +13484,7 @@ namespace ts { computeEnumMemberValues(node); - let enumIsConst = isConst(node); + const enumIsConst = isConst(node); if (compilerOptions.isolatedModules && enumIsConst && isInAmbientContext(node)) { error(node.name, Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } @@ -13497,8 +13495,8 @@ namespace ts { // for the first member. // // Only perform this check once per symbol - let enumSymbol = getSymbolOfNode(node); - let firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); + const enumSymbol = getSymbolOfNode(node); + const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { if (enumSymbol.declarations.length > 1) { // check that const is placed\omitted on all enum declarations @@ -13516,12 +13514,12 @@ namespace ts { return false; } - let enumDeclaration = declaration; + const enumDeclaration = declaration; if (!enumDeclaration.members.length) { return false; } - let firstEnumMember = enumDeclaration.members[0]; + const firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { if (seenEnumMissingInitialInitializer) { error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); @@ -13535,8 +13533,8 @@ namespace ts { } function getFirstNonAmbientClassOrFunctionDeclaration(symbol: Symbol): Declaration { - let declarations = symbol.declarations; - for (let declaration of declarations) { + const declarations = symbol.declarations; + for (const declaration of declarations) { if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && !isInAmbientContext(declaration)) { @@ -13547,8 +13545,8 @@ namespace ts { } function inSameLexicalScope(node1: Node, node2: Node) { - let container1 = getEnclosingBlockScopeContainer(node1); - let container2 = getEnclosingBlockScopeContainer(node2); + const container1 = getEnclosingBlockScopeContainer(node1); + const container2 = getEnclosingBlockScopeContainer(node2); if (isGlobalSourceFile(container1)) { return isGlobalSourceFile(container2); } @@ -13563,8 +13561,8 @@ namespace ts { function checkModuleDeclaration(node: ModuleDeclaration) { if (produceDiagnostics) { // Grammar checking - let isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; - let contextErrorMessage = isAmbientExternalModule + const isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; + const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { @@ -13581,14 +13579,14 @@ namespace ts { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(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 || compilerOptions.isolatedModules)) { - let firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) { error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); @@ -13600,7 +13598,7 @@ namespace ts { // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - let mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); + const mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= NodeCheckFlags.LexicalModuleMergesWithClass; @@ -13637,12 +13635,12 @@ namespace ts { } function checkExternalImportOrExportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean { - let moduleName = getExternalModuleName(node); + const moduleName = getExternalModuleName(node); if (!nodeIsMissing(moduleName) && moduleName.kind !== SyntaxKind.StringLiteral) { error(moduleName, Diagnostics.String_literal_expected); return false; } - let inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(moduleName, node.kind === SyntaxKind.ExportDeclaration ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : @@ -13661,15 +13659,15 @@ namespace ts { } function checkAliasSymbol(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier | ExportSpecifier) { - let symbol = getSymbolOfNode(node); - let target = resolveAlias(symbol); + const symbol = getSymbolOfNode(node); + const target = resolveAlias(symbol); if (target !== unknownSymbol) { - let excludedMeanings = + const excludedMeanings = (symbol.flags & SymbolFlags.Value ? SymbolFlags.Value : 0) | (symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) | (symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0); if (target.flags & excludedMeanings) { - let message = node.kind === SyntaxKind.ExportSpecifier ? + const message = node.kind === SyntaxKind.ExportSpecifier ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -13692,7 +13690,7 @@ namespace ts { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { - let importClause = node.importClause; + const importClause = node.importClause; if (importClause) { if (importClause.name) { checkImportBinding(importClause); @@ -13722,11 +13720,11 @@ namespace ts { markExportAsReferenced(node); } if (isInternalModuleImportEqualsDeclaration(node)) { - let target = resolveAlias(getSymbolOfNode(node)); + const target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & SymbolFlags.Value) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - let moduleName = getFirstIdentifier(node.moduleReference); + const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, SymbolFlags.Value | SymbolFlags.Namespace).flags & SymbolFlags.Namespace)) { error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); } @@ -13761,14 +13759,14 @@ namespace ts { // export { x, y } from "foo" forEach(node.exportClause.elements, checkExportSpecifier); - let inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" - let moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); if (moduleSymbol && moduleSymbol.exports["export="]) { error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } @@ -13795,7 +13793,7 @@ namespace ts { return; } - let container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; + const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; if (container.kind === SyntaxKind.ModuleDeclaration && (container).name.kind === SyntaxKind.Identifier) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; @@ -13845,12 +13843,12 @@ namespace ts { } function checkExternalModuleExports(node: SourceFile | ModuleDeclaration) { - let moduleSymbol = getSymbolOfNode(node); - let links = getSymbolLinks(moduleSymbol); + const moduleSymbol = getSymbolOfNode(node); + const links = getSymbolLinks(moduleSymbol); if (!links.exportsChecked) { - let exportEqualsSymbol = moduleSymbol.exports["export="]; + const exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - let declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } links.exportsChecked = true; @@ -13868,7 +13866,7 @@ namespace ts { return; } - let kind = node.kind; + const kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessivly // hitting the cancellation token on every node we check. @@ -13992,8 +13990,8 @@ namespace ts { // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: - // let foo = function () { - // let s = foo(); + // const foo = function () { + // const s = foo(); // return "hello"; // } // Here, performing a full type check of the body of the function expression whilst in the process of @@ -14099,7 +14097,7 @@ namespace ts { } function checkSourceFile(node: SourceFile) { - let start = new Date().getTime(); + const start = new Date().getTime(); checkSourceFileWorker(node); @@ -14108,7 +14106,7 @@ namespace ts { // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node: SourceFile) { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!(links.flags & NodeCheckFlags.TypeChecked)) { // Check whether the file has declared it is the default lib, // and whether the user has specifically chosen to avoid checking it. @@ -14210,7 +14208,7 @@ namespace ts { } function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] { - let symbols: SymbolTable = {}; + const symbols: SymbolTable = {}; let memberFlags: NodeFlags = 0; if (isInsideWithStatementBody(location)) { @@ -14240,7 +14238,7 @@ namespace ts { copySymbols(getSymbolOfNode(location).exports, meaning & SymbolFlags.EnumMember); break; case SyntaxKind.ClassExpression: - let className = (location).name; + const className = (location).name; if (className) { copySymbol(location.symbol, meaning); } @@ -14257,7 +14255,7 @@ namespace ts { } break; case SyntaxKind.FunctionExpression: - let funcName = (location).name; + const funcName = (location).name; if (funcName) { copySymbol(location.symbol, meaning); } @@ -14284,7 +14282,7 @@ namespace ts { */ function copySymbol(symbol: Symbol, meaning: SymbolFlags): void { if (symbol.flags & meaning) { - let id = symbol.name; + const id = symbol.name; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array @@ -14296,8 +14294,8 @@ namespace ts { function copySymbols(source: SymbolTable, meaning: SymbolFlags): void { if (meaning) { - for (let id in source) { - let symbol = source[id]; + for (const id in source) { + const symbol = source[id]; copySymbol(symbol, meaning); } } @@ -14414,18 +14412,18 @@ namespace ts { if (entityName.kind === SyntaxKind.Identifier) { // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. - let meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; + const meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; return resolveEntityName(entityName, meaning); } else if (entityName.kind === SyntaxKind.PropertyAccessExpression) { - let symbol = getNodeLinks(entityName).resolvedSymbol; + const symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } else if (entityName.kind === SyntaxKind.QualifiedName) { - let symbol = getNodeLinks(entityName).resolvedSymbol; + const symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); } @@ -14471,8 +14469,8 @@ namespace ts { else if (node.parent.kind === SyntaxKind.BindingElement && node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && node === (node.parent).propertyName) { - let typeOfPattern = getTypeOfNode(node.parent.parent); - let propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); + const typeOfPattern = getTypeOfNode(node.parent.parent); + const propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); if (propertyDeclaration) { return propertyDeclaration; @@ -14488,12 +14486,12 @@ namespace ts { case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: - let type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case SyntaxKind.ConstructorKeyword: // constructor keyword for an overload, should take us to the definition if it exist - let constructorDeclaration = node.parent; + const constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === SyntaxKind.Constructor) { return (constructorDeclaration.parent).symbol; } @@ -14512,9 +14510,9 @@ namespace ts { case SyntaxKind.NumericLiteral: // index access if (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { - let objectType = checkExpression((node.parent).expression); + const objectType = checkExpression((node.parent).expression); if (objectType === unknownType) return undefined; - let apparentType = getApparentType(objectType); + const apparentType = getApparentType(objectType); if (apparentType === unknownType) return undefined; return getPropertyOfType(apparentType, (node).text); } @@ -14555,23 +14553,23 @@ namespace ts { if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } if (isTypeDeclarationName(node)) { - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); } if (isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } if (isDeclarationName(node)) { - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -14580,8 +14578,8 @@ namespace ts { } if (isInRightSideOfImportOrExportAssignment(node)) { - let symbol = getSymbolAtLocation(node); - let declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + const symbol = getSymbolAtLocation(node); + const declaredType = symbol && getDeclaredTypeOfSymbol(symbol); return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); } @@ -14601,7 +14599,7 @@ namespace ts { * whether the element is declared as "static". */ function getParentTypeOfClassElement(node: ClassElement) { - let classSymbol = getSymbolOfNode(node.parent); + const classSymbol = getSymbolOfNode(node.parent); return node.flags & NodeFlags.Static ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); @@ -14611,7 +14609,7 @@ namespace ts { // if the type has call or construct signatures function getAugmentedPropertiesOfType(type: Type): Symbol[] { type = getApparentType(type); - let propsByName = createSymbolTable(getPropertiesOfType(type)); + const propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, SignatureKind.Call).length || getSignaturesOfType(type, SignatureKind.Construct).length) { forEach(getPropertiesOfType(globalFunctionType), p => { if (!hasProperty(propsByName, p.name)) { @@ -14624,10 +14622,10 @@ namespace ts { function getRootSymbols(symbol: Symbol): Symbol[] { if (symbol.flags & SymbolFlags.SyntheticProperty) { - let symbols: Symbol[] = []; - let name = symbol.name; + const symbols: Symbol[] = []; + const name = symbol.name; forEach(getSymbolLinks(symbol).containingType.types, t => { - let symbol = getPropertyOfType(t, name); + const symbol = getPropertyOfType(t, name); if (symbol) { symbols.push(symbol); } @@ -14635,7 +14633,7 @@ namespace ts { return symbols; } else if (symbol.flags & SymbolFlags.Transient) { - let target = getSymbolLinks(symbol).target; + const target = getSymbolLinks(symbol).target; if (target) { return [target]; } @@ -14658,13 +14656,13 @@ namespace ts { // If we reference an exported entity within the same module declaration, then whether // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. - let exportSymbol = getMergedSymbol(symbol.exportSymbol); + const exportSymbol = getMergedSymbol(symbol.exportSymbol); if (exportSymbol.flags & SymbolFlags.ExportHasLocal) { return undefined; } symbol = exportSymbol; } - let parentSymbol = getParentOfSymbol(symbol); + const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { return parentSymbol.valueDeclaration; @@ -14681,7 +14679,7 @@ namespace ts { // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node: Identifier): Declaration { - let symbol = getReferencedValueSymbol(node); + const symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & SymbolFlags.Alias ? getDeclarationOfAliasSymbol(symbol) : undefined; } @@ -14699,9 +14697,9 @@ namespace ts { function isNestedRedeclarationSymbol(symbol: Symbol): boolean { if (symbol.flags & SymbolFlags.BlockScoped) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (links.isNestedRedeclaration === undefined) { - let container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); links.isNestedRedeclaration = isStatementWithLocals(container) && !!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); } @@ -14713,7 +14711,7 @@ namespace ts { // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. function getReferencedNestedRedeclaration(node: Identifier): Declaration { - let symbol = getReferencedValueSymbol(node); + const symbol = getReferencedValueSymbol(node); return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; } @@ -14732,7 +14730,7 @@ namespace ts { case SyntaxKind.ExportSpecifier: return isAliasResolvedToValue(getSymbolOfNode(node)); case SyntaxKind.ExportDeclaration: - let exportClause = (node).exportClause; + const exportClause = (node).exportClause; return exportClause && forEach(exportClause.elements, isValueAliasDeclaration); case SyntaxKind.ExportAssignment: return (node).expression && (node).expression.kind === SyntaxKind.Identifier ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; @@ -14746,12 +14744,12 @@ namespace ts { return false; } - let isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + const isValue = isAliasResolvedToValue(getSymbolOfNode(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol: Symbol): boolean { - let target = resolveAlias(symbol); + const target = resolveAlias(symbol); if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } @@ -14769,7 +14767,7 @@ namespace ts { function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean { if (isAliasSymbolDeclaration(node)) { - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); if (getSymbolLinks(symbol).referenced) { return true; } @@ -14783,8 +14781,8 @@ namespace ts { function isImplementationOfOverload(node: FunctionLikeDeclaration) { if (nodeIsPresent(node.body)) { - let symbol = getSymbolOfNode(node); - let signaturesOfSymbol = getSignaturesOfSymbol(symbol); + const symbol = getSymbolOfNode(node); + const signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload // e.g.: function foo(a: string): string; // function foo(a: number): number; @@ -14816,7 +14814,7 @@ namespace ts { return getEnumMemberValue(node); } - let symbol = getNodeLinks(node).resolvedSymbol; + const symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & SymbolFlags.EnumMember)) { // inline property\index accesses only for const enums if (isConstEnumDeclaration(symbol.valueDeclaration.parent)) { @@ -14833,19 +14831,19 @@ namespace ts { function getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - let valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true); - let constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; + const valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true); + const constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - let typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true); + const typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return TypeReferenceSerializationKind.ObjectType; } - let type = getDeclaredTypeOfSymbol(typeSymbol); + const type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { return TypeReferenceSerializationKind.Unknown; } @@ -14883,8 +14881,8 @@ namespace ts { function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { // Get type of the symbol if this is the valid symbol otherwise get type at location - let symbol = getSymbolOfNode(declaration); - let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) + const symbol = getSymbolOfNode(declaration); + const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) ? getTypeOfSymbol(symbol) : unknownType; @@ -14892,12 +14890,12 @@ namespace ts { } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - let signature = getSignatureFromDeclaration(signatureDeclaration); + const signature = getSignatureFromDeclaration(signatureDeclaration); getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - let type = getTypeOfExpression(expr); + const type = getTypeOfExpression(expr); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -14913,7 +14911,7 @@ namespace ts { function getReferencedValueDeclaration(reference: Identifier): Declaration { Debug.assert(!nodeIsSynthesized(reference)); - let symbol = getReferencedValueSymbol(reference); + const symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } @@ -14922,12 +14920,12 @@ namespace ts { return unknownType; } - let signature = getSingleCallSignature(functionType); + const signature = getSingleCallSignature(functionType); if (!signature) { return unknownType; } - let instantiatedSignature = getSignatureInstantiation(signature, typeArguments); + const instantiatedSignature = getSignatureInstantiation(signature, typeArguments); return getOrCreateTypeFromSignature(instantiatedSignature); } @@ -15025,7 +15023,7 @@ namespace ts { } function createInstantiatedPromiseLikeType(): ObjectType { - let promiseLikeType = getGlobalPromiseLikeType(); + const promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { return createTypeReference(promiseLikeType, [anyType]); } @@ -15035,10 +15033,10 @@ namespace ts { function createThenableType() { // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. - let thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); + const thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - let thenableType = createObjectType(TypeFlags.Anonymous); + const thenableType = createObjectType(TypeFlags.Anonymous); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -15055,7 +15053,7 @@ namespace ts { return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); } else if (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor) { - let accessors = getAllAccessorDeclarations((node.parent).members, node); + const accessors = getAllAccessorDeclarations((node.parent).members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } @@ -15110,7 +15108,7 @@ namespace ts { let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node, lastAsync: Node; let flags = 0; - for (let modifier of node.modifiers) { + for (const modifier of node.modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: @@ -15301,9 +15299,9 @@ namespace ts { function checkGrammarForDisallowedTrailingComma(list: NodeArray): boolean { if (list && list.hasTrailingComma) { - let start = list.end - ",".length; - let end = list.end; - let sourceFile = getSourceFileOfNode(list[0]); + const start = list.end - ",".length; + const end = list.end; + const sourceFile = getSourceFileOfNode(list[0]); return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Trailing_comma_not_allowed); } } @@ -15314,8 +15312,8 @@ namespace ts { } if (typeParameters && typeParameters.length === 0) { - let start = typeParameters.pos - "<".length; - let end = skipTrivia(file.text, typeParameters.end) + ">".length; + const start = typeParameters.pos - "<".length; + const end = skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty); } } @@ -15326,10 +15324,10 @@ namespace ts { } let seenOptionalParameter = false; - let parameterCount = parameters.length; + const parameterCount = parameters.length; for (let i = 0; i < parameterCount; i++) { - let parameter = parameters[i]; + const parameter = parameters[i]; if (parameter.dotDotDotToken) { if (i !== (parameterCount - 1)) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); @@ -15362,16 +15360,16 @@ namespace ts { function checkGrammarFunctionLikeDeclaration(node: FunctionLikeDeclaration): boolean { // Prevent cascading error by short-circuit - let file = getSourceFileOfNode(node); + const file = getSourceFileOfNode(node); return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node: FunctionLikeDeclaration, file: SourceFile): boolean { if (node.kind === SyntaxKind.ArrowFunction) { - let arrowFunction = node; - let startLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - let endLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + const arrowFunction = node; + const startLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + const endLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; if (startLine !== endLine) { return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow); } @@ -15380,7 +15378,7 @@ namespace ts { } function checkGrammarIndexSignatureParameters(node: SignatureDeclaration): boolean { - let parameter = node.parameters[0]; + const parameter = node.parameters[0]; if (node.parameters.length !== 1) { if (parameter) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter); @@ -15425,9 +15423,9 @@ namespace ts { function checkGrammarForAtLeastOneTypeArgument(node: Node, typeArguments: NodeArray): boolean { if (typeArguments && typeArguments.length === 0) { - let sourceFile = getSourceFileOfNode(node); - let start = typeArguments.pos - "<".length; - let end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + const sourceFile = getSourceFileOfNode(node); + const start = typeArguments.pos - "<".length; + const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); } } @@ -15439,8 +15437,8 @@ namespace ts { function checkGrammarForOmittedArgument(node: CallExpression, args: NodeArray): boolean { if (args) { - let sourceFile = getSourceFileOfNode(node); - for (let arg of args) { + const sourceFile = getSourceFileOfNode(node); + for (const arg of args) { if (arg.kind === SyntaxKind.OmittedExpression) { return grammarErrorAtPos(sourceFile, arg.pos, 0, Diagnostics.Argument_expression_expected); } @@ -15454,13 +15452,13 @@ namespace ts { } function checkGrammarHeritageClause(node: HeritageClause): boolean { - let types = node.types; + const types = node.types; if (checkGrammarForDisallowedTrailingComma(types)) { return true; } if (types && types.length === 0) { - let listType = tokenToString(node.token); - let sourceFile = getSourceFileOfNode(node); + const listType = tokenToString(node.token); + const sourceFile = getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType); } } @@ -15470,7 +15468,7 @@ namespace ts { let seenImplementsClause = false; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (let heritageClause of node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); @@ -15505,7 +15503,7 @@ namespace ts { let seenExtendsClause = false; if (node.heritageClauses) { - for (let heritageClause of node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); @@ -15532,7 +15530,7 @@ namespace ts { return false; } - let computedPropertyName = node; + const computedPropertyName = node; if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && (computedPropertyName.expression).operatorToken.kind === SyntaxKind.CommaToken) { return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } @@ -15563,14 +15561,14 @@ namespace ts { } function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) { - let seen: Map = {}; - let Property = 1; - let GetAccessor = 2; - let SetAccesor = 4; - let GetOrSetAccessor = GetAccessor | SetAccesor; + const seen: Map = {}; + const Property = 1; + const GetAccessor = 2; + const SetAccesor = 4; + const GetOrSetAccessor = GetAccessor | SetAccesor; - for (let prop of node.properties) { - let name = prop.name; + for (const prop of node.properties) { + const name = prop.name; if (prop.kind === SyntaxKind.OmittedExpression || name.kind === SyntaxKind.ComputedPropertyName) { // If the name is not a ComputedPropertyName, the grammar checking will skip it @@ -15618,7 +15616,7 @@ namespace ts { seen[(name).text] = currentKind; } else { - let existingKind = seen[(name).text]; + const existingKind = seen[(name).text]; if (currentKind === Property && existingKind === Property) { continue; } @@ -15639,13 +15637,13 @@ namespace ts { function checkGrammarJsxElement(node: JsxOpeningLikeElement) { const seen: Map = {}; - for (let attr of node.attributes) { + for (const attr of node.attributes) { if (attr.kind === SyntaxKind.JsxSpreadAttribute) { continue; } - let jsxAttr = (attr); - let name = jsxAttr.name; + const jsxAttr = (attr); + const name = jsxAttr.name; if (!hasProperty(seen, name.text)) { seen[name.text] = true; } @@ -15653,7 +15651,7 @@ namespace ts { return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - let initializer = jsxAttr.initializer; + const initializer = jsxAttr.initializer; if (initializer && initializer.kind === SyntaxKind.JsxExpression && !(initializer).expression) { return grammarErrorOnNode(jsxAttr.initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } @@ -15666,23 +15664,23 @@ namespace ts { } if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableList = forInOrOfStatement.initializer; + const variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - let firstDeclaration = variableList.declarations[0]; + const firstDeclaration = variableList.declarations[0]; if (firstDeclaration.initializer) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -15694,7 +15692,7 @@ namespace ts { } function checkGrammarAccessor(accessor: MethodDeclaration): boolean { - let kind = accessor.kind; + const kind = accessor.kind; if (languageVersion < ScriptTarget.ES5) { return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } @@ -15718,7 +15716,7 @@ namespace ts { return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } else { - let parameter = accessor.parameters[0]; + const parameter = accessor.parameters[0]; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter); } @@ -15793,7 +15791,7 @@ namespace ts { if (node.label && (current).label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - let isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement + const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement && !isIterationStatement((current).statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { @@ -15821,14 +15819,14 @@ namespace ts { } if (node.label) { - let message = node.kind === SyntaxKind.BreakStatement + const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - let message = node.kind === SyntaxKind.BreakStatement + const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -15837,7 +15835,7 @@ namespace ts { function checkGrammarBindingElement(node: BindingElement) { if (node.dotDotDotToken) { - let elements = (node.parent).elements; + const elements = (node.parent).elements; if (node !== lastOrUndefined(elements)) { return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } @@ -15858,7 +15856,7 @@ namespace ts { if (isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer - let equalsTokenLength = "=".length; + const equalsTokenLength = "=".length; return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -15873,7 +15871,7 @@ namespace ts { } } - let checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); + const checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -15892,8 +15890,8 @@ namespace ts { } } else { - let elements = (name).elements; - for (let element of elements) { + const elements = (name).elements; + for (const element of elements) { if (element.kind !== SyntaxKind.OmittedExpression) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -15902,7 +15900,7 @@ namespace ts { } function checkGrammarVariableDeclarationList(declarationList: VariableDeclarationList): boolean { - let declarations = declarationList.declarations; + const declarations = declarationList.declarations; if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { return true; } @@ -15942,7 +15940,7 @@ namespace ts { function isIntegerLiteral(expression: Expression): boolean { if (expression.kind === SyntaxKind.PrefixUnaryExpression) { - let unaryExpression = expression; + const unaryExpression = expression; if (unaryExpression.operator === SyntaxKind.PlusToken || unaryExpression.operator === SyntaxKind.MinusToken) { expression = unaryExpression.operand; } @@ -15964,9 +15962,9 @@ namespace ts { } function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - let span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } @@ -15980,7 +15978,7 @@ namespace ts { } function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; @@ -16056,7 +16054,7 @@ namespace ts { } function checkGrammarTopLevelElementsForRequiredDeclareModifier(file: SourceFile): boolean { - for (let decl of file.statements) { + for (const decl of file.statements) { if (isDeclaration(decl) || decl.kind === SyntaxKind.VariableStatement) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; @@ -16077,7 +16075,7 @@ namespace ts { } // Find containing block which is either Block, ModuleBlock, SourceFile - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.hasReportedStatementInAmbientContext && isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } @@ -16088,7 +16086,7 @@ namespace ts { // this has already been reported, and don't report if it has. // if (node.parent.kind === SyntaxKind.Block || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - let links = getNodeLinks(node.parent); + const links = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links.hasReportedStatementInAmbientContext) { return links.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -16110,9 +16108,9 @@ namespace ts { } function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - let span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index f4de5c430ac..3fca97c0450 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -295,8 +295,8 @@ namespace ts { return optionNameMapCache; } - let optionNameMap: Map = {}; - let shortOptionNames: Map = {}; + const optionNameMap: Map = {}; + const shortOptionNames: Map = {}; forEach(optionDeclarations, option => { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -309,10 +309,10 @@ namespace ts { } export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine { - let options: CompilerOptions = {}; - let fileNames: string[] = []; - let errors: Diagnostic[] = []; - let { optionNameMap, shortOptionNames } = getOptionNameMap(); + const options: CompilerOptions = {}; + const fileNames: string[] = []; + const errors: Diagnostic[] = []; + const { optionNameMap, shortOptionNames } = getOptionNameMap(); parseStrings(commandLine); return { @@ -337,7 +337,7 @@ namespace ts { } if (hasProperty(optionNameMap, s)) { - let opt = optionNameMap[s]; + const opt = optionNameMap[s]; // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { @@ -377,19 +377,19 @@ namespace ts { } function parseResponseFile(fileName: string) { - let text = readFile ? readFile(fileName) : sys.readFile(fileName); + const text = readFile ? readFile(fileName) : sys.readFile(fileName); if (!text) { errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName)); return; } - let args: string[] = []; + const args: string[] = []; let pos = 0; while (true) { while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++; if (pos >= text.length) break; - let start = pos; + const start = pos; if (text.charCodeAt(start) === CharacterCodes.doubleQuote) { pos++; while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++; @@ -432,7 +432,7 @@ namespace ts { */ export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic } { try { - let jsonTextWithoutComments = removeComments(jsonText); + const jsonTextWithoutComments = removeComments(jsonText); return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { @@ -449,7 +449,7 @@ namespace ts { */ function removeComments(jsonText: string): string { let output = ""; - let scanner = createScanner(ScriptTarget.ES5, /* skipTrivia */ false, LanguageVariant.Standard, jsonText); + const scanner = createScanner(ScriptTarget.ES5, /* skipTrivia */ false, LanguageVariant.Standard, jsonText); let token: SyntaxKind; while ((token = scanner.scan()) !== SyntaxKind.EndOfFileToken) { switch (token) { @@ -475,7 +475,7 @@ namespace ts { * file to. e.g. outDir */ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine { - let { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath); + const { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath); return { options, @@ -494,12 +494,12 @@ namespace ts { } } else { - let exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; - let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); + const exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; + const sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude)); for (let i = 0; i < sysFiles.length; i++) { - let name = sysFiles[i]; + const name = sysFiles[i]; if (fileExtensionIs(name, ".d.ts")) { - let baseName = name.substr(0, name.length - ".d.ts".length); + const baseName = name.substr(0, name.length - ".d.ts".length); if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) { fileNames.push(name); } @@ -519,24 +519,24 @@ namespace ts { } export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions, errors: Diagnostic[] } { - let options: CompilerOptions = {}; - let errors: Diagnostic[] = []; + const options: CompilerOptions = {}; + const errors: Diagnostic[] = []; if (!jsonOptions) { return { options, errors }; } - let optionNameMap = arrayToMap(optionDeclarations, opt => opt.name); + const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name); - for (let id in jsonOptions) { + for (const id in jsonOptions) { if (hasProperty(optionNameMap, id)) { - let opt = optionNameMap[id]; - let optType = opt.type; + const opt = optionNameMap[id]; + const optType = opt.type; let value = jsonOptions[id]; - let expectedType = typeof optType === "string" ? optType : "string"; + const expectedType = typeof optType === "string" ? optType : "string"; if (typeof value === expectedType) { if (typeof optType !== "string") { - let key = value.toLowerCase(); + const key = value.toLowerCase(); if (hasProperty(optType, key)) { value = optType[key]; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 068ab1865bb..5c882fb5304 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -29,7 +29,7 @@ namespace ts { }; function forEachValueInMap(f: (key: Path, value: T) => void) { - for (let key in files) { + for (const key in files) { f(key, files[key]); } } @@ -84,7 +84,7 @@ namespace ts { export function forEach(array: T[], callback: (element: T, index: number) => U): U { if (array) { for (let i = 0, len = array.length; i < len; i++) { - let result = callback(array[i], i); + const result = callback(array[i], i); if (result) { return result; } @@ -95,7 +95,7 @@ namespace ts { export function contains(array: T[], value: T): boolean { if (array) { - for (let v of array) { + for (const v of array) { if (v === value) { return true; } @@ -118,7 +118,7 @@ namespace ts { export function countWhere(array: T[], predicate: (x: T) => boolean): number { let count = 0; if (array) { - for (let v of array) { + for (const v of array) { if (predicate(v)) { count++; } @@ -131,7 +131,7 @@ namespace ts { let result: T[]; if (array) { result = []; - for (let item of array) { + for (const item of array) { if (f(item)) { result.push(item); } @@ -144,7 +144,7 @@ namespace ts { let result: U[]; if (array) { result = []; - for (let v of array) { + for (const v of array) { result.push(f(v)); } } @@ -162,7 +162,7 @@ namespace ts { let result: T[]; if (array) { result = []; - for (let item of array) { + for (const item of array) { if (!contains(result, item)) { result.push(item); } @@ -173,7 +173,7 @@ namespace ts { export function sum(array: any[], prop: string): number { let result = 0; - for (let v of array) { + for (const v of array) { result += v[prop]; } return result; @@ -181,7 +181,7 @@ namespace ts { export function addRange(to: T[], from: T[]): void { if (to && from) { - for (let v of from) { + for (const v of from) { to.push(v); } } @@ -220,8 +220,8 @@ namespace ts { let high = array.length - 1; while (low <= high) { - let middle = low + ((high - low) >> 1); - let midValue = array[middle]; + const middle = low + ((high - low) >> 1); + const midValue = array[middle]; if (midValue === value) { return middle; @@ -270,7 +270,7 @@ namespace ts { return initial; } - let hasOwnProperty = Object.prototype.hasOwnProperty; + const hasOwnProperty = Object.prototype.hasOwnProperty; export function hasProperty(map: Map, key: string): boolean { return hasOwnProperty.call(map, key); @@ -281,7 +281,7 @@ namespace ts { } export function isEmpty(map: Map) { - for (let id in map) { + for (const id in map) { if (hasProperty(map, id)) { return false; } @@ -290,19 +290,19 @@ namespace ts { } export function clone(object: T): T { - let result: any = {}; - for (let id in object) { + const result: any = {}; + for (const id in object) { result[id] = (object)[id]; } return result; } export function extend(first: Map, second: Map): Map { - let result: Map = {}; - for (let id in first) { + const result: Map = {}; + for (const id in first) { (result as any)[id] = first[id]; } - for (let id in second) { + for (const id in second) { if (!hasProperty(result, id)) { (result as any)[id] = second[id]; } @@ -312,7 +312,7 @@ namespace ts { export function forEachValue(map: Map, callback: (value: T) => U): U { let result: U; - for (let id in map) { + for (const id in map) { if (result = callback(map[id])) break; } return result; @@ -320,7 +320,7 @@ namespace ts { export function forEachKey(map: Map, callback: (key: string) => U): U { let result: U; - for (let id in map) { + for (const id in map) { if (result = callback(id)) break; } return result; @@ -331,7 +331,7 @@ namespace ts { } export function copyMap(source: Map, target: Map): void { - for (let p in source) { + for (const p in source) { target[p] = source[p]; } } @@ -347,7 +347,7 @@ namespace ts { * index in the array will be the one associated with the produced key. */ export function arrayToMap(array: T[], makeKey: (value: T) => string): Map { - let result: Map = {}; + const result: Map = {}; forEach(array, value => { result[makeKey(value)] = value; @@ -383,7 +383,7 @@ namespace ts { export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic { - let end = start + length; + const end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); @@ -479,10 +479,10 @@ namespace ts { function compareMessageText(text1: string | DiagnosticMessageChain, text2: string | DiagnosticMessageChain): Comparison { while (text1 && text2) { // We still have both chains. - let string1 = typeof text1 === "string" ? text1 : text1.messageText; - let string2 = typeof text2 === "string" ? text2 : text2.messageText; + const string1 = typeof text1 === "string" ? text1 : text1.messageText; + const string2 = typeof text2 === "string" ? text2 : text2.messageText; - let res = compareValues(string1, string2); + const res = compareValues(string1, string2); if (res) { return res; } @@ -509,11 +509,11 @@ namespace ts { return diagnostics; } - let newDiagnostics = [diagnostics[0]]; + const newDiagnostics = [diagnostics[0]]; let previousDiagnostic = diagnostics[0]; for (let i = 1; i < diagnostics.length; i++) { - let currentDiagnostic = diagnostics[i]; - let isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo; + const currentDiagnostic = diagnostics[i]; + const isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo; if (!isDupe) { newDiagnostics.push(currentDiagnostic); previousDiagnostic = currentDiagnostic; @@ -531,9 +531,9 @@ namespace ts { export function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1; - let p1 = path.indexOf("/", 2); + const p1 = path.indexOf("/", 2); if (p1 < 0) return 2; - let p2 = path.indexOf("/", p1 + 1); + const p2 = path.indexOf("/", p1 + 1); if (p2 < 0) return p1 + 1; return p2 + 1; } @@ -549,7 +549,7 @@ namespace ts { if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; } - let idx = path.indexOf("://"); + const idx = path.indexOf("://"); if (idx !== -1) { return idx + "://".length; } @@ -558,9 +558,9 @@ namespace ts { export let directorySeparator = "/"; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { - let parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); - let normalized: string[] = []; - for (let part of parts) { + const parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); + const normalized: string[] = []; + for (const part of parts) { if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -580,8 +580,8 @@ namespace ts { export function normalizePath(path: string): string { path = normalizeSlashes(path); - let rootLength = getRootLength(path); - let normalized = getNormalizedParts(path, rootLength); + const rootLength = getRootLength(path); + const normalized = getNormalizedParts(path, rootLength); return path.substr(0, rootLength) + normalized.join(directorySeparator); } @@ -598,7 +598,7 @@ namespace ts { } function normalizedPathComponents(path: string, rootLength: number) { - let normalizedParts = getNormalizedParts(path, rootLength); + const normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); } @@ -629,7 +629,7 @@ namespace ts { // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - let urlLength = url.length; + const urlLength = url.length; // Initial root length is http:// part let rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { @@ -650,7 +650,7 @@ namespace ts { } // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - let indexOfNextSlash = url.indexOf(directorySeparator, rootLength); + const indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ // and get components afetr the root normally like any other folder components @@ -676,8 +676,8 @@ namespace ts { } export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) { - let pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - let directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); + const pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); + const directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] @@ -694,7 +694,7 @@ namespace ts { // Get the relative path if (joinStartIndex) { let relativePath = ""; - let relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); + const relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== "") { relativePath = relativePath + ".." + directorySeparator; @@ -717,7 +717,7 @@ namespace ts { if (!path) { return undefined; } - let i = path.lastIndexOf(directorySeparator); + const i = path.lastIndexOf(directorySeparator); return i < 0 ? path : path.substring(i + 1); } @@ -730,8 +730,8 @@ namespace ts { } export function fileExtensionIs(path: string, extension: string): boolean { - let pathLen = path.length; - let extLen = extension.length; + const pathLen = path.length; + const extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } @@ -749,7 +749,7 @@ namespace ts { export function isSupportedSourceFileName(fileName: string) { if (!fileName) { return false; } - for (let extension of supportedExtensions) { + for (const extension of supportedExtensions) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -759,7 +759,7 @@ namespace ts { const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; export function removeFileExtension(path: string): string { - for (let ext of extensionsToRemove) { + for (const ext of extensionsToRemove) { if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -767,9 +767,9 @@ namespace ts { return path; } - let backslashOrDoubleQuote = /[\"\\]/g; - let escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - let escapedCharsMap: Map = { + const backslashOrDoubleQuote = /[\"\\]/g; + const escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + const escapedCharsMap: Map = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -828,7 +828,7 @@ namespace ts { } export namespace Debug { - let currentAssertionLevel = AssertionLevel.None; + const currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { return currentAssertionLevel >= level; @@ -851,8 +851,8 @@ namespace ts { } export function copyListRemovingItem(item: T, list: T[]) { - let copiedList: T[] = []; - for (let e of list) { + const copiedList: T[] = []; + for (const e of list) { if (e !== item) { copiedList.push(e); } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 719085f7f6a..ac91a39a78b 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -31,15 +31,15 @@ namespace ts { } export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { - let diagnostics: Diagnostic[] = []; - let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); + const diagnostics: Diagnostic[] = []; + const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile); return diagnostics; } function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit { - let newLine = host.getNewLine(); - let compilerOptions = host.getCompilerOptions(); + const newLine = host.getNewLine(); + const compilerOptions = host.getCompilerOptions(); let write: (s: string) => void; let writeLine: () => void; @@ -53,10 +53,10 @@ namespace ts { let currentSourceFile: SourceFile; let reportedDeclarationError = false; let errorNameNode: DeclarationName; - let emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; - let emit = compilerOptions.stripInternal ? stripInternal : emitNode; + const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; + const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; + const moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; // Contains the reference paths that needs to go in the declaration file. @@ -69,7 +69,7 @@ namespace ts { if (!compilerOptions.noResolve) { let addedGlobalFileReference = false; forEach(root.referencedFiles, fileReference => { - let referencedFile = tryResolveScriptReference(host, root, fileReference); + const 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 @@ -88,7 +88,7 @@ namespace ts { // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { - let oldWriter = writer; + const oldWriter = writer; forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => { if (aliasEmitInfo.isVisible) { Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration); @@ -103,13 +103,13 @@ namespace ts { } else { // Emit references corresponding to this file - let emittedReferencedFiles: SourceFile[] = []; + const emittedReferencedFiles: SourceFile[] = []; forEach(host.getSourceFiles(), sourceFile => { if (!isExternalModuleOrDeclarationFile(sourceFile)) { // Check what references need to be added if (!compilerOptions.noResolve) { forEach(sourceFile.referencedFiles, fileReference => { - let referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); + const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); // If the reference file is a declaration file or an external module, emit that reference if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) && @@ -134,14 +134,14 @@ namespace ts { }; function hasInternalAnnotation(range: CommentRange) { - let text = currentSourceFile.text; - let comment = text.substring(range.pos, range.end); + const text = currentSourceFile.text; + const comment = text.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node: Node) { if (node) { - let leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); + const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -151,7 +151,7 @@ namespace ts { } function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter { - let writer = createTextWriter(newLine); + const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; writer.writeKeyword = writer.write; @@ -175,7 +175,7 @@ namespace ts { } function writeAsynchronousModuleElements(nodes: Node[]) { - let oldWriter = writer; + const oldWriter = writer; forEach(nodes, declaration => { let nodeToCheck: Node; if (declaration.kind === SyntaxKind.VariableDeclaration) { @@ -238,7 +238,7 @@ namespace ts { else { // Report error reportedDeclarationError = true; - let errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, @@ -297,14 +297,14 @@ namespace ts { } function emitLines(nodes: Node[]) { - for (let node of nodes) { + for (const node of nodes) { emit(node); } } function emitSeparatedList(nodes: Node[], separator: string, eachNodeEmitFn: (node: Node) => void, canEmitFn?: (node: Node) => boolean) { let currentWriterPos = writer.getTextPos(); - for (let node of nodes) { + for (const node of nodes) { if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -321,7 +321,7 @@ namespace ts { function writeJsDocComments(declaration: Node) { if (declaration) { - let jsDocComments = getJsDocComments(declaration, currentSourceFile); + const jsDocComments = getJsDocComments(declaration, currentSourceFile); emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange); @@ -378,8 +378,8 @@ namespace ts { writeTextOfNode(currentSourceFile, entityName); } else { - let left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; - let right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; + const left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; + const right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -387,7 +387,7 @@ namespace ts { } function emitEntityName(entityName: EntityName | PropertyAccessExpression) { - let visibilityResult = resolver.isEntityNameVisible(entityName, + const visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration); @@ -477,13 +477,13 @@ namespace ts { // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. function getExportDefaultTempVariableName(): string { - let baseName = "_default"; + const baseName = "_default"; if (!hasProperty(currentSourceFile.identifiers, baseName)) { return baseName; } let count = 0; while (true) { - let name = baseName + "_" + (++count); + const name = baseName + "_" + (++count); if (!hasProperty(currentSourceFile.identifiers, name)) { return name; } @@ -497,7 +497,7 @@ namespace ts { } else { // Expression - let tempVarName = getExportDefaultTempVariableName(); + const tempVarName = getExportDefaultTempVariableName(); write("declare var "); write(tempVarName); write(": "); @@ -513,7 +513,7 @@ namespace ts { // Make all the declarations visible for the export name if (node.expression.kind === SyntaxKind.Identifier) { - let nodes = resolver.collectLinkedAliases(node.expression); + const nodes = resolver.collectLinkedAliases(node.expression); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); @@ -550,7 +550,7 @@ namespace ts { } else { if (node.kind === SyntaxKind.ImportDeclaration) { - let importDeclaration = node; + const importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || isVisibleNamedBinding(importDeclaration.importClause.namedBindings); @@ -676,7 +676,7 @@ namespace ts { } write("import "); if (node.importClause) { - let currentWriterPos = writer.getTextPos(); + const currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { writeTextOfNode(currentSourceFile, node.importClause.name); } @@ -714,7 +714,7 @@ namespace ts { emitImportOrExportSpecifier(node); // Make all the declarations visible for the export name - let nodes = resolver.collectLinkedAliases(node.propertyName || node.name); + const nodes = resolver.collectLinkedAliases(node.propertyName || node.name); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); @@ -754,7 +754,7 @@ namespace ts { write("."); writeTextOfNode(currentSourceFile, node.name); } - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; write(" {"); writeLine(); @@ -767,7 +767,7 @@ namespace ts { } function writeTypeAliasDeclaration(node: TypeAliasDeclaration) { - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -809,7 +809,7 @@ namespace ts { function emitEnumMemberDeclaration(node: EnumMember) { emitJsDocComments(node); writeTextOfNode(currentSourceFile, node.name); - let enumMemberValue = resolver.getConstantValue(node); + const enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); write(enumMemberValue.toString()); @@ -959,10 +959,10 @@ namespace ts { write("class "); writeTextOfNode(currentSourceFile, node.name); - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } @@ -983,7 +983,7 @@ namespace ts { emitModuleElementDeclarationFlags(node); write("interface "); writeTextOfNode(currentSourceFile, node.name); - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); @@ -1069,7 +1069,7 @@ namespace ts { } function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1083,8 +1083,8 @@ namespace ts { // For example: // original: var [, c,,] = [ 2,3,4] // emitted: declare var c: number; // instead of declare var c:number, ; - let elements: Node[] = []; - for (let element of bindingPattern.elements) { + const elements: Node[] = []; + for (const element of bindingPattern.elements) { if (element.kind !== SyntaxKind.OmittedExpression) { elements.push(element); } @@ -1094,7 +1094,7 @@ namespace ts { function emitBindingElement(bindingElement: BindingElement) { function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1150,7 +1150,7 @@ namespace ts { return; } - let accessors = getAllAccessorDeclarations((node.parent).members, node); + const accessors = getAllAccessorDeclarations((node.parent).members, node); let accessorWithTypeAnnotation: AccessorDeclaration; if (node === accessors.firstAccessor) { @@ -1163,7 +1163,7 @@ namespace ts { let type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - let anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; + const anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -1280,7 +1280,7 @@ namespace ts { write("("); } - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; // Parameters @@ -1294,7 +1294,7 @@ namespace ts { } // If this is not a constructor and is not private, emit the return type - let isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; + const isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; if (isFunctionTypeOrConstructorType || node.parent.kind === SyntaxKind.TypeLiteral) { // Emit type literal signature return type only if specified if (node.type) { @@ -1410,7 +1410,7 @@ namespace ts { } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1483,7 +1483,7 @@ namespace ts { } else if (bindingPattern.kind === SyntaxKind.ArrayBindingPattern) { write("["); - let elements = bindingPattern.elements; + const elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); if (elements && elements.hasTrailingComma) { write(", "); @@ -1494,7 +1494,7 @@ namespace ts { function emitBindingElement(bindingElement: BindingElement) { function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1609,11 +1609,11 @@ namespace ts { /* @internal */ export function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile, host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[]) { - let emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile); + const 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) { - let declarationOutput = emitDeclarationResult.referencePathsOutput + const declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); writeFile(host, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, host.getCompilerOptions().emitBOM); } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index f44911a3189..057be9e0b96 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -15,7 +15,7 @@ namespace ts { Return = 1 << 3 } - let entities: Map = { + const entities: Map = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -324,19 +324,19 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi }); };`; - let compilerOptions = host.getCompilerOptions(); - let languageVersion = compilerOptions.target || ScriptTarget.ES3; - let modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; - let sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + const compilerOptions = host.getCompilerOptions(); + const languageVersion = compilerOptions.target || ScriptTarget.ES3; + const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; let diagnostics: Diagnostic[] = []; - let newLine = host.getNewLine(); - let jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve; - let shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring); + const newLine = host.getNewLine(); + const jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve; + const shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring); if (targetSourceFile === undefined) { forEach(host.getSourceFiles(), sourceFile => { if (shouldEmitToOwnFile(sourceFile, compilerOptions)) { - let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); + const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js"); emitFile(jsFilePath, sourceFile); } }); @@ -348,7 +348,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); + const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js"); emitFile(jsFilePath, targetSourceFile); } else if (!isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) { @@ -471,8 +471,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitJavaScript(jsFilePath: string, root?: SourceFile) { - let writer = createTextWriter(newLine); - let { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer; + const writer = createTextWriter(newLine); + const { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer; let currentSourceFile: SourceFile; // name of an exporter function if file is a System external module @@ -483,8 +483,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // var x;... exporter("x", x = 1) let exportFunctionForFile: string; - let generatedNameSet: Map = {}; - let nodeToGeneratedName: string[] = []; + const generatedNameSet: Map = {}; + const nodeToGeneratedName: string[] = []; let computedPropertyNamesToGeneratedNames: string[]; let convertedLoopState: ConvertedLoopState; @@ -537,9 +537,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapData: SourceMapData; /** If removeComments is true, no leading-comments needed to be emitted **/ - let emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker; + const emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker; - let moduleEmitDelegates: Map<(node: SourceFile) => void> = { + const moduleEmitDelegates: Map<(node: SourceFile) => void> = { [ModuleKind.ES6]: emitES6Module, [ModuleKind.AMD]: emitAMDModule, [ModuleKind.System]: emitSystemModule, @@ -584,18 +584,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName(flags: TempFlags): string { if (flags && !(tempFlags & flags)) { - let name = flags === TempFlags._i ? "_i" : "_n"; + const name = flags === TempFlags._i ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; return name; } } while (true) { - let count = tempFlags & TempFlags.CountMask; + const count = tempFlags & TempFlags.CountMask; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - let name = count < 26 ? "_" + String.fromCharCode(CharacterCodes.a + count) : "_" + (count - 26); + const name = count < 26 ? "_" + String.fromCharCode(CharacterCodes.a + count) : "_" + (count - 26); if (isUniqueName(name)) { return name; } @@ -614,7 +614,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } let i = 1; while (true) { - let generatedName = baseName + i; + const generatedName = baseName + i; if (isUniqueName(generatedName)) { return generatedNameSet[generatedName] = generatedName; } @@ -623,14 +623,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function generateNameForModuleOrEnum(node: ModuleDeclaration | EnumDeclaration) { - let name = node.name.text; + const name = node.name.text; // Use module/enum name itself if it is unique, otherwise make a unique variation return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) { - let expr = getExternalModuleName(node); - let baseName = expr.kind === SyntaxKind.StringLiteral ? + const expr = getExternalModuleName(node); + const baseName = expr.kind === SyntaxKind.StringLiteral ? escapeIdentifier(makeIdentifierFromModuleName((expr).text)) : "module"; return makeUniqueName(baseName); } @@ -663,7 +663,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getGeneratedNameForNode(node: Node) { - let id = getNodeId(node); + const id = getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = unescapeIdentifier(generateNameForNode(node))); } @@ -674,8 +674,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapSourceIndex = -1; // Names and its index map - let sourceMapNameIndexMap: Map = {}; - let sourceMapNameIndices: number[] = []; + const sourceMapNameIndexMap: Map = {}; + const sourceMapNameIndices: number[] = []; function getSourceMapNameIndex() { return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1; } @@ -771,14 +771,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function recordSourceMapSpan(pos: number) { - let sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); + const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; - let emittedLine = writer.getLine(); - let emittedColumn = writer.getColumn(); + const emittedLine = writer.getLine(); + const emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || @@ -818,9 +818,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeTextWithSpanRecord(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - let tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + const tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); recordSourceMapSpan(tokenStartPos); - let tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + const tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); recordSourceMapSpan(tokenEndPos); return tokenEndPos; } @@ -829,7 +829,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // 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 - let sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, @@ -857,12 +857,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function recordScopeNameStart(scopeName: string) { let scopeNameIndex = -1; if (scopeName) { - let parentIndex = getSourceMapNameIndex(); + const parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { // Child scopes are always shown with a dot (even if they have no name), // unless it is a computed property. Then it is shown with brackets, // but the brackets are included in the name. - let name = (node).name; + const name = (node).name; if (!name || name.kind !== SyntaxKind.ComputedPropertyName) { scopeName = "." + scopeName; } @@ -894,7 +894,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi node.kind === SyntaxKind.EnumDeclaration) { // Declaration and has associated name use it if ((node).name) { - let name = (node).name; + const name = (node).name; // For computed property names, the text will include the brackets scopeName = name.kind === SyntaxKind.ComputedPropertyName ? getTextOfNode(name) @@ -920,7 +920,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function serializeSourceMapContents(version: number, file: string, sourceRoot: string, sources: string[], names: string[], mappings: string, sourcesContent?: string[]) { if (typeof JSON !== "undefined") { - let map: any = { + const map: any = { version, file, sourceRoot, @@ -953,7 +953,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) { encodeLastRecordedSourceMapSpan(); - let sourceMapText = serializeSourceMapContents( + const sourceMapText = serializeSourceMapContents( 3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, @@ -967,7 +967,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapUrl: string; if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - let base64SourceMapText = convertToBase64(sourceMapText); + const base64SourceMapText = convertToBase64(sourceMapText); sourceMapUrl = `//# sourceMappingURL=data:application/json;base64,${base64SourceMapText}`; } else { @@ -981,7 +981,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Initialize source map data - let sourceMapJsFile = getBaseFileName(normalizeSlashes(jsFilePath)); + const sourceMapJsFile = getBaseFileName(normalizeSlashes(jsFilePath)); sourceMapData = { sourceMapFilePath: jsFilePath + ".map", jsSourceMappingURL: sourceMapJsFile + ".map", @@ -1065,7 +1065,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Create a temporary variable with a unique unused name. function createTempVariable(flags: TempFlags): Identifier { - let result = createSynthesizedNode(SyntaxKind.Identifier); + const result = createSynthesizedNode(SyntaxKind.Identifier); result.text = makeTempVariableName(flags); return result; } @@ -1078,7 +1078,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createAndRecordTempVariable(flags: TempFlags): Identifier { - let temp = createTempVariable(flags); + const temp = createTempVariable(flags); recordTempDeclaration(temp); return temp; @@ -1099,7 +1099,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitTokenText(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - let tokenString = tokenToString(tokenKind); + const tokenString = tokenToString(tokenKind); if (emitFn) { emitFn(); } @@ -1193,7 +1193,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(", "); } } - let node = nodes[start + i]; + const node = nodes[start + i]; // This emitting is to make sure we emit following comment properly // ...(x, /*comment1*/ y)... // ^ => node.pos @@ -1245,7 +1245,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitLiteral(node: LiteralExpression) { - let text = getLiteralText(node); + const text = getLiteralText(node); if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); @@ -1306,7 +1306,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; + const isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: @@ -1334,7 +1334,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDownlevelTaggedTemplate(node: TaggedTemplateExpression) { - let tempVariable = createAndRecordTempVariable(TempFlags.Auto); + const tempVariable = createAndRecordTempVariable(TempFlags.Auto); write("("); emit(tempVariable); write(" = "); @@ -1354,7 +1354,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.template.kind === SyntaxKind.TemplateExpression) { forEach((node.template).templateSpans, templateSpan => { write(", "); - let needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression + const needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression && (templateSpan.expression).operatorToken.kind === SyntaxKind.CommaToken; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -1370,7 +1370,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let emitOuterParens = isExpression(node.parent) + const emitOuterParens = isExpression(node.parent) && templateNeedsParens(node, node.parent); if (emitOuterParens) { @@ -1384,7 +1384,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } for (let i = 0, n = node.templateSpans.length; i < n; i++) { - let templateSpan = node.templateSpans[i]; + const templateSpan = node.templateSpans[i]; // 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 @@ -1395,7 +1395,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - let needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression + const needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression && comparePrecedenceToBinaryPlus(templateSpan.expression) !== Comparison.GreaterThan; if (i > 0 || headEmitted) { @@ -1538,7 +1538,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitJsxElement(openingNode: JsxOpeningLikeElement, children?: JsxChild[]) { - let syntheticReactRef = createSynthesizedNode(SyntaxKind.Identifier); + const syntheticReactRef = createSynthesizedNode(SyntaxKind.Identifier); syntheticReactRef.text = "React"; syntheticReactRef.parent = openingNode; @@ -1557,7 +1557,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { // Either emit one big object literal (no spread attribs), or // a call to React.__spread - let attrs = openingNode.attributes; + const attrs = openingNode.attributes; if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); @@ -1621,7 +1621,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Don't emit empty strings if (children[i].kind === SyntaxKind.JsxText) { - let text = getTextToEmit(children[i]); + const text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); write(text); @@ -1780,7 +1780,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function isExpressionIdentifier(node: Node): boolean { - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.AsExpression: @@ -1848,7 +1848,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let container = resolver.getReferencedExportContainer(node); + const container = resolver.getReferencedExportContainer(node); if (container) { if (container.kind === SyntaxKind.SourceFile) { // Identifier references module export @@ -1864,7 +1864,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else { if (modulekind !== ModuleKind.ES6) { - let declaration = resolver.getReferencedImportDeclaration(node); + const declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (declaration.kind === SyntaxKind.ImportClause) { // Identifier references default import @@ -1875,8 +1875,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else if (declaration.kind === SyntaxKind.ImportSpecifier) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); - let name = (declaration).propertyName || (declaration).name; - let identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name); + const name = (declaration).propertyName || (declaration).name; + const identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name); if (languageVersion === ScriptTarget.ES3 && identifier === "default") { write(`["default"]`); } @@ -1890,7 +1890,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (languageVersion !== ScriptTarget.ES6) { - let declaration = resolver.getReferencedNestedRedeclaration(node); + const declaration = resolver.getReferencedNestedRedeclaration(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; @@ -1908,7 +1908,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function isNameOfNestedRedeclaration(node: Identifier) { if (languageVersion < ScriptTarget.ES6) { - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: @@ -1924,7 +1924,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { // in converted loop body arguments cannot be used directly. - let name = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + const name = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); write(name); return; } @@ -1961,7 +1961,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("super"); } else { - let flags = resolver.getNodeCheckFlags(node); + const flags = resolver.getNodeCheckFlags(node); if (flags & NodeCheckFlags.SuperInstance) { write("_super.prototype"); } @@ -1973,14 +1973,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitObjectBindingPattern(node: BindingPattern) { write("{ "); - let elements = node.elements; + const elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write(" }"); } function emitArrayBindingPattern(node: BindingPattern) { write("["); - let elements = node.elements; + const elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write("]"); } @@ -2019,7 +2019,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAwaitExpression(node: AwaitExpression) { - let needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); + const needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); if (needsParenthesis) { write("("); } @@ -2060,7 +2060,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitListWithSpread(elements: Expression[], needsUniqueCopy: boolean, multiLine: boolean, trailingComma: boolean, useConcat: boolean) { let pos = 0; let group = 0; - let length = elements.length; + const length = elements.length; while (pos < length) { // Emit using the pattern .concat(, , ...) if (group === 1 && useConcat) { @@ -2108,7 +2108,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitArrayLiteral(node: ArrayLiteralExpression) { - let elements = node.elements; + const elements = node.elements; if (elements.length === 0) { write("[]"); } @@ -2132,7 +2132,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("{"); if (numElements > 0) { - let properties = node.properties; + const properties = node.properties; // If we are not doing a downlevel transformation for object literals, // then try to preserve the original shape of the object literal. @@ -2141,7 +2141,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= ScriptTarget.ES5, /* spacesBetweenBraces */ true); } else { - let multiLine = (node.flags & NodeFlags.MultiLine) !== 0; + const multiLine = (node.flags & NodeFlags.MultiLine) !== 0; if (!multiLine) { write(" "); } @@ -2164,8 +2164,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDownlevelObjectLiteralWithComputedProperties(node: ObjectLiteralExpression, firstComputedPropertyIndex: number) { - let multiLine = (node.flags & NodeFlags.MultiLine) !== 0; - let properties = node.properties; + const multiLine = (node.flags & NodeFlags.MultiLine) !== 0; + const properties = node.properties; write("("); @@ -2175,7 +2175,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // For computed properties, we need to create a unique handle to the object // literal so we can modify it without risking internal assignments tainting the object. - let tempVar = createAndRecordTempVariable(TempFlags.Auto); + const tempVar = createAndRecordTempVariable(TempFlags.Auto); // Write out the first non-computed properties // (or all properties if none of them are computed), @@ -2187,12 +2187,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi for (let i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { writeComma(); - let property = properties[i]; + const property = properties[i]; emitStart(property); if (property.kind === SyntaxKind.GetAccessor || property.kind === SyntaxKind.SetAccessor) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. - let accessors = getAllAccessorDeclarations(node.properties, property); + const accessors = getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } @@ -2283,10 +2283,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitObjectLiteral(node: ObjectLiteralExpression): void { - let properties = node.properties; + const properties = node.properties; if (languageVersion < ScriptTarget.ES6) { - let numProperties = properties.length; + const numProperties = properties.length; // Find the first computed property. // Everything until that point can be emitted as part of the initial object literal. @@ -2298,7 +2298,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - let hasComputedProperty = numInitialNonComputedProperties !== properties.length; + const hasComputedProperty = numInitialNonComputedProperties !== properties.length; if (hasComputedProperty) { emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); return; @@ -2311,7 +2311,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createBinaryExpression(left: Expression, operator: SyntaxKind, right: Expression, startsOnNewLine?: boolean): BinaryExpression { - let result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); + const result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); result.operatorToken = createSynthesizedNode(operator); result.left = left; result.right = right; @@ -2320,7 +2320,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createPropertyAccessExpression(expression: Expression, name: Identifier): PropertyAccessExpression { - let result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); + const result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); result.expression = parenthesizeForAccess(expression); result.dotToken = createSynthesizedNode(SyntaxKind.DotToken); result.name = name; @@ -2329,7 +2329,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createElementAccessExpression(expression: Expression, argumentExpression: Expression): ElementAccessExpression { - let result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); + const result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; @@ -2357,7 +2357,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return expr; } - let node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); + const node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); node.expression = expr; return node; } @@ -2396,7 +2396,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node: Identifier) { - let container = resolver.getReferencedExportContainer(node); + const container = resolver.getReferencedExportContainer(node); return container && container.kind !== SyntaxKind.SourceFile; } @@ -2426,11 +2426,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { - let constantValue = tryGetConstEnumValue(node); + const constantValue = tryGetConstEnumValue(node); if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - let propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); + const propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -2452,10 +2452,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // If the code is not indented, an optional valueToWriteWhenNotIndenting will be // emitted instead. function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean { - let realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); + const realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); // Always use a newline for synthesized code if the synthesizer desires it. - let synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); + const synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { increaseIndent(); @@ -2476,7 +2476,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } emit(node.expression); - let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + const indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal @@ -2484,12 +2484,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (!indentedBeforeDot) { if (node.expression.kind === SyntaxKind.NumericLiteral) { // check if numeric literal was originally written with a dot - let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + const text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0; } else { // check if constant enum value is integer - let constantValue = tryGetConstEnumValue(node.expression); + const constantValue = tryGetConstEnumValue(node.expression); // isFinite handles cases when constantValue is undefined shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; } @@ -2502,7 +2502,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("."); } - let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + const indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -2518,7 +2518,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { - let temp = createAndRecordTempVariable(TempFlags.Auto); + const temp = createAndRecordTempVariable(TempFlags.Auto); write("("); emitNodeWithoutSourceMap(temp); write(" = "); @@ -2578,7 +2578,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node); return node; } - let temp = createAndRecordTempVariable(TempFlags.Auto); + const temp = createAndRecordTempVariable(TempFlags.Auto); write("("); emit(temp); @@ -2590,7 +2590,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitCallWithSpread(node: CallExpression) { let target: Expression; - let expr = skipParentheses(node.expression); + const expr = skipParentheses(node.expression); if (expr.kind === SyntaxKind.PropertyAccessExpression) { // Target will be emitted as "this" argument target = emitCallTarget((expr).expression); @@ -2684,7 +2684,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi hasSpreadElement(node.arguments)) { write("("); - let target = emitCallTarget(node.expression); + const target = emitCallTarget(node.expression); write(".bind.apply("); emit(target); write(", [void 0].concat("); @@ -2816,7 +2816,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. if (node.operand.kind === SyntaxKind.PrefixUnaryExpression) { - let operand = node.operand; + const operand = node.operand; if (node.operator === SyntaxKind.PlusToken && (operand.operator === SyntaxKind.PlusToken || operand.operator === SyntaxKind.PlusPlusToken)) { write(" "); } @@ -2895,7 +2895,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi * @param node a binary expression node containing exponentiationOperator (**, **=) */ function emitExponentiationOperator(node: BinaryExpression) { - let leftHandSideExpression = node.left; + const leftHandSideExpression = node.left; if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) { let synthesizedLHS: ElementAccessExpression | PropertyAccessExpression; let shouldEmitParentheses = false; @@ -2905,12 +2905,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi synthesizedLHS = createSynthesizedNode(SyntaxKind.ElementAccessExpression, /*startsOnNewLine*/ false); - let identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== SyntaxKind.NumericLiteral && leftHandSideExpression.argumentExpression.kind !== SyntaxKind.StringLiteral) { - let tempArgumentExpression = createAndRecordTempVariable(TempFlags._i); + const tempArgumentExpression = createAndRecordTempVariable(TempFlags._i); (synthesizedLHS).argumentExpression = tempArgumentExpression; emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true); } @@ -2924,7 +2924,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("("); synthesizedLHS = createSynthesizedNode(SyntaxKind.PropertyAccessExpression, /*startsOnNewLine*/ false); - let identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; (synthesizedLHS).dotToken = leftHandSideExpression.dotToken; @@ -2983,9 +2983,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // emitted as // 3 // + 2; - let indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); + const indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); write(tokenToString(node.operatorToken.kind)); - let indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); + const indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); emit(node.right); decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); } @@ -3002,14 +3002,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitConditionalExpression(node: ConditionalExpression) { emit(node.condition); - let indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); + const indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); write("?"); - let indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); + const indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); emit(node.whenTrue); decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - let indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); + const indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); write(":"); - let indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); + const indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); emit(node.whenFalse); decreaseIndentIf(indentedBeforeColon, indentedAfterColon); } @@ -3029,7 +3029,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function isSingleLineEmptyBlock(node: Node) { if (node && node.kind === SyntaxKind.Block) { - let block = node; + const block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } } @@ -3190,7 +3190,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitVariableDeclarationListSkippingUninitializedEntries(list: VariableDeclarationList): boolean { let started = false; - for (let decl of list.declarations) { + for (const decl of list.declarations) { if (!decl.initializer) { continue; } @@ -3468,8 +3468,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - for (let labelText in table) { - let labelMarker = table[labelText]; + for (const labelText in table) { + const labelMarker = table[labelText]; writeLine(); write(`case "${labelMarker}": `); // if there are no outer converted loop or outer label in question is located inside outer converted loop @@ -3501,8 +3501,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableDeclarationList = node.initializer; - let startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + const variableDeclarationList = node.initializer; + const startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -3541,7 +3541,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableDeclarationList = node.initializer; + const variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); emit(variableDeclarationList.declarations[0]); @@ -3607,8 +3607,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // for (let v of arr) { } // // we can't reuse 'arr' because it might be modified within the body of the loop. - let counter = createTempVariable(TempFlags._i); - let rhsReference = createSynthesizedNode(SyntaxKind.Identifier) as Identifier; + const counter = createTempVariable(TempFlags._i); + const rhsReference = createSynthesizedNode(SyntaxKind.Identifier) as Identifier; rhsReference.text = node.expression.kind === SyntaxKind.Identifier ? makeUniqueName((node.expression).text) : makeTempVariableName(TempFlags.Auto); @@ -3658,13 +3658,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Initialize LHS // let v = _a[_i]; - let rhsIterationValue = createElementAccessExpression(rhsReference, counter); + const rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { write("var "); - let variableDeclarationList = node.initializer; + const variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { - let declaration = variableDeclarationList.declarations[0]; + const declaration = variableDeclarationList.declarations[0]; if (isBindingPattern(declaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -3689,7 +3689,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - let assignmentExpression = createBinaryExpression(node.initializer, SyntaxKind.EqualsToken, rhsIterationValue, /*startsOnNewLine*/ false); + const assignmentExpression = createBinaryExpression(node.initializer, SyntaxKind.EqualsToken, rhsIterationValue, /*startsOnNewLine*/ false); if (node.initializer.kind === SyntaxKind.ArrayLiteralExpression || node.initializer.kind === SyntaxKind.ObjectLiteralExpression) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. @@ -3869,7 +3869,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitCatchClause(node: CatchClause) { writeLine(); - let endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); + const endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); write(" "); emitToken(SyntaxKind.OpenParenToken, endPos); emit(node.variableDeclaration); @@ -3915,14 +3915,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitContainingModuleName(node: Node) { - let container = getContainingModule(node); + const container = getContainingModule(node); write(container ? getGeneratedNameForNode(container) : "exports"); } function emitModuleMemberName(node: Declaration) { emitStart(node.name); if (getCombinedNodeFlags(node) & NodeFlags.Export) { - let container = getContainingModule(node); + const container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); @@ -3936,9 +3936,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createVoidZero(): Expression { - let zero = createSynthesizedNode(SyntaxKind.NumericLiteral); + const zero = createSynthesizedNode(SyntaxKind.NumericLiteral); zero.text = "0"; - let result = createSynthesizedNode(SyntaxKind.VoidExpression); + const result = createSynthesizedNode(SyntaxKind.VoidExpression); result.expression = zero; return result; } @@ -4010,7 +4010,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) { - for (let specifier of exportSpecifiers[name.text]) { + for (const specifier of exportSpecifiers[name.text]) { writeLine(); emitStart(specifier.name); emitContainingModuleName(specifier); @@ -4053,7 +4053,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(", "); } - let exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); + const exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(`${exportFunctionForFile}("`); @@ -4086,7 +4086,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma */ function emitTempVariableAssignment(expression: Expression, canDefineTempVariablesInPlace: boolean, shouldEmitCommaBeforeAssignment: boolean): Identifier { - let identifier = createTempVariable(TempFlags.Auto); + const identifier = createTempVariable(TempFlags.Auto); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } @@ -4103,8 +4103,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // because actual variable declarations are hoisted let canDefineTempVariablesInPlace = false; if (root.kind === SyntaxKind.VariableDeclaration) { - let isExported = getCombinedNodeFlags(root) & NodeFlags.Export; - let isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); + const isExported = getCombinedNodeFlags(root) & NodeFlags.Export; + const isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } else if (root.kind === SyntaxKind.Parameter) { @@ -4134,7 +4134,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return expr; } - let identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + const identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); emitCount++; return identifier; } @@ -4144,7 +4144,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // we need to generate a temporary variable value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); // Return the expression 'value === void 0 ? defaultValue : value' - let equals = createSynthesizedNode(SyntaxKind.BinaryExpression); + const equals = createSynthesizedNode(SyntaxKind.BinaryExpression); equals.left = value; equals.operatorToken = createSynthesizedNode(SyntaxKind.EqualsEqualsEqualsToken); equals.right = createVoidZero(); @@ -4152,7 +4152,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createConditionalExpression(condition: Expression, whenTrue: Expression, whenFalse: Expression) { - let cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); + const cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); cond.condition = condition; cond.questionToken = createSynthesizedNode(SyntaxKind.QuestionToken); cond.whenTrue = whenTrue; @@ -4162,7 +4162,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createNumericLiteral(value: number) { - let node = createSynthesizedNode(SyntaxKind.NumericLiteral); + const node = createSynthesizedNode(SyntaxKind.NumericLiteral); node.text = "" + value; return node; } @@ -4186,8 +4186,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createSliceCall(value: Expression, sliceIndex: number): CallExpression { - let call = createSynthesizedNode(SyntaxKind.CallExpression); - let sliceIdentifier = createSynthesizedNode(SyntaxKind.Identifier); + const call = createSynthesizedNode(SyntaxKind.CallExpression); + const sliceIdentifier = createSynthesizedNode(SyntaxKind.Identifier); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); call.arguments = >createSynthesizedNodeArray(); @@ -4196,30 +4196,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression) { - let properties = target.properties; + const properties = target.properties; if (properties.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } - for (let p of properties) { + for (const p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - let propName = (p).name; - let target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? p : (p).initializer || propName; + const propName = (p).name; + const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? p : (p).initializer || propName; emitDestructuringAssignment(target, createPropertyAccessForDestructuringProperty(value, propName)); } } } function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression) { - let elements = target.elements; + const elements = target.elements; if (elements.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } for (let i = 0; i < elements.length; i++) { - let e = elements[i]; + const e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); @@ -4255,7 +4255,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAssignmentExpression(root: BinaryExpression) { - let target = root.left; + const target = root.left; let value = root.right; if (isEmptyObjectLiteralOrArrayLiteral(target)) { @@ -4301,10 +4301,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } for (let i = 0; i < numElements; i++) { - let element = elements[i]; + const element = elements[i]; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Rewrite element to a declaration with an initializer that fetches property - let propName = element.propertyName || element.name; + const propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } else if (element.kind !== SyntaxKind.OmittedExpression) { @@ -4345,7 +4345,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // for (...) { var = void 0; } // this is necessary to preserve ES6 semantic in scenarios like // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations - let isLetDefinedInLoop = + const isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) && (getCombinedFlagsForIdentifier(node.name) & NodeFlags.Let); @@ -4357,7 +4357,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - let exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); + const exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); if (exportChanged) { write(`${exportFunctionForFile}("`); @@ -4378,7 +4378,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.OmittedExpression) { return; } - let name = node.name; + const name = node.name; if (name.kind === SyntaxKind.Identifier) { emitExportMemberAssignments(name); } @@ -4420,7 +4420,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(";"); } else { - let atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); + const atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); if (atLeastOneItem) { write(";"); } @@ -4444,7 +4444,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Otherwise, only emit if we have at least one initializer present. - for (let declaration of node.declarationList.declarations) { + for (const declaration of node.declarationList.declarations) { if (declaration.initializer) { return true; } @@ -4455,7 +4455,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitParameter(node: ParameterDeclaration) { if (languageVersion < ScriptTarget.ES6) { if (isBindingPattern(node.name)) { - let name = createTempVariable(TempFlags.Auto); + const name = createTempVariable(TempFlags.Auto); if (!tempParameters) { tempParameters = []; } @@ -4485,12 +4485,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let { name: paramName, initializer } = parameter; + const { name: paramName, initializer } = parameter; if (isBindingPattern(paramName)) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. - let hasBindingElements = paramName.elements.length > 0; + const hasBindingElements = paramName.elements.length > 0; if (hasBindingElements || initializer) { writeLine(); write("var "); @@ -4529,15 +4529,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitRestParameter(node: FunctionLikeDeclaration) { if (languageVersion < ScriptTarget.ES6 && hasRestParameter(node)) { - let restIndex = node.parameters.length - 1; - let restParam = node.parameters[restIndex]; + const restIndex = node.parameters.length - 1; + const restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (isBindingPattern(restParam.name)) { return; } - let tempName = createTempVariable(TempFlags._i).text; + const tempName = createTempVariable(TempFlags._i).text; writeLine(); emitLeadingComments(restParam); emitStart(restParam); @@ -4674,8 +4674,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); write("("); if (node) { - let parameters = node.parameters; - let omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0; + const parameters = node.parameters; + const omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false); } write(")"); @@ -4693,10 +4693,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAsyncFunctionBodyForES6(node: FunctionLikeDeclaration) { - let promiseConstructor = getEntityNameFromTypeNode(node.type); - let isArrowFunction = node.kind === SyntaxKind.ArrowFunction; - let hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; - let args: string; + const promiseConstructor = getEntityNameFromTypeNode(node.type); + const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; + const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -4834,9 +4833,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitSignatureAndBody(node: FunctionLikeDeclaration) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; convertedLoopState = undefined; tempFlags = 0; @@ -4852,7 +4851,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitSignatureParameters(node); } - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync && languageVersion === ScriptTarget.ES6) { emitAsyncFunctionBodyForES6(node); } @@ -4905,10 +4904,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi scopeEmitStart(node); increaseIndent(); - let outPos = writer.getTextPos(); + const outPos = writer.getTextPos(); emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); - let preambleEmitted = writer.getTextPos() !== outPos; + const preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); // If we didn't have to emit any preamble code, then attempt to keep the arrow @@ -4948,21 +4947,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" {"); scopeEmitStart(node); - let initialTextPos = writer.getTextPos(); + const initialTextPos = writer.getTextPos(); increaseIndent(); emitDetachedCommentsAndUpdateCommentsInfo(body.statements); // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). - let startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); emitFunctionBodyPreamble(node); decreaseIndent(); - let preambleEmitted = writer.getTextPos() !== initialTextPos; + const preambleEmitted = writer.getTextPos() !== initialTextPos; if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (let statement of body.statements) { + for (const statement of body.statements) { write(" "); emit(statement); } @@ -4986,11 +4985,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function findInitialSuperCall(ctor: ConstructorDeclaration): ExpressionStatement { if (ctor.body) { - let statement = (ctor.body).statements[0]; + const statement = (ctor.body).statements[0]; if (statement && statement.kind === SyntaxKind.ExpressionStatement) { - let expr = (statement).expression; + const expr = (statement).expression; if (expr && expr.kind === SyntaxKind.CallExpression) { - let func = (expr).expression; + const func = (expr).expression; if (func && func.kind === SyntaxKind.SuperKeyword) { return statement; } @@ -5035,8 +5034,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getInitializedProperties(node: ClassLikeDeclaration, isStatic: boolean) { - let properties: PropertyDeclaration[] = []; - for (let member of node.members) { + const properties: PropertyDeclaration[] = []; + for (const member of node.members) { if (member.kind === SyntaxKind.PropertyDeclaration && isStatic === ((member.flags & NodeFlags.Static) !== 0) && (member).initializer) { properties.push(member); } @@ -5046,7 +5045,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitPropertyDeclarations(node: ClassLikeDeclaration, properties: PropertyDeclaration[]) { - for (let property of properties) { + for (const property of properties) { emitPropertyDeclaration(node, property); } } @@ -5104,7 +5103,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitTrailingComments(member); } else if (member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) { - let accessors = getAllAccessorDeclarations(node.members, member); + const accessors = getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); emitStart(member); @@ -5152,7 +5151,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitMemberFunctionsForES6AndHigher(node: ClassLikeDeclaration) { - for (let member of node.members) { + for (const member of node.members) { if ((member.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && !(member).body) { emitCommentsOnNotEmittedNode(member); } @@ -5189,9 +5188,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitConstructor(node: ClassLikeDeclaration, baseTypeElement: ExpressionWithTypeArguments) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; convertedLoopState = undefined; tempFlags = 0; @@ -5225,7 +5224,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } }); - let ctor = getFirstConstructorWithBody(node); + const ctor = getFirstConstructorWithBody(node); // For target ES6 and above, if there is no user-defined constructor and there is no property assignment // do not emit constructor in class declaration. @@ -5345,7 +5344,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) { - let thisNodeIsDecorated = nodeIsDecorated(node); + const thisNodeIsDecorated = nodeIsDecorated(node); if (node.kind === SyntaxKind.ClassDeclaration) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, @@ -5424,8 +5423,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. - let staticProperties = getInitializedProperties(node, /*static:*/ true); - let isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression; + const staticProperties = getInitializedProperties(node, /*static:*/ true); + const isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression; let tempVariable: Identifier; if (isClassExpressionWithStaticProperties) { @@ -5446,7 +5445,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitDeclarationName(node); } - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { write(" extends "); emit(baseTypeNode.expression); @@ -5531,16 +5530,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write("(function ("); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { write("_super"); } write(") {"); - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; - let saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - let saveConvertedLoopState = convertedLoopState; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; + const saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; + const saveConvertedLoopState = convertedLoopState; convertedLoopState = undefined; tempFlags = 0; @@ -5612,9 +5611,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDecoratorsOfConstructor(node: ClassLikeDeclaration) { - let decorators = node.decorators; - let constructor = getFirstConstructorWithBody(node); - let hasDecoratedParameters = constructor && forEach(constructor.parameters, nodeIsDecorated); + const decorators = node.decorators; + const constructor = getFirstConstructorWithBody(node); + const hasDecoratedParameters = constructor && forEach(constructor.parameters, nodeIsDecorated); // skip decoration of the constructor if neither it nor its parameters are decorated if (!decorators && !hasDecoratedParameters) { @@ -5639,7 +5638,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); - let decoratorCount = decorators ? decorators.length : 0; + const decoratorCount = decorators ? decorators.length : 0; let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); emit(decorator.expression); @@ -5659,7 +5658,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDecoratorsOfMembers(node: ClassLikeDeclaration, staticFlag: NodeFlags) { - for (let member of node.members) { + for (const member of node.members) { // only emit members in the correct group if ((member.flags & NodeFlags.Static) !== staticFlag) { continue; @@ -5679,7 +5678,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let decorators: NodeArray; let functionLikeMember: FunctionLikeDeclaration; if (isAccessor(member)) { - let accessors = getAllAccessorDeclarations(node.members, member); + const accessors = getAllAccessorDeclarations(node.members, member); if (member !== accessors.firstAccessor) { continue; } @@ -5739,7 +5738,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); - let decoratorCount = decorators ? decorators.length : 0; + const decoratorCount = decorators ? decorators.length : 0; let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); emit(decorator.expression); @@ -5781,9 +5780,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let argumentsWritten = 0; if (node) { let parameterIndex = 0; - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { if (nodeIsDecorated(parameter)) { - let decorators = parameter.decorators; + const decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); write(`__param(${parameterIndex}, `); @@ -5948,10 +5947,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Clone the type name and parent it to a location outside of the current declaration. - let typeName = cloneEntityName(node.typeName); + const typeName = cloneEntityName(node.typeName); typeName.parent = location; - let result = resolver.getTypeReferenceSerializationKind(typeName); + const result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case TypeReferenceSerializationKind.Unknown: let temp = createAndRecordTempVariable(TempFlags.Auto); @@ -6113,7 +6112,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function shouldEmitEnumDeclaration(node: EnumDeclaration) { - let isConstEnum = isConst(node); + const isConstEnum = isConst(node); return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } @@ -6182,7 +6181,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitEnumMember(node: EnumMember) { - let enumParent = node.parent; + const enumParent = node.parent; emitStart(node); write(getGeneratedNameForNode(enumParent)); write("["); @@ -6198,7 +6197,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeEnumMemberDeclarationValue(member: EnumMember) { - let value = resolver.getConstantValue(member); + const value = resolver.getConstantValue(member); if (value !== undefined) { write(value.toString()); return; @@ -6213,7 +6212,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration { if (moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { - let recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } @@ -6228,13 +6227,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitModuleDeclaration(node: ModuleDeclaration) { // Emit only if this module is non-ambient. - let shouldEmit = shouldEmitModuleDeclaration(node); + const shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { return emitCommentsOnNotEmittedNode(node); } - let hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - let emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); + const hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); + const emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { emitStart(node); @@ -6256,8 +6255,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(") "); if (node.body.kind === SyntaxKind.ModuleBlock) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; @@ -6279,7 +6278,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.body); decreaseIndent(); writeLine(); - let moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(SyntaxKind.CloseBraceToken, moduleBlock.statements.end); scopeEmitEnd(); } @@ -6321,7 +6320,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitRequire(moduleName: Expression) { if (moduleName.kind === SyntaxKind.StringLiteral) { write("require("); - let text = tryRenameExternalModule(moduleName); + const text = tryRenameExternalModule(moduleName); if (text) { write(text); } @@ -6341,7 +6340,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.ImportEqualsDeclaration) { return node; } - let importClause = (node).importClause; + const importClause = (node).importClause; if (importClause && importClause.namedBindings && importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { return importClause.namedBindings; } @@ -6365,8 +6364,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // ES6 import if (node.importClause) { - let shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - let shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); + const shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); + const shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { write("import "); emitStart(node.importClause); @@ -6407,8 +6406,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitExternalImportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration) { if (contains(externalImports, node)) { - let isExportedImport = node.kind === SyntaxKind.ImportEqualsDeclaration && (node.flags & NodeFlags.Export) !== 0; - let namespaceDeclaration = getNamespaceDeclarationNode(node); + const isExportedImport = node.kind === SyntaxKind.ImportEqualsDeclaration && (node.flags & NodeFlags.Export) !== 0; + const namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== ModuleKind.AMD) { emitLeadingComments(node); @@ -6426,7 +6425,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - let isNakedImport = SyntaxKind.ImportDeclaration && !(node).importClause; + const isNakedImport = SyntaxKind.ImportDeclaration && !(node).importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -6481,11 +6480,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // variable declaration for import-equals declaration can be hoisted in system modules // in this case 'var' should be omitted and emit should contain only initialization - let variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); + const variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); // is it top level export import v = a.b.c in system module? // if yes - it needs to be rewritten as exporter('v', v = a.b.c) - let isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); + const isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); if (!variableDeclarationIsHoisted) { Debug.assert(!isExported); @@ -6527,7 +6526,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (modulekind !== ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); - let generatedName = getGeneratedNameForNode(node); + const generatedName = getGeneratedNameForNode(node); if (node.exportClause) { // export { x, y, ... } from "foo" if (modulekind !== ModuleKind.AMD) { @@ -6537,7 +6536,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitRequire(getExternalModuleName(node)); write(";"); } - for (let specifier of node.exportClause.elements) { + for (const specifier of node.exportClause.elements) { if (resolver.isValueAliasDeclaration(specifier)) { writeLine(); emitStart(specifier); @@ -6593,7 +6592,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi Debug.assert(modulekind === ModuleKind.ES6); let needsComma = false; - for (let specifier of specifiers) { + for (const specifier of specifiers) { if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -6614,7 +6613,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); emitStart(node); write("export default "); - let expression = node.expression; + const expression = node.expression; emit(expression); if (expression.kind !== SyntaxKind.FunctionDeclaration && expression.kind !== SyntaxKind.ClassDeclaration) { @@ -6652,7 +6651,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi exportSpecifiers = {}; exportEquals = undefined; hasExportStars = false; - for (let node of sourceFile.statements) { + for (const node of sourceFile.statements) { switch (node.kind) { case SyntaxKind.ImportDeclaration: if (!(node).importClause || @@ -6684,8 +6683,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else { // export { x, y } - for (let specifier of (node).exportClause.elements) { - let name = (specifier.propertyName || specifier.name).text; + for (const specifier of (node).exportClause.elements) { + const name = (specifier.propertyName || specifier.name).text; (exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier); } } @@ -6714,7 +6713,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { - let namespaceDeclaration = getNamespaceDeclarationNode(node); + const namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { return getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } @@ -6727,7 +6726,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { - let moduleName = getExternalModuleName(importNode); + const moduleName = getExternalModuleName(importNode); if (moduleName.kind === SyntaxKind.StringLiteral) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); } @@ -6742,9 +6741,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); let started = false; - for (let importNode of externalImports) { + for (const importNode of externalImports) { // do not create variable declaration for exports and imports that lack import clause - let skipNode = + const skipNode = importNode.kind === SyntaxKind.ExportDeclaration || (importNode.kind === SyntaxKind.ImportDeclaration && !(importNode).importClause); @@ -6783,7 +6782,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. let hasExportDeclarationWithExportClause = false; - for (let externalImport of externalImports) { + for (const externalImport of externalImports) { if (externalImport.kind === SyntaxKind.ExportDeclaration && (externalImport).exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -6811,26 +6810,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (exportSpecifiers) { - for (let n in exportSpecifiers) { - for (let specifier of exportSpecifiers[n]) { + for (const n in exportSpecifiers) { + for (const specifier of exportSpecifiers[n]) { // write name of export specified, i.e. 'export {x}' writeExportedName(specifier.name); } } } - for (let externalImport of externalImports) { + for (const externalImport of externalImports) { if (externalImport.kind !== SyntaxKind.ExportDeclaration) { continue; } - let exportDecl = externalImport; + const exportDecl = externalImport; if (!exportDecl.exportClause) { // export * from ... continue; } - for (let element of exportDecl.exportClause.elements) { + for (const element of exportDecl.exportClause.elements) { // write name of indirectly exported entry, i.e. 'export {x} from ...' writeExportedName(element.name || element.propertyName); } @@ -6919,16 +6918,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (hoistedVars) { writeLine(); write("var "); - let seen: Map = {}; + const seen: Map = {}; for (let i = 0; i < hoistedVars.length; ++i) { - let local = hoistedVars[i]; - let name = local.kind === SyntaxKind.Identifier + const local = hoistedVars[i]; + const name = local.kind === SyntaxKind.Identifier ? local : (local).name; if (name) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - let text = unescapeIdentifier(name.text); + const text = unescapeIdentifier(name.text); if (hasProperty(seen, text)) { continue; } @@ -6948,7 +6947,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(local); } - let flags = getCombinedNodeFlags(local.kind === SyntaxKind.Identifier ? local.parent : local); + const flags = getCombinedNodeFlags(local.kind === SyntaxKind.Identifier ? local.parent : local); if (flags & NodeFlags.Export) { if (!exportedDeclarations) { exportedDeclarations = []; @@ -6960,7 +6959,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (hoistedFunctionDeclarations) { - for (let f of hoistedFunctionDeclarations) { + for (const f of hoistedFunctionDeclarations) { writeLine(); emit(f); @@ -7023,7 +7022,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - let name = (node).name; + const name = (node).name; if (name.kind === SyntaxKind.Identifier) { if (!hoistedVars) { hoistedVars = []; @@ -7114,8 +7113,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // } emitVariableDeclarationsForImports(); writeLine(); - let exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); + const exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); + const exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); writeLine(); write("return {"); increaseIndent(); @@ -7140,15 +7139,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); increaseIndent(); - let group = dependencyGroups[i]; + const group = dependencyGroups[i]; // derive a unique name for parameter from the first named entry in the group - let parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || ""); + const parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || ""); write(`function (${parameterName}) {`); increaseIndent(); - for (let entry of group) { - let importVariableName = getLocalNameForExternalImport(entry) || ""; + for (const entry of group) { + const importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case SyntaxKind.ImportDeclaration: @@ -7186,7 +7185,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); } - let e = (entry).exportClause.elements[i]; + const e = (entry).exportClause.elements[i]; write(`"`); emitNodeWithCommentsAndWithoutSourcemap(e.name); write(`": ${parameterName}["`); @@ -7224,7 +7223,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); for (let i = startIndex; i < node.statements.length; ++i) { - let statement = node.statements[i]; + const statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters @@ -7235,7 +7234,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi continue; case SyntaxKind.ExportDeclaration: if (!(statement).moduleSpecifier) { - for (let element of (statement).exportClause.elements) { + for (const element of (statement).exportClause.elements) { // write call to exporter function for every export specifier in exports list emitExportSpecifierInSystemModule(element); } @@ -7277,14 +7276,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write("["); - let groupIndices: Map = {}; - let dependencyGroups: DependencyGroup[] = []; + const groupIndices: Map = {}; + const dependencyGroups: DependencyGroup[] = []; for (let i = 0; i < externalImports.length; ++i) { - let text = getExternalModuleNameText(externalImports[i]); + const text = getExternalModuleNameText(externalImports[i]); if (hasProperty(groupIndices, text)) { // deduplicate/group entries in dependency list by the dependency name - let groupIndex = groupIndices[text]; + const groupIndex = groupIndices[text]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } @@ -7302,7 +7301,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(`], function(${exportFunctionForFile}) {`); writeLine(); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -7319,15 +7318,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getAMDDependencyNames(node: SourceFile, includeNonAmdDependencies: boolean): AMDDependencyNames { // names of modules with corresponding parameter in the factory function - let aliasedModuleNames: string[] = []; + const aliasedModuleNames: string[] = []; // names of modules with no corresponding parameters in factory function - let unaliasedModuleNames: string[] = []; - let importAliasNames: string[] = []; // names of the parameters in the factory function; these + const unaliasedModuleNames: string[] = []; + const importAliasNames: string[] = []; // names of the parameters in the factory function; these // parameters need to match the indexes of the corresponding // module names in aliasedModuleNames. // Fill in amd-dependency tags - for (let amdDependency of node.amdDependencies) { + for (const amdDependency of node.amdDependencies) { if (amdDependency.name) { aliasedModuleNames.push("\"" + amdDependency.path + "\""); importAliasNames.push(amdDependency.name); @@ -7337,12 +7336,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - for (let importNode of externalImports) { + for (const importNode of externalImports) { // Find the name of the external module - let externalModuleName = getExternalModuleNameText(importNode); + const externalModuleName = getExternalModuleNameText(importNode); // Find the name of the module alias, if there is one - let importAliasName = getLocalNameForExternalImport(importNode); + const importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); importAliasNames.push(importAliasName); @@ -7368,7 +7367,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // `import "module"` or `` // we need to add modules without alias names to the end of the dependencies list - let dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + const dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -7407,7 +7406,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7419,7 +7418,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitCommonJSModule(node: SourceFile) { - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -7433,7 +7432,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitEmitHelpers(node); collectExternalModuleInfo(node); - let dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); + const dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); // Module is detected first to support Browserify users that load into a browser with an AMD loader writeLines(`(function (factory) { @@ -7448,7 +7447,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi })(`); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7464,7 +7463,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi exportSpecifiers = undefined; exportEquals = undefined; hasExportStars = false; - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7499,7 +7498,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function trimReactWhitespaceAndApplyEntities(node: JsxText): string { let result: string = undefined; - let text = getTextOfNode(node, /*includeTrivia*/ true); + const text = getTextOfNode(node, /*includeTrivia*/ true); let firstNonWhitespace = 0; let lastNonWhitespace = -1; @@ -7507,10 +7506,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // start/end of a tag is considered a start/end of a line only if that line is // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx for (let i = 0; i < text.length; i++) { - let c = text.charCodeAt(i); + const c = text.charCodeAt(i); if (isLineBreak(c)) { if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + const part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); result = (result ? result + "\" + ' ' + \"" : "") + escapeString(part); } firstNonWhitespace = -1; @@ -7524,7 +7523,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (firstNonWhitespace !== -1) { - let part = text.substr(firstNonWhitespace); + const part = text.substr(firstNonWhitespace); result = (result ? result + "\" + ' ' + \"" : "") + escapeString(part); } @@ -7607,9 +7606,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeLines(text: string): void { - let lines = text.split(/\r\n|\r|\n/g); + const lines = text.split(/\r\n|\r|\n/g); for (let i = 0; i < lines.length; ++i) { - let line = lines[i]; + const line = lines[i]; if (line.length) { writeLine(); write(line); @@ -7654,12 +7653,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitDetachedCommentsAndUpdateCommentsInfo(node); if (isExternalModule(node) || compilerOptions.isolatedModules) { - let emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS]; + const emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS]; emitModule(node); } else { // emit prologue directives prior to __extends - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; @@ -7688,7 +7687,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return emitNodeWithoutSourceMap(node); } - let emitComments = shouldEmitLeadingAndTrailingComments(node); + const emitComments = shouldEmitLeadingAndTrailingComments(node); if (emitComments) { emitLeadingComments(node); } @@ -7935,7 +7934,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - let leadingComments = getLeadingCommentRanges(currentSourceFile.text, + const leadingComments = getLeadingCommentRanges(currentSourceFile.text, lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); @@ -7958,7 +7957,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.slash && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.slash) { - let textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + const textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); return textSubStr.match(fullTripleSlashReferencePathRegEx) || textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -8037,7 +8036,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Emit the trailing comments only if the parent's end doesn't match - let trailingComments = getTrailingCommentsToEmit(node); + const trailingComments = getTrailingCommentsToEmit(node); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); @@ -8053,7 +8052,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos); + const trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); @@ -8081,7 +8080,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDetachedCommentsAndUpdateCommentsInfo(node: TextRange) { - let currentDetachedCommentInfo = emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + const currentDetachedCommentInfo = emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); if (currentDetachedCommentInfo) { if (detachedCommentsInfo) { @@ -8094,7 +8093,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitShebang() { - let shebang = getShebang(currentSourceFile.text); + const shebang = getShebang(currentSourceFile.text); if (shebang) { write(shebang); } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 65f55f14cc6..2e539097e24 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2,7 +2,7 @@ /// namespace ts { - let nodeConstructors = new Array Node>(SyntaxKind.Count); + const nodeConstructors = new Array Node>(SyntaxKind.Count); /* @internal */ export let parseTime = 0; export function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node { @@ -27,8 +27,8 @@ namespace ts { function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { if (nodes) { - for (let node of nodes) { - let result = cbNode(node); + for (const node of nodes) { + const result = cbNode(node); if (result) { return result; } @@ -47,8 +47,8 @@ namespace ts { // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray // callback parameters, but that causes a closure allocation for each invocation with noticeable effects // on performance. - let visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; - let cbNodes = cbNodeArray || cbNode; + const visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; + const cbNodes = cbNodeArray || cbNode; switch (node.kind) { case SyntaxKind.QualifiedName: return visitNode(cbNode, (node).left) || @@ -397,8 +397,8 @@ namespace ts { } export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile { - let start = new Date().getTime(); - let result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + const start = new Date().getTime(); + const result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); parseTime += new Date().getTime() - start; return result; @@ -529,7 +529,7 @@ namespace ts { export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean): SourceFile { initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - let result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + const result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); clearState(); @@ -620,10 +620,10 @@ namespace ts { } function addJSDocComment(node: Node) { - let comments = getLeadingCommentRangesOfNode(node, sourceFile); + const comments = getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (let comment of comments) { - let jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + for (const comment of comments) { + const jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; } @@ -648,7 +648,7 @@ namespace ts { if (n.parent !== parent) { n.parent = parent; - let saveParent = parent; + const saveParent = parent; parent = n; forEachChild(n, visitNode); parent = saveParent; @@ -657,7 +657,7 @@ namespace ts { } function createSourceFile(fileName: string, languageVersion: ScriptTarget): SourceFile { - let sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); + const sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; @@ -703,11 +703,11 @@ namespace ts { // that we do not mutate cached flags for the incremental // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). - let contextFlagsToClear = context & contextFlags; + const contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags setContextFlag(false, contextFlagsToClear); - let result = func(); + const result = func(); // restore the context flags we just cleared setContextFlag(true, contextFlagsToClear); return result; @@ -724,11 +724,11 @@ namespace ts { // that we do not mutate cached flags for the incremental // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). - let contextFlagsToSet = context & ~contextFlags; + const contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags setContextFlag(true, contextFlagsToSet); - let result = func(); + const result = func(); // reset the context flags we just set setContextFlag(false, contextFlagsToSet); return result; @@ -795,15 +795,15 @@ namespace ts { } function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { - let start = scanner.getTokenPos(); - let length = scanner.getTextPos() - start; + const start = scanner.getTokenPos(); + const length = scanner.getTextPos() - start; parseErrorAtPosition(start, length, message, arg0); } function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): void { // Don't report another error if it would just be at the same position as the last error. - let lastError = lastOrUndefined(parseDiagnostics); + const lastError = lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { parseDiagnostics.push(createFileDiagnostic(sourceFile, start, length, message, arg0)); } @@ -814,7 +814,7 @@ namespace ts { } function scanError(message: DiagnosticMessage, length?: number) { - let pos = scanner.getTextPos(); + const pos = scanner.getTextPos(); parseErrorAtPosition(pos, length || 0, message); } @@ -857,20 +857,20 @@ namespace ts { function speculationHelper(callback: () => T, isLookAhead: boolean): T { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - let saveToken = token; - let saveParseDiagnosticsLength = parseDiagnostics.length; - let saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + const saveToken = token; + const saveParseDiagnosticsLength = parseDiagnostics.length; + const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can // assert that that invariant holds. - let saveContextFlags = contextFlags; + const saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the // same. - let result = isLookAhead + const result = isLookAhead ? scanner.lookAhead(callback) : scanner.tryScan(callback); @@ -962,7 +962,7 @@ namespace ts { } function parseTokenNode(): T { - let node = createNode(token); + const node = createNode(token); nextToken(); return finishNode(node); } @@ -1025,7 +1025,7 @@ namespace ts { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - let result = createNode(kind, scanner.getStartPos()); + const result = createNode(kind, scanner.getStartPos()); (result).text = ""; return finishNode(result); } @@ -1041,7 +1041,7 @@ namespace ts { function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage): Identifier { identifierCount++; if (isIdentifier) { - let node = createNode(SyntaxKind.Identifier); + const node = createNode(SyntaxKind.Identifier); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker if (token !== SyntaxKind.Identifier) { @@ -1095,7 +1095,7 @@ namespace ts { // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - let node = createNode(SyntaxKind.ComputedPropertyName); + const node = createNode(SyntaxKind.ComputedPropertyName); parseExpected(SyntaxKind.OpenBracketToken); // We parse any expression (including a comma expression). But the grammar @@ -1156,7 +1156,7 @@ namespace ts { // True if positioned at the start of a list element function isListElement(parsingContext: ParsingContext, inErrorRecovery: boolean): boolean { - let node = currentNode(parsingContext); + const node = currentNode(parsingContext); if (node) { return true; } @@ -1250,7 +1250,7 @@ namespace ts { // extends {} extends // extends {} implements - let next = nextToken(); + const next = nextToken(); return next === SyntaxKind.CommaToken || next === SyntaxKind.OpenBraceToken || next === SyntaxKind.ExtendsKeyword || next === SyntaxKind.ImplementsKeyword; } @@ -1378,14 +1378,14 @@ namespace ts { // Parses a list of elements function parseList(kind: ParsingContext, parseElement: () => T): NodeArray { - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << kind; - let result = >[]; + const result = >[]; result.pos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /* inErrorRecovery */ false)) { - let element = parseListElement(kind, parseElement); + const element = parseListElement(kind, parseElement); result.push(element); continue; @@ -1402,7 +1402,7 @@ namespace ts { } function parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { - let node = currentNode(parsingContext); + const node = currentNode(parsingContext); if (node) { return consumeNode(node); } @@ -1427,7 +1427,7 @@ namespace ts { return undefined; } - let node = syntaxCursor.currentNode(scanner.getStartPos()); + const node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. if (nodeIsMissing(node)) { @@ -1456,7 +1456,7 @@ namespace ts { // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - let nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; + const nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -1668,7 +1668,7 @@ namespace ts { // // In order to prevent this, we do not allow a variable declarator to be reused if it // has an initializer. - let variableDeclarator = node; + const variableDeclarator = node; return variableDeclarator.initializer === undefined; } @@ -1678,7 +1678,7 @@ namespace ts { } // See the comment in isReusableVariableDeclaration for why we do this. - let parameter = node; + const parameter = node; return parameter.initializer === undefined; } @@ -1726,9 +1726,9 @@ namespace ts { // Parses a comma-delimited list of elements function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimeter?: boolean): NodeArray { - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << kind; - let result = >[]; + const result = >[]; result.pos = getNodePos(); let commaStart = -1; // Meaning the previous token was not a comma @@ -1785,8 +1785,8 @@ namespace ts { } function createMissingList(): NodeArray { - let pos = getNodePos(); - let result = >[]; + const pos = getNodePos(); + const result = >[]; result.pos = pos; result.end = pos; return result; @@ -1794,7 +1794,7 @@ namespace ts { function parseBracketedList(kind: ParsingContext, parseElement: () => T, open: SyntaxKind, close: SyntaxKind): NodeArray { if (parseExpected(open)) { - let result = parseDelimitedList(kind, parseElement); + const result = parseDelimitedList(kind, parseElement); parseExpected(close); return result; } @@ -1806,7 +1806,7 @@ namespace ts { function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName { let entity: EntityName = parseIdentifier(diagnosticMessage); while (parseOptional(SyntaxKind.DotToken)) { - let node = createNode(SyntaxKind.QualifiedName, entity.pos); + const node = createNode(SyntaxKind.QualifiedName, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -1835,7 +1835,7 @@ namespace ts { // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token)) { - let matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -1849,12 +1849,12 @@ namespace ts { } function parseTemplateExpression(): TemplateExpression { - let template = createNode(SyntaxKind.TemplateExpression); + const template = createNode(SyntaxKind.TemplateExpression); template.head = parseLiteralNode(); Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind"); - let templateSpans = >[]; + const templateSpans = >[]; templateSpans.pos = getNodePos(); do { @@ -1869,7 +1869,7 @@ namespace ts { } function parseTemplateSpan(): TemplateSpan { - let span = createNode(SyntaxKind.TemplateSpan); + const span = createNode(SyntaxKind.TemplateSpan); span.expression = allowInAnd(parseExpression); let literal: LiteralExpression; @@ -1887,8 +1887,8 @@ namespace ts { } function parseLiteralNode(internName?: boolean): LiteralExpression { - let node = createNode(token); - let text = scanner.getTokenValue(); + const node = createNode(token); + const text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -1899,7 +1899,7 @@ namespace ts { node.isUnterminated = true; } - let tokenPos = scanner.getTokenPos(); + const tokenPos = scanner.getTokenPos(); nextToken(); finishNode(node); @@ -1922,15 +1922,15 @@ namespace ts { // TYPES function parseTypeReferenceOrTypePredicate(): TypeReferenceNode | TypePredicateNode { - let typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); + const typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); if (typeName.kind === SyntaxKind.Identifier && token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) { nextToken(); - let node = createNode(SyntaxKind.TypePredicate, typeName.pos); + const node = createNode(SyntaxKind.TypePredicate, typeName.pos); node.parameterName = typeName; node.type = parseType(); return finishNode(node); } - let node = createNode(SyntaxKind.TypeReference, typeName.pos); + const node = createNode(SyntaxKind.TypeReference, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); @@ -1939,14 +1939,14 @@ namespace ts { } function parseTypeQuery(): TypeQueryNode { - let node = createNode(SyntaxKind.TypeQuery); + const node = createNode(SyntaxKind.TypeQuery); parseExpected(SyntaxKind.TypeOfKeyword); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter(): TypeParameterDeclaration { - let node = createNode(SyntaxKind.TypeParameter); + const node = createNode(SyntaxKind.TypeParameter); node.name = parseIdentifier(); if (parseOptional(SyntaxKind.ExtendsKeyword)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -1999,7 +1999,7 @@ namespace ts { } function parseParameter(): ParameterDeclaration { - let node = createNode(SyntaxKind.Parameter); + const node = createNode(SyntaxKind.Parameter); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); @@ -2051,7 +2051,7 @@ namespace ts { requireCompleteParameterList: boolean, signature: SignatureDeclaration): void { - let returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; + const returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); @@ -2079,13 +2079,13 @@ namespace ts { // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt if (parseExpected(SyntaxKind.OpenParenToken)) { - let savedYieldContext = inYieldContext(); - let savedAwaitContext = inAwaitContext(); + const savedYieldContext = inYieldContext(); + const savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); setAwaitContext(awaitContext); - let result = parseDelimitedList(ParsingContext.Parameters, parseParameter); + const result = parseDelimitedList(ParsingContext.Parameters, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); @@ -2117,7 +2117,7 @@ namespace ts { } function parseSignatureMember(kind: SyntaxKind): SignatureDeclaration { - let node = createNode(kind); + const node = createNode(kind); if (kind === SyntaxKind.ConstructSignature) { parseExpected(SyntaxKind.NewKeyword); } @@ -2190,7 +2190,7 @@ namespace ts { } function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): IndexSignatureDeclaration { - let node = createNode(SyntaxKind.IndexSignature, fullStart); + const node = createNode(SyntaxKind.IndexSignature, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); @@ -2200,12 +2200,12 @@ namespace ts { } function parsePropertyOrMethodSignature(): Declaration { - let fullStart = scanner.getStartPos(); - let name = parsePropertyName(); - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const fullStart = scanner.getStartPos(); + const name = parsePropertyName(); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { - let method = createNode(SyntaxKind.MethodSignature, fullStart); + const method = createNode(SyntaxKind.MethodSignature, fullStart); method.name = name; method.questionToken = questionToken; @@ -2216,7 +2216,7 @@ namespace ts { return finishNode(method); } else { - let property = createNode(SyntaxKind.PropertySignature, fullStart); + const property = createNode(SyntaxKind.PropertySignature, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -2233,7 +2233,7 @@ namespace ts { return true; default: if (isModifier(token)) { - let result = lookAhead(isStartOfIndexSignatureDeclaration); + const result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; } @@ -2286,7 +2286,7 @@ namespace ts { // if it has the same text regardless of whether it is inside a class or an // object type. if (isModifier(token)) { - let result = tryParse(parseIndexSignatureWithModifiers); + const result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; } @@ -2299,9 +2299,9 @@ namespace ts { } function parseIndexSignatureWithModifiers() { - let fullStart = scanner.getStartPos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = scanner.getStartPos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); return isIndexSignature() ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) : undefined; @@ -2313,7 +2313,7 @@ namespace ts { } function parseTypeLiteral(): TypeLiteralNode { - let node = createNode(SyntaxKind.TypeLiteral); + const node = createNode(SyntaxKind.TypeLiteral); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -2332,13 +2332,13 @@ namespace ts { } function parseTupleType(): TupleTypeNode { - let node = createNode(SyntaxKind.TupleType); + const node = createNode(SyntaxKind.TupleType); node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); return finishNode(node); } function parseParenthesizedType(): ParenthesizedTypeNode { - let node = createNode(SyntaxKind.ParenthesizedType); + const node = createNode(SyntaxKind.ParenthesizedType); parseExpected(SyntaxKind.OpenParenToken); node.type = parseType(); parseExpected(SyntaxKind.CloseParenToken); @@ -2346,7 +2346,7 @@ namespace ts { } function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode { - let node = createNode(kind); + const node = createNode(kind); if (kind === SyntaxKind.ConstructorType) { parseExpected(SyntaxKind.NewKeyword); } @@ -2355,7 +2355,7 @@ namespace ts { } function parseKeywordAndNoDot(): TypeNode { - let node = parseTokenNode(); + const node = parseTokenNode(); return token === SyntaxKind.DotToken ? undefined : node; } @@ -2367,7 +2367,7 @@ namespace ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: // If these are followed by a dot, then parse these out as a dotted type reference instead. - let node = tryParse(parseKeywordAndNoDot); + const node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case SyntaxKind.VoidKeyword: case SyntaxKind.ThisKeyword: @@ -2418,7 +2418,7 @@ namespace ts { let type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) { parseExpected(SyntaxKind.CloseBracketToken); - let node = createNode(SyntaxKind.ArrayType, type.pos); + const node = createNode(SyntaxKind.ArrayType, type.pos); node.elementType = type; type = finishNode(node); } @@ -2428,13 +2428,13 @@ namespace ts { function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode { let type = parseConstituentType(); if (token === operator) { - let types = >[type]; + const types = >[type]; types.pos = type.pos; while (parseOptional(operator)) { types.push(parseConstituentType()); } types.end = getNodeEnd(); - let node = createNode(kind, type.pos); + const node = createNode(kind, type.pos); node.types = types; type = finishNode(node); } @@ -2588,7 +2588,7 @@ namespace ts { // Expression[in] , AssignmentExpression[in] // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } @@ -2649,7 +2649,7 @@ namespace ts { // parameter list. If we do, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - let arrowExpression = tryParseParenthesizedArrowFunctionExpression(); + const arrowExpression = tryParseParenthesizedArrowFunctionExpression(); if (arrowExpression) { return arrowExpression; } @@ -2663,7 +2663,7 @@ namespace ts { // Otherwise, we try to parse out the conditional expression bit. We want to allow any // binary expression here, so we pass in the 'lowest' precedence here so that it matches // and consumes anything. - let expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + const expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single @@ -2720,7 +2720,7 @@ namespace ts { } function parseYieldExpression(): YieldExpression { - let node = createNode(SyntaxKind.YieldExpression); + const node = createNode(SyntaxKind.YieldExpression); // YieldExpression[In] : // yield @@ -2744,9 +2744,9 @@ namespace ts { function parseSimpleArrowFunctionExpression(identifier: Identifier): Expression { Debug.assert(token === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - let node = createNode(SyntaxKind.ArrowFunction, identifier.pos); + const node = createNode(SyntaxKind.ArrowFunction, identifier.pos); - let parameter = createNode(SyntaxKind.Parameter, identifier.pos); + const parameter = createNode(SyntaxKind.Parameter, identifier.pos); parameter.name = identifier; finishNode(parameter); @@ -2761,7 +2761,7 @@ namespace ts { } function tryParseParenthesizedArrowFunctionExpression(): Expression { - let triState = isParenthesizedArrowFunctionExpression(); + const triState = isParenthesizedArrowFunctionExpression(); if (triState === Tristate.False) { // It's definitely not a parenthesized arrow function expression. return undefined; @@ -2771,7 +2771,7 @@ namespace ts { // following => or { token. Otherwise, we *might* have an arrow function. Try to parse // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. - let arrowFunction = triState === Tristate.True + const arrowFunction = triState === Tristate.True ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); @@ -2780,11 +2780,11 @@ namespace ts { return undefined; } - let isAsync = !!(arrowFunction.flags & NodeFlags.Async); + const isAsync = !!(arrowFunction.flags & NodeFlags.Async); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - let lastToken = token; + const lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken) ? parseArrowFunctionExpressionBody(isAsync) @@ -2823,8 +2823,8 @@ namespace ts { } } - let first = token; - let second = nextToken(); + const first = token; + const second = nextToken(); if (first === SyntaxKind.OpenParenToken) { if (second === SyntaxKind.CloseParenToken) { @@ -2832,7 +2832,7 @@ namespace ts { // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. - let third = nextToken(); + const third = nextToken(); switch (third) { case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.ColonToken: @@ -2875,7 +2875,7 @@ namespace ts { } // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. + // Return Unknown to const the caller know. return Tristate.Unknown; } else { @@ -2889,10 +2889,10 @@ namespace ts { // JSX overrides if (sourceFile.languageVariant === LanguageVariant.JSX) { - let isArrowFunctionInJsx = lookAhead(() => { - let third = nextToken(); + const isArrowFunctionInJsx = lookAhead(() => { + const third = nextToken(); if (third === SyntaxKind.ExtendsKeyword) { - let fourth = nextToken(); + const fourth = nextToken(); switch (fourth) { case SyntaxKind.EqualsToken: case SyntaxKind.GreaterThanToken: @@ -2924,9 +2924,9 @@ namespace ts { } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction { - let node = createNode(SyntaxKind.ArrowFunction); + const node = createNode(SyntaxKind.ArrowFunction); setModifiers(node, parseModifiersForArrowFunction()); - let isAsync = !!(node.flags & NodeFlags.Async); + const isAsync = !!(node.flags & NodeFlags.Async); // Arrow functions are never generators. // @@ -2974,7 +2974,7 @@ namespace ts { // user meant to supply a block. For example, if the user wrote: // // a => - // let v = 0; + // const v = 0; // } // // they may be missing an open brace. Check to see if that's the case so we can @@ -2992,14 +2992,14 @@ namespace ts { function parseConditionalExpressionRest(leftOperand: Expression): Expression { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - let node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); + const node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -3010,7 +3010,7 @@ namespace ts { } function parseBinaryExpressionOrHigher(precedence: number): Expression { - let leftOperand = parseUnaryExpressionOrHigher(); + const leftOperand = parseUnaryExpressionOrHigher(); return parseBinaryExpressionRest(precedence, leftOperand); } @@ -3024,7 +3024,7 @@ namespace ts { // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - let newPrecedence = getBinaryOperatorPrecedence(); + const newPrecedence = getBinaryOperatorPrecedence(); // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, @@ -3135,7 +3135,7 @@ namespace ts { } function makeBinaryExpression(left: Expression, operatorToken: Node, right: Expression): BinaryExpression { - let node = createNode(SyntaxKind.BinaryExpression, left.pos); + const node = createNode(SyntaxKind.BinaryExpression, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; @@ -3143,14 +3143,14 @@ namespace ts { } function makeAsExpression(left: Expression, right: TypeNode): AsExpression { - let node = createNode(SyntaxKind.AsExpression, left.pos); + const node = createNode(SyntaxKind.AsExpression, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - let node = createNode(SyntaxKind.PrefixUnaryExpression); + const node = createNode(SyntaxKind.PrefixUnaryExpression); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); @@ -3159,21 +3159,21 @@ namespace ts { } function parseDeleteExpression() { - let node = createNode(SyntaxKind.DeleteExpression); + const node = createNode(SyntaxKind.DeleteExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - let node = createNode(SyntaxKind.TypeOfExpression); + const node = createNode(SyntaxKind.TypeOfExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - let node = createNode(SyntaxKind.VoidExpression); + const node = createNode(SyntaxKind.VoidExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -3212,17 +3212,16 @@ namespace ts { } if (isIncrementExpression()) { - let incrementExpression = parseIncrementExpression(); + const incrementExpression = parseIncrementExpression(); return token === SyntaxKind.AsteriskAsteriskToken ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - let unaryOperator = token; - let simpleUnaryExpression = parseSimpleUnaryExpression(); + const unaryOperator = token; + const simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === SyntaxKind.AsteriskAsteriskToken) { - let diagnostic: Diagnostic; - let start = skipTrivia(sourceText, simpleUnaryExpression.pos); + const start = skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === SyntaxKind.TypeAssertionExpression) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } @@ -3316,7 +3315,7 @@ namespace ts { */ function parseIncrementExpression(): IncrementExpression { if (token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) { - let node = createNode(SyntaxKind.PrefixUnaryExpression); + const node = createNode(SyntaxKind.PrefixUnaryExpression); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -3327,11 +3326,11 @@ namespace ts { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } - let expression = parseLeftHandSideExpressionOrHigher(); + const expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); if ((token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) { - let node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); + const node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -3372,7 +3371,7 @@ namespace ts { // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - let expression = token === SyntaxKind.SuperKeyword + const expression = token === SyntaxKind.SuperKeyword ? parseSuperExpression() : parseMemberExpressionOrHigher(); @@ -3429,19 +3428,19 @@ namespace ts { // // Because CallExpression and MemberExpression are left recursive, we need to bottom out // of the recursion immediately. So we parse out a primary expression to start with. - let expression = parsePrimaryExpression(); + const expression = parsePrimaryExpression(); return parseMemberExpressionRest(expression); } function parseSuperExpression(): MemberExpression { - let expression = parseTokenNode(); + const expression = parseTokenNode(); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken || token === SyntaxKind.OpenBracketToken) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - let node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + const node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(SyntaxKind.DotToken, /*reportAtCurrentPosition*/ false, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -3449,10 +3448,10 @@ namespace ts { } function parseJsxElementOrSelfClosingElement(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement { - let opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + const opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); let result: JsxElement | JsxSelfClosingElement; if (opening.kind === SyntaxKind.JsxOpeningElement) { - let node = createNode(SyntaxKind.JsxElement, opening.pos); + const node = createNode(SyntaxKind.JsxElement, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); @@ -3473,10 +3472,10 @@ namespace ts { // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. if (inExpressionContext && token === SyntaxKind.LessThanToken) { - let invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/true)); + const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/true)); if (invalidElement) { parseErrorAtCurrentToken(Diagnostics.JSX_expressions_must_have_one_parent_element); - let badNode = createNode(SyntaxKind.BinaryExpression, result.pos); + const badNode = createNode(SyntaxKind.BinaryExpression, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -3490,7 +3489,7 @@ namespace ts { } function parseJsxText(): JsxText { - let node = createNode(SyntaxKind.JsxText, scanner.getStartPos()); + const node = createNode(SyntaxKind.JsxText, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } @@ -3508,9 +3507,9 @@ namespace ts { } function parseJsxChildren(openingTagName: EntityName): NodeArray { - let result = >[]; + const result = >[]; result.pos = scanner.getStartPos(); - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << ParsingContext.JsxChildren; while (true) { @@ -3533,13 +3532,13 @@ namespace ts { } function parseJsxOpeningOrSelfClosingElement(inExpressionContext: boolean): JsxOpeningElement | JsxSelfClosingElement { - let fullStart = scanner.getStartPos(); + const fullStart = scanner.getStartPos(); parseExpected(SyntaxKind.LessThanToken); - let tagName = parseJsxElementName(); + const tagName = parseJsxElementName(); - let attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute); + const attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute); let node: JsxOpeningLikeElement; if (token === SyntaxKind.GreaterThanToken) { @@ -3572,7 +3571,7 @@ namespace ts { let elementName: EntityName = parseIdentifierName(); while (parseOptional(SyntaxKind.DotToken)) { scanJsxIdentifier(); - let node = createNode(SyntaxKind.QualifiedName, elementName.pos); + const node = createNode(SyntaxKind.QualifiedName, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -3581,7 +3580,7 @@ namespace ts { } function parseJsxExpression(inExpressionContext: boolean): JsxExpression { - let node = createNode(SyntaxKind.JsxExpression); + const node = createNode(SyntaxKind.JsxExpression); parseExpected(SyntaxKind.OpenBraceToken); if (token !== SyntaxKind.CloseBraceToken) { @@ -3604,7 +3603,7 @@ namespace ts { } scanJsxIdentifier(); - let node = createNode(SyntaxKind.JsxAttribute); + const node = createNode(SyntaxKind.JsxAttribute); node.name = parseIdentifierName(); if (parseOptional(SyntaxKind.EqualsToken)) { switch (token) { @@ -3620,7 +3619,7 @@ namespace ts { } function parseJsxSpreadAttribute(): JsxSpreadAttribute { - let node = createNode(SyntaxKind.JsxSpreadAttribute); + const node = createNode(SyntaxKind.JsxSpreadAttribute); parseExpected(SyntaxKind.OpenBraceToken); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseExpression(); @@ -3629,7 +3628,7 @@ namespace ts { } function parseJsxClosingElement(inExpressionContext: boolean): JsxClosingElement { - let node = createNode(SyntaxKind.JsxClosingElement); + const node = createNode(SyntaxKind.JsxClosingElement); parseExpected(SyntaxKind.LessThanSlashToken); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -3643,7 +3642,7 @@ namespace ts { } function parseTypeAssertion(): TypeAssertion { - let node = createNode(SyntaxKind.TypeAssertionExpression); + const node = createNode(SyntaxKind.TypeAssertionExpression); parseExpected(SyntaxKind.LessThanToken); node.type = parseType(); parseExpected(SyntaxKind.GreaterThanToken); @@ -3653,9 +3652,9 @@ namespace ts { function parseMemberExpressionRest(expression: LeftHandSideExpression): MemberExpression { while (true) { - let dotToken = parseOptionalToken(SyntaxKind.DotToken); + const dotToken = parseOptionalToken(SyntaxKind.DotToken); if (dotToken) { - let propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + const propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -3665,7 +3664,7 @@ namespace ts { // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) { - let indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); + const indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". @@ -3673,7 +3672,7 @@ namespace ts { if (token !== SyntaxKind.CloseBracketToken) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === SyntaxKind.StringLiteral || indexedAccess.argumentExpression.kind === SyntaxKind.NumericLiteral) { - let literal = indexedAccess.argumentExpression; + const literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } @@ -3684,7 +3683,7 @@ namespace ts { } if (token === SyntaxKind.NoSubstitutionTemplateLiteral || token === SyntaxKind.TemplateHead) { - let tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); + const tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); tagExpression.tag = expression; tagExpression.template = token === SyntaxKind.NoSubstitutionTemplateLiteral ? parseLiteralNode() @@ -3705,12 +3704,12 @@ namespace ts { // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the // stack. - let typeArguments = tryParse(parseTypeArgumentsInExpression); + const typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + const callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -3718,7 +3717,7 @@ namespace ts { continue; } else if (token === SyntaxKind.OpenParenToken) { - let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + const callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -3731,7 +3730,7 @@ namespace ts { function parseArgumentList() { parseExpected(SyntaxKind.OpenParenToken); - let result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); + const result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); parseExpected(SyntaxKind.CloseParenToken); return result; } @@ -3741,7 +3740,7 @@ namespace ts { return undefined; } - let typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); + const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); if (!parseExpected(SyntaxKind.GreaterThanToken)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; @@ -3841,7 +3840,7 @@ namespace ts { } function parseParenthesizedExpression(): ParenthesizedExpression { - let node = createNode(SyntaxKind.ParenthesizedExpression); + const node = createNode(SyntaxKind.ParenthesizedExpression); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); @@ -3849,7 +3848,7 @@ namespace ts { } function parseSpreadElement(): Expression { - let node = createNode(SyntaxKind.SpreadElementExpression); + const node = createNode(SyntaxKind.SpreadElementExpression); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -3866,7 +3865,7 @@ namespace ts { } function parseArrayLiteralExpression(): ArrayLiteralExpression { - let node = createNode(SyntaxKind.ArrayLiteralExpression); + const node = createNode(SyntaxKind.ArrayLiteralExpression); parseExpected(SyntaxKind.OpenBracketToken); if (scanner.hasPrecedingLineBreak()) node.flags |= NodeFlags.MultiLine; node.elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement); @@ -3886,22 +3885,22 @@ namespace ts { } function parseObjectLiteralElement(): ObjectLiteralElement { - let fullStart = scanner.getStartPos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = scanner.getStartPos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); - let accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + const accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let tokenIsIdentifier = isIdentifier(); - let nameToken = token; - let propertyName = parsePropertyName(); + const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + const tokenIsIdentifier = isIdentifier(); + const nameToken = token; + const propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } @@ -3915,7 +3914,7 @@ namespace ts { tokenIsIdentifier && (token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBraceToken || token === SyntaxKind.EqualsToken); if (isShorthandPropertyAssignment) { - let shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); + const shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; const equalsToken = parseOptionalToken(SyntaxKind.EqualsToken); @@ -3926,7 +3925,7 @@ namespace ts { return finishNode(shorthandDeclaration); } else { - let propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); + const propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(SyntaxKind.ColonToken); @@ -3936,7 +3935,7 @@ namespace ts { } function parseObjectLiteralExpression(): ObjectLiteralExpression { - let node = createNode(SyntaxKind.ObjectLiteralExpression); + const node = createNode(SyntaxKind.ObjectLiteralExpression); parseExpected(SyntaxKind.OpenBraceToken); if (scanner.hasPrecedingLineBreak()) { node.flags |= NodeFlags.MultiLine; @@ -3953,18 +3952,18 @@ namespace ts { // // FunctionExpression: // function BindingIdentifier[opt](FormalParameters){ FunctionBody } - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } - let node = createNode(SyntaxKind.FunctionExpression); + const node = createNode(SyntaxKind.FunctionExpression); setModifiers(node, parseModifiers()); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let isGenerator = !!node.asteriskToken; - let isAsync = !!(node.flags & NodeFlags.Async); + const isGenerator = !!node.asteriskToken; + const isAsync = !!(node.flags & NodeFlags.Async); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -3986,7 +3985,7 @@ namespace ts { } function parseNewExpression(): NewExpression { - let node = createNode(SyntaxKind.NewExpression); + const node = createNode(SyntaxKind.NewExpression); parseExpected(SyntaxKind.NewKeyword); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -3999,7 +3998,7 @@ namespace ts { // STATEMENTS function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { - let node = createNode(SyntaxKind.Block); + const node = createNode(SyntaxKind.Block); if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4011,20 +4010,20 @@ namespace ts { } function parseFunctionBlock(allowYield: boolean, allowAwait: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { - let savedYieldContext = inYieldContext(); + const savedYieldContext = inYieldContext(); setYieldContext(allowYield); - let savedAwaitContext = inAwaitContext(); + const savedAwaitContext = inAwaitContext(); setAwaitContext(allowAwait); // We may be in a [Decorator] context when parsing a function expression or // arrow function. The body of the function is not in [Decorator] context. - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } - let block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); + const block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); @@ -4037,13 +4036,13 @@ namespace ts { } function parseEmptyStatement(): Statement { - let node = createNode(SyntaxKind.EmptyStatement); + const node = createNode(SyntaxKind.EmptyStatement); parseExpected(SyntaxKind.SemicolonToken); return finishNode(node); } function parseIfStatement(): IfStatement { - let node = createNode(SyntaxKind.IfStatement); + const node = createNode(SyntaxKind.IfStatement); parseExpected(SyntaxKind.IfKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4054,7 +4053,7 @@ namespace ts { } function parseDoStatement(): DoStatement { - let node = createNode(SyntaxKind.DoStatement); + const node = createNode(SyntaxKind.DoStatement); parseExpected(SyntaxKind.DoKeyword); node.statement = parseStatement(); parseExpected(SyntaxKind.WhileKeyword); @@ -4071,7 +4070,7 @@ namespace ts { } function parseWhileStatement(): WhileStatement { - let node = createNode(SyntaxKind.WhileStatement); + const node = createNode(SyntaxKind.WhileStatement); parseExpected(SyntaxKind.WhileKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4081,7 +4080,7 @@ namespace ts { } function parseForOrForInOrForOfStatement(): Statement { - let pos = getNodePos(); + const pos = getNodePos(); parseExpected(SyntaxKind.ForKeyword); parseExpected(SyntaxKind.OpenParenToken); @@ -4096,21 +4095,21 @@ namespace ts { } let forOrForInOrForOfStatement: IterationStatement; if (parseOptional(SyntaxKind.InKeyword)) { - let forInStatement = createNode(SyntaxKind.ForInStatement, pos); + const forInStatement = createNode(SyntaxKind.ForInStatement, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(SyntaxKind.OfKeyword)) { - let forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); + const forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forOfStatement; } else { - let forStatement = createNode(SyntaxKind.ForStatement, pos); + const forStatement = createNode(SyntaxKind.ForStatement, pos); forStatement.initializer = initializer; parseExpected(SyntaxKind.SemicolonToken); if (token !== SyntaxKind.SemicolonToken && token !== SyntaxKind.CloseParenToken) { @@ -4130,7 +4129,7 @@ namespace ts { } function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement { - let node = createNode(kind); + const node = createNode(kind); parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword); if (!canParseSemicolon()) { @@ -4142,7 +4141,7 @@ namespace ts { } function parseReturnStatement(): ReturnStatement { - let node = createNode(SyntaxKind.ReturnStatement); + const node = createNode(SyntaxKind.ReturnStatement); parseExpected(SyntaxKind.ReturnKeyword); if (!canParseSemicolon()) { @@ -4154,7 +4153,7 @@ namespace ts { } function parseWithStatement(): WithStatement { - let node = createNode(SyntaxKind.WithStatement); + const node = createNode(SyntaxKind.WithStatement); parseExpected(SyntaxKind.WithKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4164,7 +4163,7 @@ namespace ts { } function parseCaseClause(): CaseClause { - let node = createNode(SyntaxKind.CaseClause); + const node = createNode(SyntaxKind.CaseClause); parseExpected(SyntaxKind.CaseKeyword); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.ColonToken); @@ -4173,7 +4172,7 @@ namespace ts { } function parseDefaultClause(): DefaultClause { - let node = createNode(SyntaxKind.DefaultClause); + const node = createNode(SyntaxKind.DefaultClause); parseExpected(SyntaxKind.DefaultKeyword); parseExpected(SyntaxKind.ColonToken); node.statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); @@ -4185,12 +4184,12 @@ namespace ts { } function parseSwitchStatement(): SwitchStatement { - let node = createNode(SyntaxKind.SwitchStatement); + const node = createNode(SyntaxKind.SwitchStatement); parseExpected(SyntaxKind.SwitchKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); - let caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); + const caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); parseExpected(SyntaxKind.OpenBraceToken); caseBlock.clauses = parseList(ParsingContext.SwitchClauses, parseCaseOrDefaultClause); parseExpected(SyntaxKind.CloseBraceToken); @@ -4207,7 +4206,7 @@ namespace ts { // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - let node = createNode(SyntaxKind.ThrowStatement); + const node = createNode(SyntaxKind.ThrowStatement); parseExpected(SyntaxKind.ThrowKeyword); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -4216,7 +4215,7 @@ namespace ts { // TODO: Review for error recovery function parseTryStatement(): TryStatement { - let node = createNode(SyntaxKind.TryStatement); + const node = createNode(SyntaxKind.TryStatement); parseExpected(SyntaxKind.TryKeyword); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); @@ -4233,7 +4232,7 @@ namespace ts { } function parseCatchClause(): CatchClause { - let result = createNode(SyntaxKind.CatchClause); + const result = createNode(SyntaxKind.CatchClause); parseExpected(SyntaxKind.CatchKeyword); if (parseExpected(SyntaxKind.OpenParenToken)) { result.variableDeclaration = parseVariableDeclaration(); @@ -4245,7 +4244,7 @@ namespace ts { } function parseDebuggerStatement(): Statement { - let node = createNode(SyntaxKind.DebuggerStatement); + const node = createNode(SyntaxKind.DebuggerStatement); parseExpected(SyntaxKind.DebuggerKeyword); parseSemicolon(); return finishNode(node); @@ -4255,17 +4254,17 @@ namespace ts { // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. - let fullStart = scanner.getStartPos(); - let expression = allowInAnd(parseExpression); + const fullStart = scanner.getStartPos(); + const expression = allowInAnd(parseExpression); if (expression.kind === SyntaxKind.Identifier && parseOptional(SyntaxKind.ColonToken)) { - let labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); + const labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - let expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); + const expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -4499,9 +4498,9 @@ namespace ts { } function parseDeclaration(): Statement { - let fullStart = getNodePos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = getNodePos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); switch (token) { case SyntaxKind.VarKeyword: case SyntaxKind.LetKeyword: @@ -4531,7 +4530,7 @@ namespace ts { if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - let node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -4560,7 +4559,7 @@ namespace ts { if (token === SyntaxKind.CommaToken) { return createNode(SyntaxKind.OmittedExpression); } - let node = createNode(SyntaxKind.BindingElement); + const node = createNode(SyntaxKind.BindingElement); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); @@ -4568,9 +4567,9 @@ namespace ts { } function parseObjectBindingElement(): BindingElement { - let node = createNode(SyntaxKind.BindingElement); - let tokenIsIdentifier = isIdentifier(); - let propertyName = parsePropertyName(); + const node = createNode(SyntaxKind.BindingElement); + const tokenIsIdentifier = isIdentifier(); + const propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== SyntaxKind.ColonToken) { node.name = propertyName; } @@ -4584,7 +4583,7 @@ namespace ts { } function parseObjectBindingPattern(): BindingPattern { - let node = createNode(SyntaxKind.ObjectBindingPattern); + const node = createNode(SyntaxKind.ObjectBindingPattern); parseExpected(SyntaxKind.OpenBraceToken); node.elements = parseDelimitedList(ParsingContext.ObjectBindingElements, parseObjectBindingElement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4592,7 +4591,7 @@ namespace ts { } function parseArrayBindingPattern(): BindingPattern { - let node = createNode(SyntaxKind.ArrayBindingPattern); + const node = createNode(SyntaxKind.ArrayBindingPattern); parseExpected(SyntaxKind.OpenBracketToken); node.elements = parseDelimitedList(ParsingContext.ArrayBindingElements, parseArrayBindingElement); parseExpected(SyntaxKind.CloseBracketToken); @@ -4614,7 +4613,7 @@ namespace ts { } function parseVariableDeclaration(): VariableDeclaration { - let node = createNode(SyntaxKind.VariableDeclaration); + const node = createNode(SyntaxKind.VariableDeclaration); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -4624,7 +4623,7 @@ namespace ts { } function parseVariableDeclarationList(inForStatementInitializer: boolean): VariableDeclarationList { - let node = createNode(SyntaxKind.VariableDeclarationList); + const node = createNode(SyntaxKind.VariableDeclarationList); switch (token) { case SyntaxKind.VarKeyword: @@ -4654,7 +4653,7 @@ namespace ts { node.declarations = createMissingList(); } else { - let savedDisallowIn = inDisallowInContext(); + const savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); node.declarations = parseDelimitedList(ParsingContext.VariableDeclarations, parseVariableDeclaration); @@ -4670,7 +4669,7 @@ namespace ts { } function parseVariableStatement(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): VariableStatement { - let node = createNode(SyntaxKind.VariableStatement, fullStart); + const node = createNode(SyntaxKind.VariableStatement, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -4679,21 +4678,21 @@ namespace ts { } function parseFunctionDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): FunctionDeclaration { - let node = createNode(SyntaxKind.FunctionDeclaration, fullStart); + const node = createNode(SyntaxKind.FunctionDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier(); - let isGenerator = !!node.asteriskToken; - let isAsync = !!(node.flags & NodeFlags.Async); + const isGenerator = !!node.asteriskToken; + const isAsync = !!(node.flags & NodeFlags.Async); fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(pos: number, decorators: NodeArray, modifiers: ModifiersArray): ConstructorDeclaration { - let node = createNode(SyntaxKind.Constructor, pos); + const node = createNode(SyntaxKind.Constructor, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ConstructorKeyword); @@ -4703,21 +4702,21 @@ namespace ts { } function parseMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { - let method = createNode(SyntaxKind.MethodDeclaration, fullStart); + const method = createNode(SyntaxKind.MethodDeclaration, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; - let isGenerator = !!asteriskToken; - let isAsync = !!(method.flags & NodeFlags.Async); + const isGenerator = !!asteriskToken; + const isAsync = !!(method.flags & NodeFlags.Async); fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); } function parsePropertyDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, name: DeclarationName, questionToken: Node): ClassElement { - let property = createNode(SyntaxKind.PropertyDeclaration, fullStart); + const property = createNode(SyntaxKind.PropertyDeclaration, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; @@ -4742,12 +4741,12 @@ namespace ts { } function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ClassElement { - let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let name = parsePropertyName(); + const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + const name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, Diagnostics.or_expected); } @@ -4761,7 +4760,7 @@ namespace ts { } function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): AccessorDeclaration { - let node = createNode(kind, fullStart); + const node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parsePropertyName(); @@ -4853,7 +4852,7 @@ namespace ts { function parseDecorators(): NodeArray { let decorators: NodeArray; while (true) { - let decoratorStart = getNodePos(); + const decoratorStart = getNodePos(); if (!parseOptional(SyntaxKind.AtToken)) { break; } @@ -4863,7 +4862,7 @@ namespace ts { decorators.pos = scanner.getStartPos(); } - let decorator = createNode(SyntaxKind.Decorator, decoratorStart); + const decorator = createNode(SyntaxKind.Decorator, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -4877,8 +4876,8 @@ namespace ts { let flags = 0; let modifiers: ModifiersArray; while (true) { - let modifierStart = scanner.getStartPos(); - let modifierKind = token; + const modifierStart = scanner.getStartPos(); + const modifierKind = token; if (!parseAnyContextualModifier()) { break; @@ -4903,8 +4902,8 @@ namespace ts { let flags = 0; let modifiers: ModifiersArray; if (token === SyntaxKind.AsyncKeyword) { - let modifierStart = scanner.getStartPos(); - let modifierKind = token; + const modifierStart = scanner.getStartPos(); + const modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -4919,16 +4918,16 @@ namespace ts { function parseClassElement(): ClassElement { if (token === SyntaxKind.SemicolonToken) { - let result = createNode(SyntaxKind.SemicolonClassElement); + const result = createNode(SyntaxKind.SemicolonClassElement); nextToken(); return finishNode(result); } - let fullStart = getNodePos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = getNodePos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); - let accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + const accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } @@ -4954,7 +4953,7 @@ namespace ts { if (decorators || modifiers) { // treat this as a property declaration with a missing name. - let name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); } @@ -4975,7 +4974,7 @@ namespace ts { } function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration { - let node = createNode(kind, fullStart); + const node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ClassKeyword); @@ -5028,7 +5027,7 @@ namespace ts { function parseHeritageClause() { if (token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword) { - let node = createNode(SyntaxKind.HeritageClause); + const node = createNode(SyntaxKind.HeritageClause); node.token = token; nextToken(); node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments); @@ -5039,7 +5038,7 @@ namespace ts { } function parseExpressionWithTypeArguments(): ExpressionWithTypeArguments { - let node = createNode(SyntaxKind.ExpressionWithTypeArguments); + const node = createNode(SyntaxKind.ExpressionWithTypeArguments); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); @@ -5057,7 +5056,7 @@ namespace ts { } function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): InterfaceDeclaration { - let node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); + const node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.InterfaceKeyword); @@ -5069,7 +5068,7 @@ namespace ts { } function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): TypeAliasDeclaration { - let node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); + const node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.TypeKeyword); @@ -5086,14 +5085,14 @@ namespace ts { // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember(): EnumMember { - let node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); + const node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): EnumDeclaration { - let node = createNode(SyntaxKind.EnumDeclaration, fullStart); + const node = createNode(SyntaxKind.EnumDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.EnumKeyword); @@ -5109,7 +5108,7 @@ namespace ts { } function parseModuleBlock(): ModuleBlock { - let node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); + const node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); if (parseExpected(SyntaxKind.OpenBraceToken)) { node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); @@ -5121,10 +5120,10 @@ namespace ts { } function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration { - let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + const node = createNode(SyntaxKind.ModuleDeclaration, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - let namespaceFlag = flags & NodeFlags.Namespace; + const namespaceFlag = flags & NodeFlags.Namespace; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -5136,7 +5135,7 @@ namespace ts { } function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ModuleDeclaration { - let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + const node = createNode(SyntaxKind.ModuleDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(/*internName*/ true); @@ -5179,7 +5178,7 @@ namespace ts { function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration { parseExpected(SyntaxKind.ImportKeyword); - let afterImportPos = scanner.getStartPos(); + const afterImportPos = scanner.getStartPos(); let identifier: Identifier; if (isIdentifier()) { @@ -5188,7 +5187,7 @@ namespace ts { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - let importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); + const importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -5200,7 +5199,7 @@ namespace ts { } // Import statement - let importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); + const importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); @@ -5227,7 +5226,7 @@ namespace ts { // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - let importClause = createNode(SyntaxKind.ImportClause, fullStart); + const importClause = createNode(SyntaxKind.ImportClause, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -5251,7 +5250,7 @@ namespace ts { } function parseExternalModuleReference() { - let node = createNode(SyntaxKind.ExternalModuleReference); + const node = createNode(SyntaxKind.ExternalModuleReference); parseExpected(SyntaxKind.RequireKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = parseModuleSpecifier(); @@ -5263,7 +5262,7 @@ namespace ts { // We allow arbitrary expressions here, even though the grammar only allows string // literals. We check to ensure that it is only a string literal later in the grammar // walker. - let result = parseExpression(); + const result = parseExpression(); // Ensure the string being required is in our 'identifier' table. This will ensure // that features like 'find refs' will look inside this file when search for its name. if (result.kind === SyntaxKind.StringLiteral) { @@ -5275,7 +5274,7 @@ namespace ts { function parseNamespaceImport(): NamespaceImport { // NameSpaceImport: // * as ImportedBinding - let namespaceImport = createNode(SyntaxKind.NamespaceImport); + const namespaceImport = createNode(SyntaxKind.NamespaceImport); parseExpected(SyntaxKind.AsteriskToken); parseExpected(SyntaxKind.AsKeyword); namespaceImport.name = parseIdentifier(); @@ -5283,7 +5282,7 @@ namespace ts { } function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports { - let node = createNode(kind); + const node = createNode(kind); // NamedImports: // { } @@ -5308,7 +5307,7 @@ namespace ts { } function parseImportOrExportSpecifier(kind: SyntaxKind): ImportOrExportSpecifier { - let node = createNode(kind); + const node = createNode(kind); // ImportSpecifier: // BindingIdentifier // IdentifierName as BindingIdentifier @@ -5318,7 +5317,7 @@ namespace ts { let checkIdentifierIsKeyword = isKeyword(token) && !isIdentifier(); let checkIdentifierStart = scanner.getTokenPos(); let checkIdentifierEnd = scanner.getTextPos(); - let identifierName = parseIdentifierName(); + const identifierName = parseIdentifierName(); if (token === SyntaxKind.AsKeyword) { node.propertyName = identifierName; parseExpected(SyntaxKind.AsKeyword); @@ -5338,7 +5337,7 @@ namespace ts { } function parseExportDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ExportDeclaration { - let node = createNode(SyntaxKind.ExportDeclaration, fullStart); + const node = createNode(SyntaxKind.ExportDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(SyntaxKind.AsteriskToken)) { @@ -5361,7 +5360,7 @@ namespace ts { } function parseExportAssignment(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ExportAssignment { - let node = createNode(SyntaxKind.ExportAssignment, fullStart); + const node = createNode(SyntaxKind.ExportAssignment, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(SyntaxKind.EqualsToken)) { @@ -5376,16 +5375,16 @@ namespace ts { } function processReferenceComments(sourceFile: SourceFile): void { - let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText); - let referencedFiles: FileReference[] = []; - let amdDependencies: { path: string; name: string }[] = []; + const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText); + const referencedFiles: FileReference[] = []; + const amdDependencies: { path: string; name: string }[] = []; let amdModuleName: string; // Keep scanning all the leading trivia in the file until we get to something that // isn't trivia. Any single line comment will be analyzed to see if it is a // reference comment. while (true) { - let kind = triviaScanner.scan(); + const kind = triviaScanner.scan(); if (kind === SyntaxKind.WhitespaceTrivia || kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.MultiLineCommentTrivia) { continue; } @@ -5393,14 +5392,14 @@ namespace ts { break; } - let range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; + const range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; - let comment = sourceText.substring(range.pos, range.end); - let referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); + const comment = sourceText.substring(range.pos, range.end); + const referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); if (referencePathMatchResult) { - let fileReference = referencePathMatchResult.fileReference; + const fileReference = referencePathMatchResult.fileReference; sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - let diagnosticMessage = referencePathMatchResult.diagnosticMessage; + const diagnosticMessage = referencePathMatchResult.diagnosticMessage; if (fileReference) { referencedFiles.push(fileReference); } @@ -5409,8 +5408,8 @@ namespace ts { } } else { - let amdModuleNameRegEx = /^\/\/\/\s*createNode(SyntaxKind.JSDocTypeExpression); + const result = createNode(SyntaxKind.JSDocTypeExpression); parseExpected(SyntaxKind.OpenBraceToken); result.type = parseJSDocTopLevelType(); @@ -5535,13 +5534,13 @@ namespace ts { function parseJSDocTopLevelType(): JSDocType { let type = parseJSDocType(); if (token === SyntaxKind.BarToken) { - let unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); + const unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === SyntaxKind.EqualsToken) { - let optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); + const optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -5555,7 +5554,7 @@ namespace ts { while (true) { if (token === SyntaxKind.OpenBracketToken) { - let arrayType = createNode(SyntaxKind.JSDocArrayType, type.pos); + const arrayType = createNode(SyntaxKind.JSDocArrayType, type.pos); arrayType.elementType = type; nextToken(); @@ -5564,14 +5563,14 @@ namespace ts { type = finishNode(arrayType); } else if (token === SyntaxKind.QuestionToken) { - let nullableType = createNode(SyntaxKind.JSDocNullableType, type.pos); + const nullableType = createNode(SyntaxKind.JSDocNullableType, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === SyntaxKind.ExclamationToken) { - let nonNullableType = createNode(SyntaxKind.JSDocNonNullableType, type.pos); + const nonNullableType = createNode(SyntaxKind.JSDocNonNullableType, type.pos); nonNullableType.type = type; nextToken(); @@ -5620,7 +5619,7 @@ namespace ts { } function parseJSDocThisType(): JSDocThisType { - let result = createNode(SyntaxKind.JSDocThisType); + const result = createNode(SyntaxKind.JSDocThisType); nextToken(); parseExpected(SyntaxKind.ColonToken); result.type = parseJSDocType(); @@ -5628,7 +5627,7 @@ namespace ts { } function parseJSDocConstructorType(): JSDocConstructorType { - let result = createNode(SyntaxKind.JSDocConstructorType); + const result = createNode(SyntaxKind.JSDocConstructorType); nextToken(); parseExpected(SyntaxKind.ColonToken); result.type = parseJSDocType(); @@ -5636,14 +5635,14 @@ namespace ts { } function parseJSDocVariadicType(): JSDocVariadicType { - let result = createNode(SyntaxKind.JSDocVariadicType); + const result = createNode(SyntaxKind.JSDocVariadicType); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType(): JSDocFunctionType { - let result = createNode(SyntaxKind.JSDocFunctionType); + const result = createNode(SyntaxKind.JSDocFunctionType); nextToken(); parseExpected(SyntaxKind.OpenParenToken); @@ -5660,20 +5659,20 @@ namespace ts { } function parseJSDocParameter(): ParameterDeclaration { - let parameter = createNode(SyntaxKind.Parameter); + const parameter = createNode(SyntaxKind.Parameter); parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocOptionalType(type: JSDocType): JSDocOptionalType { - let result = createNode(SyntaxKind.JSDocOptionalType, type.pos); + const result = createNode(SyntaxKind.JSDocOptionalType, type.pos); nextToken(); result.type = type; return finishNode(result); } function parseJSDocTypeReference(): JSDocTypeReference { - let result = createNode(SyntaxKind.JSDocTypeReference); + const result = createNode(SyntaxKind.JSDocTypeReference); result.name = parseSimplePropertyName(); while (parseOptional(SyntaxKind.DotToken)) { @@ -5692,7 +5691,7 @@ namespace ts { function parseTypeArguments() { // Move past the < nextToken(); - let typeArguments = parseDelimitedList(ParsingContext.JSDocTypeArguments, parseJSDocType); + const typeArguments = parseDelimitedList(ParsingContext.JSDocTypeArguments, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); parseExpected(SyntaxKind.GreaterThanToken); @@ -5702,14 +5701,14 @@ namespace ts { function checkForEmptyTypeArgumentList(typeArguments: NodeArray) { if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { - let start = typeArguments.pos - "<".length; - let end = skipTrivia(sourceText, typeArguments.end) + ">".length; + const start = typeArguments.pos - "<".length; + const end = skipTrivia(sourceText, typeArguments.end) + ">".length; return parseErrorAtPosition(start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); } } function parseQualifiedName(left: EntityName): QualifiedName { - let result = createNode(SyntaxKind.QualifiedName, left.pos); + const result = createNode(SyntaxKind.QualifiedName, left.pos); result.left = left; result.right = parseIdentifierName(); @@ -5717,7 +5716,7 @@ namespace ts { } function parseJSDocRecordType(): JSDocRecordType { - let result = createNode(SyntaxKind.JSDocRecordType); + const result = createNode(SyntaxKind.JSDocRecordType); nextToken(); result.members = parseDelimitedList(ParsingContext.JSDocRecordMembers, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -5726,7 +5725,7 @@ namespace ts { } function parseJSDocRecordMember(): JSDocRecordMember { - let result = createNode(SyntaxKind.JSDocRecordMember); + const result = createNode(SyntaxKind.JSDocRecordMember); result.name = parseSimplePropertyName(); if (token === SyntaxKind.ColonToken) { @@ -5738,14 +5737,14 @@ namespace ts { } function parseJSDocNonNullableType(): JSDocNonNullableType { - let result = createNode(SyntaxKind.JSDocNonNullableType); + const result = createNode(SyntaxKind.JSDocNonNullableType); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType(): JSDocTupleType { - let result = createNode(SyntaxKind.JSDocTupleType); + const result = createNode(SyntaxKind.JSDocTupleType); nextToken(); result.types = parseDelimitedList(ParsingContext.JSDocTupleTypes, parseJSDocType); checkForTrailingComma(result.types); @@ -5756,13 +5755,13 @@ namespace ts { function checkForTrailingComma(list: NodeArray) { if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - let start = list.end - ",".length; + const start = list.end - ",".length; parseErrorAtPosition(start, ",".length, Diagnostics.Trailing_comma_not_allowed); } } function parseJSDocUnionType(): JSDocUnionType { - let result = createNode(SyntaxKind.JSDocUnionType); + const result = createNode(SyntaxKind.JSDocUnionType); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); @@ -5774,7 +5773,7 @@ namespace ts { function parseJSDocTypeList(firstType: JSDocType) { Debug.assert(!!firstType); - let types = >[]; + const types = >[]; types.pos = firstType.pos; types.push(firstType); @@ -5787,13 +5786,13 @@ namespace ts { } function parseJSDocAllType(): JSDocAllType { - let result = createNode(SyntaxKind.JSDocAllType); + const result = createNode(SyntaxKind.JSDocAllType); nextToken(); return finishNode(result); } function parseJSDocUnknownOrNullableType(): JSDocUnknownType | JSDocNullableType { - let pos = scanner.getStartPos(); + const pos = scanner.getStartPos(); // skip the ? nextToken(); @@ -5814,11 +5813,11 @@ namespace ts { token === SyntaxKind.EqualsToken || token === SyntaxKind.BarToken) { - let result = createNode(SyntaxKind.JSDocUnknownType, pos); + const result = createNode(SyntaxKind.JSDocUnknownType, pos); return finishNode(result); } else { - let result = createNode(SyntaxKind.JSDocNullableType, pos); + const result = createNode(SyntaxKind.JSDocNullableType, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -5826,15 +5825,15 @@ namespace ts { export function parseIsolatedJSDocComment(content: string, start: number, length: number) { initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined); - let jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); - let diagnostics = parseDiagnostics; + const jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); + const diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment, diagnostics } : undefined; } export function parseJSDocComment(parent: Node, start: number, length: number): JSDocComment { - let comment = parseJSDocCommentWorker(start, length); + const comment = parseJSDocCommentWorker(start, length); if (comment) { fixupParentReferences(comment); comment.parent = parent; @@ -5844,9 +5843,9 @@ namespace ts { } export function parseJSDocCommentWorker(start: number, length: number): JSDocComment { - let content = sourceText; + const content = sourceText; start = start || 0; - let end = length === undefined ? content.length : start + length; + const end = length === undefined ? content.length : start + length; length = end - start; Debug.assert(start >= 0); @@ -5873,7 +5872,7 @@ namespace ts { let seenAsterisk = true; for (pos = start + "/**".length; pos < end; ) { - let ch = content.charCodeAt(pos); + const ch = content.charCodeAt(pos); pos++; if (ch === CharacterCodes.at && canParseTag) { @@ -5923,7 +5922,7 @@ namespace ts { return undefined; } - let result = createNode(SyntaxKind.JSDocComment, start); + const result = createNode(SyntaxKind.JSDocComment, start); result.tags = tags; return finishNode(result, end); } @@ -5936,15 +5935,15 @@ namespace ts { function parseTag(): void { Debug.assert(content.charCodeAt(pos - 1) === CharacterCodes.at); - let atToken = createNode(SyntaxKind.AtToken, pos - 1); + const atToken = createNode(SyntaxKind.AtToken, pos - 1); atToken.end = pos; - let tagName = scanIdentifier(); + const tagName = scanIdentifier(); if (!tagName) { return; } - let tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + const tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); addTag(tag); } @@ -5967,7 +5966,7 @@ namespace ts { } function handleUnknownTag(atToken: Node, tagName: Identifier) { - let result = createNode(SyntaxKind.JSDocTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -5992,7 +5991,7 @@ namespace ts { return undefined; } - let typeExpression = parseJSDocTypeExpression(pos, end - pos); + const typeExpression = parseJSDocTypeExpression(pos, end - pos); pos = typeExpression.end; return typeExpression; } @@ -6029,7 +6028,7 @@ namespace ts { typeExpression = tryParseTypeExpression(); } - let result = createNode(SyntaxKind.JSDocParameterTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocParameterTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -6044,7 +6043,7 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -6056,7 +6055,7 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -6068,20 +6067,20 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let typeParameters = >[]; + const typeParameters = >[]; typeParameters.pos = pos; while (true) { skipWhitespace(); - let startPos = pos; - let name = scanIdentifier(); + const startPos = pos; + const name = scanIdentifier(); if (!name) { parseErrorAtPosition(startPos, 0, Diagnostics.Identifier_expected); return undefined; } - let typeParameter = createNode(SyntaxKind.TypeParameter, name.pos); + const typeParameter = createNode(SyntaxKind.TypeParameter, name.pos); typeParameter.name = name; finishNode(typeParameter, pos); @@ -6097,7 +6096,7 @@ namespace ts { typeParameters.end = pos; - let result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -6105,9 +6104,9 @@ namespace ts { } function scanIdentifier(): Identifier { - let startPos = pos; + const startPos = pos; for (; pos < end; pos++) { - let ch = content.charCodeAt(pos); + const ch = content.charCodeAt(pos); if (pos === startPos && isIdentifierStart(ch, ScriptTarget.Latest)) { continue; } @@ -6122,7 +6121,7 @@ namespace ts { return undefined; } - let result = createNode(SyntaxKind.Identifier, startPos); + const result = createNode(SyntaxKind.Identifier, startPos); result.text = content.substring(startPos, pos); return finishNode(result, pos); } @@ -6152,16 +6151,16 @@ namespace ts { // This is because we do incremental parsing in-place. i.e. we take nodes from the old // tree and give them new positions and parents. From that point on, trusting the old // tree at all is not possible as far too much of it may violate invariants. - let incrementalSourceFile = sourceFile; + const incrementalSourceFile = sourceFile; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; - let oldText = sourceFile.text; - let syntaxCursor = createSyntaxCursor(sourceFile); + const oldText = sourceFile.text; + const syntaxCursor = createSyntaxCursor(sourceFile); // Make the actual change larger so that we know to reparse anything whose lookahead // might have intersected the change. - let changeRange = extendToAffectedRange(sourceFile, textChangeRange); + const changeRange = extendToAffectedRange(sourceFile, textChangeRange); checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); // Ensure that extending the affected range only moved the start of the change range @@ -6173,7 +6172,7 @@ namespace ts { // 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). - let delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + const 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 (if we inserted chars) or they @@ -6207,7 +6206,7 @@ namespace ts { // 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. - let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); return result; } @@ -6253,7 +6252,7 @@ namespace ts { array.pos += delta; array.end += delta; - for (let node of array) { + for (const node of array) { visitNode(node); } } @@ -6381,7 +6380,7 @@ namespace ts { // 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. - let fullEnd = child.end; + const fullEnd = child.end; if (fullEnd >= changeStart) { child.intersectsChange = true; child._children = undefined; @@ -6410,14 +6409,14 @@ namespace ts { // 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. - let fullEnd = array.end; + const fullEnd = array.end; if (fullEnd >= changeStart) { array.intersectsChange = true; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (let node of array) { + for (const node of array) { visitNode(node); } return; @@ -6439,7 +6438,7 @@ namespace ts { // (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. - let maxLookahead = 1; + const maxLookahead = 1; let start = changeRange.span.start; @@ -6447,15 +6446,15 @@ namespace ts { // the left by maxLookahead tokens. We only need to do this as long as we're not at the // start of the tree. for (let i = 0; start > 0 && i <= maxLookahead; i++) { - let nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + const nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); Debug.assert(nearestNode.pos <= start); - let position = nearestNode.pos; + const position = nearestNode.pos; start = Math.max(0, position - 1); } - let finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); - let finalLength = changeRange.newLength + (changeRange.span.start - start); + const finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + const finalLength = changeRange.newLength + (changeRange.span.start - start); return createTextChangeRange(finalSpan, finalLength); } @@ -6467,7 +6466,7 @@ namespace ts { forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - let lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + const lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } @@ -6477,7 +6476,7 @@ namespace ts { function getLastChild(node: Node): Node { while (true) { - let lastChild = getLastChildWorker(node); + const lastChild = getLastChildWorker(node); if (lastChild) { node = lastChild; } @@ -6556,17 +6555,17 @@ namespace ts { } function checkChangeRange(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean) { - let oldText = sourceFile.text; + const oldText = sourceFile.text; if (textChangeRange) { Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); if (aggressiveChecks || Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - let oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - let newTextPrefix = newText.substr(0, textChangeRange.span.start); + const oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + const newTextPrefix = newText.substr(0, textChangeRange.span.start); Debug.assert(oldTextPrefix === newTextPrefix); - let oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); - let newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); + const oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); + const newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); Debug.assert(oldTextSuffix === newTextSuffix); } } @@ -6668,7 +6667,7 @@ namespace ts { // position was in this array. Search through this array to see if we find a // viable element. for (let i = 0, n = array.length; i < n; i++) { - let child = array[i]; + const child = array[i]; if (child) { if (child.pos === position) { // Found the right node. We're done. diff --git a/src/compiler/program.ts b/src/compiler/program.ts index a22db74c669..4600d489c45 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -10,7 +10,7 @@ namespace ts { /** The version of the TypeScript compiler release */ - let emptyArray: any[] = []; + const emptyArray: any[] = []; export const version = "1.8.0"; @@ -20,7 +20,7 @@ namespace ts { if (sys.fileExists(fileName)) { return fileName; } - let parentPath = getDirectoryPath(searchPath); + const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } @@ -31,13 +31,13 @@ namespace ts { } export function resolveTripleslashReference(moduleName: string, containingFile: string): string { - let basePath = getDirectoryPath(containingFile); - let referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); + const basePath = getDirectoryPath(containingFile); + const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); return normalizePath(referencedFileName); } export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let moduleResolution = compilerOptions.moduleResolution !== undefined + const moduleResolution = compilerOptions.moduleResolution !== undefined ? compilerOptions.moduleResolution : compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; @@ -48,11 +48,11 @@ namespace ts { } export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let containingDirectory = getDirectoryPath(containingFile); + const containingDirectory = getDirectoryPath(containingFile); if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - let failedLookupLocations: string[] = []; - let candidate = normalizePath(combinePaths(containingDirectory, moduleName)); + const failedLookupLocations: string[] = []; + const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); let resolvedFileName = loadNodeModuleFromFile(candidate, failedLookupLocations, host); if (resolvedFileName) { @@ -73,7 +73,7 @@ namespace ts { return forEach(moduleFileExtensions, tryLoad); function tryLoad(ext: string): string { - let fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; if (host.fileExists(fileName)) { return fileName; } @@ -85,13 +85,13 @@ namespace ts { } function loadNodeModuleFromDirectory(candidate: string, failedLookupLocation: string[], host: ModuleResolutionHost): string { - let packageJsonPath = combinePaths(candidate, "package.json"); + const packageJsonPath = combinePaths(candidate, "package.json"); if (host.fileExists(packageJsonPath)) { let jsonContent: { typings?: string }; try { - let jsonText = host.readFile(packageJsonPath); + const jsonText = host.readFile(packageJsonPath); jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined }; } catch (e) { @@ -100,7 +100,7 @@ namespace ts { } if (jsonContent.typings) { - let result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); + const result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), failedLookupLocation, host); if (result) { return result; } @@ -115,13 +115,13 @@ namespace ts { } function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let failedLookupLocations: string[] = []; + const failedLookupLocations: string[] = []; directory = normalizeSlashes(directory); while (true) { - let baseName = getBaseFileName(directory); + const baseName = getBaseFileName(directory); if (baseName !== "node_modules") { - let nodeModulesFolder = combinePaths(directory, "node_modules"); - let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); + const nodeModulesFolder = combinePaths(directory, "node_modules"); + const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); let result = loadNodeModuleFromFile(candidate, failedLookupLocations, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations }; @@ -133,7 +133,7 @@ namespace ts { } } - let parentPath = getDirectoryPath(directory); + const parentPath = getDirectoryPath(directory); if (parentPath === directory) { break; } @@ -145,7 +145,7 @@ namespace ts { } function nameStartsWithDotSlashOrDotDotSlash(name: string) { - let i = name.lastIndexOf("./", 1); + const i = name.lastIndexOf("./", 1); return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot); } @@ -159,7 +159,7 @@ namespace ts { let searchPath = getDirectoryPath(containingFile); let searchName: string; - let failedLookupLocations: string[] = []; + const failedLookupLocations: string[] = []; let referencedSourceFile: string; while (true) { @@ -171,7 +171,7 @@ namespace ts { return undefined; } - let candidate = searchName + extension; + const candidate = searchName + extension; if (host.fileExists(candidate)) { return candidate; } @@ -184,7 +184,7 @@ namespace ts { break; } - let parentPath = getDirectoryPath(searchPath); + const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } @@ -205,7 +205,7 @@ namespace ts { }; export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { - let existingDirectories: Map = {}; + const 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. @@ -214,12 +214,12 @@ namespace ts { } // returned by CScript sys environment - let unsupportedFileEncodingErrorCode = -2147024809; + const unsupportedFileEncodingErrorCode = -2147024809; function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { let text: string; try { - let start = new Date().getTime(); + const start = new Date().getTime(); text = sys.readFile(fileName, options.charset); ioReadTime += new Date().getTime() - start; } @@ -248,7 +248,7 @@ namespace ts { function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { - let parentDirectory = getDirectoryPath(directoryPath); + const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } @@ -256,7 +256,7 @@ namespace ts { function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { - let start = new Date().getTime(); + const start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; @@ -284,7 +284,7 @@ namespace ts { } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { - let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( + const diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); @@ -326,7 +326,7 @@ namespace ts { let program: Program; let files: SourceFile[] = []; let fileProcessingDiagnostics = createDiagnosticCollection(); - let programDiagnostics = createDiagnosticCollection(); + const programDiagnostics = createDiagnosticCollection(); let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; @@ -335,7 +335,7 @@ namespace ts { let skipDefaultLib = options.noLib; - let start = new Date().getTime(); + const start = new Date().getTime(); host = host || createCompilerHost(options); @@ -344,15 +344,15 @@ namespace ts { ? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile)) : ((moduleNames: string[], containingFile: string) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedModule)); - let filesByName = createFileMap(); + const filesByName = createFileMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing - let filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap(fileName => fileName.toLowerCase()) : undefined; + const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap(fileName => fileName.toLowerCase()) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused - let oldOptions = oldProgram.getCompilerOptions(); + const oldOptions = oldProgram.getCompilerOptions(); if ((oldOptions.module !== options.module) || (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || @@ -410,7 +410,7 @@ namespace ts { getTypeChecker(); classifiableNames = {}; - for (let sourceFile of files) { + for (const sourceFile of files) { copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -426,17 +426,17 @@ namespace ts { Debug.assert(!oldProgram.structureIsReused); // there is an old program, check if we can reuse its structure - let oldRootNames = oldProgram.getRootFileNames(); + const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return false; } // check if program source files has changed in the way that can affect structure of the program - let newSourceFiles: SourceFile[] = []; - let filePaths: Path[] = []; - let modifiedSourceFiles: SourceFile[] = []; + const newSourceFiles: SourceFile[] = []; + const filePaths: Path[] = []; + const modifiedSourceFiles: SourceFile[] = []; - for (let oldSourceFile of oldProgram.getSourceFiles()) { + for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return false; @@ -466,13 +466,13 @@ namespace ts { } if (resolveModuleNamesWorker) { - let moduleNames = map(newSourceFile.imports, name => name.text); - let resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); + const moduleNames = map(newSourceFile.imports, name => name.text); + const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (let i = 0; i < moduleNames.length; ++i) { - let newResolution = resolutions[i]; - let oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); - let resolutionChanged = oldResolution + const newResolution = resolutions[i]; + const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); + const resolutionChanged = oldResolution ? !newResolution || oldResolution.resolvedFileName !== newResolution.resolvedFileName || !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport @@ -504,7 +504,7 @@ namespace ts { files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (let modifiedFile of modifiedSourceFiles) { + for (const modifiedFile of modifiedSourceFiles) { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -554,11 +554,11 @@ namespace ts { // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - let start = new Date().getTime(); + const start = new Date().getTime(); - let emitResult = emitFiles( + const emitResult = emitFiles( emitResolver, getEmitHost(writeFileCallback), sourceFile); @@ -579,7 +579,7 @@ namespace ts { return getDiagnostics(sourceFile, cancellationToken); } - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; forEach(program.getSourceFiles(), sourceFile => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); @@ -631,13 +631,13 @@ namespace ts { function getSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { - let typeChecker = getDiagnosticsProducingTypeChecker(); + const typeChecker = getDiagnosticsProducingTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); - let bindDiagnostics = sourceFile.bindDiagnostics; - let checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); - let fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); - let programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + const bindDiagnostics = sourceFile.bindDiagnostics; + const checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); @@ -646,23 +646,23 @@ namespace ts { function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { - let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - let writeFile: WriteFileCallback = () => { }; + const writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); } function getOptionsDiagnostics(): Diagnostic[] { - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } function getGlobalDiagnostics(): Diagnostic[] { - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -689,7 +689,7 @@ namespace ts { } let imports: LiteralExpression[]; - for (let node of file.statements) { + for (const node of file.statements) { collect(node, /* allowRelativeModuleNames */ true); } @@ -749,7 +749,7 @@ namespace ts { } } else { - let nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); + const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; @@ -797,7 +797,7 @@ namespace ts { } // We haven't looked for this file, do so now and cache result - let file = host.getSourceFile(fileName, options.target, hostErrorMessage => { + const file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); @@ -824,7 +824,7 @@ namespace ts { skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - let basePath = getDirectoryPath(fileName); + const basePath = getDirectoryPath(fileName); if (!options.noResolve) { processReferencedFiles(file, basePath); } @@ -846,7 +846,7 @@ namespace ts { function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { - let referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); }); } @@ -859,21 +859,21 @@ namespace ts { collectExternalModuleReferences(file); if (file.imports.length) { file.resolvedModules = {}; - let moduleNames = map(file.imports, name => name.text); - let resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); + const moduleNames = map(file.imports, name => name.text); + const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (let i = 0; i < file.imports.length; ++i) { - let resolution = resolutions[i]; + const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!isExternalModule(importedFile)) { - let start = getTokenPosOfNode(file.imports[i], file); + const start = getTokenPosOfNode(file.imports[i], file); fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { - let firstRef = importedFile.referencedFiles[0]; + const firstRef = importedFile.referencedFiles[0]; fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); } } @@ -895,7 +895,7 @@ namespace ts { return; } - let sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); + const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { @@ -929,11 +929,11 @@ namespace ts { function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; if (sourceFiles) { - let absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var sourceFile of sourceFiles) { if (!isDeclarationFile(sourceFile)) { - let absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); allFilesBelongToPath = false; @@ -998,24 +998,24 @@ namespace ts { return; } - let languageVersion = options.target || ScriptTarget.ES3; - let outFile = options.outFile || options.out; + const languageVersion = options.target || ScriptTarget.ES3; + const outFile = options.outFile || options.out; - let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); + const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); if (options.isolatedModules) { if (!options.module && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - let firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { - let span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); } diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index a827d755302..4e11e0d6b99 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -49,7 +49,7 @@ namespace ts { tryScan(callback: () => T): T; } - let textToToken: Map = { + const textToToken: Map = { "abstract": SyntaxKind.AbstractKeyword, "any": SyntaxKind.AnyKeyword, "as": SyntaxKind.AsKeyword, @@ -191,8 +191,8 @@ namespace ts { Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt */ - let unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; - let unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers @@ -216,8 +216,8 @@ namespace ts { Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt */ - let unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; - let unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; function lookupInUnicodeMap(code: number, map: number[]): boolean { // Bail out quickly if it couldn't possibly be in the map. @@ -262,8 +262,8 @@ namespace ts { } function makeReverseMap(source: Map): string[] { - let result: string[] = []; - for (let name in source) { + const result: string[] = []; + for (const name in source) { if (source.hasOwnProperty(name)) { result[source[name]] = name; } @@ -271,7 +271,7 @@ namespace ts { return result; } - let tokenStrings = makeReverseMap(textToToken); + const tokenStrings = makeReverseMap(textToToken); export function tokenToString(t: SyntaxKind): string { return tokenStrings[t]; @@ -284,11 +284,11 @@ namespace ts { /* @internal */ export function computeLineStarts(text: string): number[] { - let result: number[] = new Array(); + const result: number[] = new Array(); let pos = 0; let lineStart = 0; while (pos < text.length) { - let ch = text.charCodeAt(pos++); + const ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos) === CharacterCodes.lineFeed) { @@ -352,7 +352,7 @@ namespace ts { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); } - let hasOwnProperty = Object.prototype.hasOwnProperty; + const hasOwnProperty = Object.prototype.hasOwnProperty; export function isWhiteSpace(ch: number): boolean { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. @@ -400,7 +400,7 @@ namespace ts { export function couldStartTrivia(text: string, pos: number): boolean { // Keep in sync with skipTrivia - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: case CharacterCodes.lineFeed: @@ -427,7 +427,7 @@ namespace ts { export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { // Keep in sync with couldStartTrivia while (true) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { @@ -498,14 +498,14 @@ namespace 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. - let mergeConflictMarkerLength = "<<<<<<<".length; + const 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))) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if ((pos + mergeConflictMarkerLength) < text.length) { for (let i = 0, n = mergeConflictMarkerLength; i < n; i++) { @@ -527,8 +527,8 @@ namespace ts { error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); } - let ch = text.charCodeAt(pos); - let len = text.length; + const ch = text.charCodeAt(pos); + const len = text.length; if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { while (pos < len && !isLineBreak(text.charCodeAt(pos))) { @@ -540,7 +540,7 @@ namespace ts { // Consume everything from the start of the mid-conlict marker to the start of the next // end-conflict marker. while (pos < len) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) { break; } @@ -561,7 +561,7 @@ namespace ts { } function scanShebangTrivia(text: string, pos: number) { - let shebang = shebangTriviaRegex.exec(text)[0]; + const shebang = shebangTriviaRegex.exec(text)[0]; pos = pos + shebang.length; return pos; } @@ -581,7 +581,7 @@ namespace ts { let result: CommentRange[]; let collecting = trailing || pos === 0; while (true) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { @@ -607,8 +607,8 @@ namespace ts { let nextChar = text.charCodeAt(pos + 1); let hasTrailingNewLine = false; if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) { - let kind = nextChar === CharacterCodes.slash ? SyntaxKind.SingleLineCommentTrivia : SyntaxKind.MultiLineCommentTrivia; - let startPos = pos; + const kind = nextChar === CharacterCodes.slash ? SyntaxKind.SingleLineCommentTrivia : SyntaxKind.MultiLineCommentTrivia; + const startPos = pos; pos += 2; if (nextChar === CharacterCodes.slash) { while (pos < text.length) { @@ -742,7 +742,7 @@ namespace ts { } function scanNumber(): number { - let start = pos; + const start = pos; while (isDigit(text.charCodeAt(pos))) pos++; if (text.charCodeAt(pos) === CharacterCodes.dot) { pos++; @@ -765,7 +765,7 @@ namespace ts { } function scanOctalDigits(): number { - let start = pos; + const start = pos; while (isOctalDigit(text.charCodeAt(pos))) { pos++; } @@ -792,7 +792,7 @@ namespace ts { let digits = 0; let value = 0; while (digits < minCount || scanAsManyAsPossible) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { value = value * 16 + ch - CharacterCodes._0; } @@ -815,7 +815,7 @@ namespace ts { } function scanString(): string { - let quote = text.charCodeAt(pos++); + const quote = text.charCodeAt(pos++); let result = ""; let start = pos; while (true) { @@ -825,7 +825,7 @@ namespace ts { error(Diagnostics.Unterminated_string_literal); break; } - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === quote) { result += text.substring(start, pos); pos++; @@ -853,7 +853,7 @@ namespace ts { * a literal component of a TemplateExpression. */ function scanTemplateAndSetTokenValue(): SyntaxKind { - let startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; + const startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; pos++; let start = pos; @@ -869,7 +869,7 @@ namespace ts { break; } - let currChar = text.charCodeAt(pos); + const currChar = text.charCodeAt(pos); // '`' if (currChar === CharacterCodes.backtick) { @@ -925,7 +925,7 @@ namespace ts { error(Diagnostics.Unexpected_end_of_text); return ""; } - let ch = text.charCodeAt(pos++); + const ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes._0: return "\0"; @@ -977,7 +977,7 @@ namespace ts { } function scanHexadecimalEscape(numDigits: number): string { - let escapedValue = scanExactNumberOfHexDigits(numDigits); + const escapedValue = scanExactNumberOfHexDigits(numDigits); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); @@ -989,7 +989,7 @@ namespace ts { } function scanExtendedUnicodeEscape(): string { - let escapedValue = scanMinimumNumberOfHexDigits(1); + const escapedValue = scanMinimumNumberOfHexDigits(1); let isInvalidExtendedEscape = false; // Validate the value of the digit @@ -1030,8 +1030,8 @@ namespace ts { return String.fromCharCode(codePoint); } - let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; - let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + const codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + const codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; return String.fromCharCode(codeUnit1, codeUnit2); } @@ -1040,9 +1040,9 @@ namespace ts { // and return code point value if valid Unicode escape is found. Otherwise return -1. function peekUnicodeEscape(): number { if (pos + 5 < end && text.charCodeAt(pos + 1) === CharacterCodes.u) { - let start = pos; + const start = pos; pos += 2; - let value = scanExactNumberOfHexDigits(4); + const value = scanExactNumberOfHexDigits(4); pos = start; return value; } @@ -1078,9 +1078,9 @@ namespace ts { function getIdentifierToken(): SyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter - let len = tokenValue.length; + const len = tokenValue.length; if (len >= 2 && len <= 11) { - let ch = tokenValue.charCodeAt(0); + const ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z && hasOwnProperty.call(textToToken, tokenValue)) { return token = textToToken[tokenValue]; } @@ -1096,8 +1096,8 @@ namespace ts { // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. let numberOfDigits = 0; while (true) { - let ch = text.charCodeAt(pos); - let valueOfCh = ch - CharacterCodes._0; + const ch = text.charCodeAt(pos); + const valueOfCh = ch - CharacterCodes._0; if (!isDigit(ch) || valueOfCh >= base) { break; } @@ -1262,7 +1262,7 @@ namespace ts { let commentClosed = false; while (pos < end) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { pos += 2; @@ -1504,7 +1504,7 @@ namespace ts { break; } - let ch = text.charCodeAt(p); + const ch = text.charCodeAt(p); if (isLineBreak(ch)) { tokenIsUnterminated = true; error(Diagnostics.Unterminated_regular_expression_literal); @@ -1594,9 +1594,9 @@ namespace ts { // they allow dashes function scanJsxIdentifier(): SyntaxKind { if (tokenIsIdentifierOrKeyword(token)) { - let firstCharPosition = pos; + const firstCharPosition = pos; while (pos < end) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { pos++; } @@ -1610,13 +1610,13 @@ namespace ts { } function speculationHelper(callback: () => T, isLookahead: boolean): T { - let savePos = pos; - let saveStartPos = startPos; - let saveTokenPos = tokenPos; - let saveToken = token; - let saveTokenValue = tokenValue; - let savePrecedingLineBreak = precedingLineBreak; - let result = callback(); + const savePos = pos; + const saveStartPos = startPos; + const saveTokenPos = tokenPos; + const saveToken = token; + const saveTokenValue = tokenValue; + const savePrecedingLineBreak = precedingLineBreak; + const result = callback(); // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 7810d9f710a..3a90ca42fa1 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -51,15 +51,15 @@ namespace ts { function getWScriptSystem(): System { - let fso = new ActiveXObject("Scripting.FileSystemObject"); + const fso = new ActiveXObject("Scripting.FileSystemObject"); - let fileStream = new ActiveXObject("ADODB.Stream"); + const fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; - let binaryStream = new ActiveXObject("ADODB.Stream"); + const binaryStream = new ActiveXObject("ADODB.Stream"); binaryStream.Type = 1 /*binary*/; - let args: string[] = []; + const args: string[] = []; for (let i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); } @@ -78,7 +78,7 @@ namespace ts { // Load file and read the first two bytes into a string with no interpretation fileStream.Charset = "x-ansi"; fileStream.LoadFromFile(fileName); - let bom = fileStream.ReadText(2) || ""; + const bom = fileStream.ReadText(2) || ""; // Position must be at 0 before encoding can be changed fileStream.Position = 0; // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8 @@ -124,7 +124,7 @@ namespace ts { } function getNames(collection: any): string[] { - let result: string[] = []; + const result: string[] = []; for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { result.push(e.item().Name); } @@ -132,22 +132,22 @@ namespace ts { } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - let result: string[] = []; + const result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - let folder = fso.GetFolder(path || "."); - let files = getNames(folder.files); - for (let current of files) { - let name = combinePaths(path, current); + const folder = fso.GetFolder(path || "."); + const files = getNames(folder.files); + for (const current of files) { + const name = combinePaths(path, current); if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) { result.push(name); } } - let subfolders = getNames(folder.subfolders); - for (let current of subfolders) { - let name = combinePaths(path, current); + const subfolders = getNames(folder.subfolders); + for (const current of subfolders) { + const name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { visitDirectory(name); } @@ -212,7 +212,7 @@ namespace ts { } function poll(checkedIndex: number) { - let watchedFile = watchedFiles[checkedIndex]; + const watchedFile = watchedFiles[checkedIndex]; if (!watchedFile) { return; } @@ -252,7 +252,7 @@ namespace ts { } function addFile(fileName: string, callback: (fileName: string, removed?: boolean) => void): WatchedFile { - let file: WatchedFile = { + const file: WatchedFile = { fileName, callback, mtime: getModifiedTime(fileName) @@ -291,7 +291,7 @@ namespace ts { // changes for large reference sets? If so, do we want // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? - let watchedFileSet = createWatchedFileSet(); + const watchedFileSet = createWatchedFileSet(); function isNode4OrLater(): Boolean { return parseInt(process.version.charAt(1)) >= 4; @@ -305,14 +305,14 @@ namespace ts { if (!_fs.existsSync(fileName)) { return undefined; } - let buffer = _fs.readFileSync(fileName); + const buffer = _fs.readFileSync(fileName); let len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, // flip all byte pairs and treat as little endian. len &= ~1; for (let i = 0; i < len; i += 2) { - let temp = buffer[i]; + const temp = buffer[i]; buffer[i] = buffer[i + 1]; buffer[i + 1] = temp; } @@ -354,17 +354,17 @@ namespace ts { } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - let result: string[] = []; + const result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - let files = _fs.readdirSync(path || ".").sort(); - let directories: string[] = []; - for (let current of files) { - let name = combinePaths(path, current); + const files = _fs.readdirSync(path || ".").sort(); + const directories: string[] = []; + for (const current of files) { + const name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { - let stat = _fs.statSync(name); + const stat = _fs.statSync(name); if (stat.isFile()) { if (!extension || fileExtensionIs(name, extension)) { result.push(name); @@ -375,7 +375,7 @@ namespace ts { } } } - for (let current of directories) { + for (const current of directories) { visitDirectory(current); } } @@ -400,7 +400,7 @@ namespace ts { return _fs.watch(fileName, (eventName: string, relativeFileName: string) => callback(fileName)); } - let watchedFile = watchedFileSet.addFile(fileName, callback); + const watchedFile = watchedFileSet.addFile(fileName, callback); return { close: () => watchedFileSet.removeFile(watchedFile) }; diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 962805d34a0..79158cf4e9d 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -9,7 +9,7 @@ namespace ts { let reportDiagnostic = reportDiagnosticSimply; function reportDiagnostics(diagnostics: Diagnostic[], host: CompilerHost): void { - for (let diagnostic of diagnostics) { + for (const diagnostic of diagnostics) { reportDiagnostic(diagnostic, host); } } @@ -19,15 +19,15 @@ namespace ts { * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { - let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); return false; } - let language = matchResult[1]; - let territory = matchResult[3]; + const language = matchResult[1]; + const territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. if (!trySetLanguageAndTerritory(language, territory, errors) && @@ -41,8 +41,8 @@ namespace ts { } function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { - let compilerFilePath = normalizePath(sys.getExecutingFilePath()); - let containingDirectoryPath = getDirectoryPath(compilerFilePath); + const compilerFilePath = normalizePath(sys.getExecutingFilePath()); + const containingDirectoryPath = getDirectoryPath(compilerFilePath); let filePath = combinePaths(containingDirectoryPath, language); @@ -85,7 +85,7 @@ namespace ts { } function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { - let diagnostic = createCompilerDiagnostic.apply(undefined, arguments); + const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } @@ -102,7 +102,7 @@ namespace ts { output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `; } - let category = DiagnosticCategory[diagnostic.category].toLowerCase(); + const category = DiagnosticCategory[diagnostic.category].toLowerCase(); output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`; sys.write(output); @@ -130,13 +130,13 @@ namespace ts { let output = ""; if (diagnostic.file) { - let { start, length, file } = diagnostic; - let { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); - let { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); + const { start, length, file } = diagnostic; + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; const relativeFileName = getRelativeFileName(file.fileName, host); - let hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; let gutterWidth = (lastLine + 1 + "").length; if (hasMoreThanFiveLines) { gutterWidth = Math.max(elipsis.length, gutterWidth); @@ -151,8 +151,8 @@ namespace ts { i = lastLine - 1; } - let lineStart = getPositionOfLineAndCharacter(file, i, 0); - let lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + const lineStart = getPositionOfLineAndCharacter(file, i, 0); + const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; let lineContent = file.text.slice(lineStart, lineEnd); lineContent = lineContent.replace(/\s+$/g, ""); // trim from end lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces @@ -200,7 +200,7 @@ namespace ts { let output = new Date().toLocaleTimeString() + " - "; if (diagnostic.file) { - let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `; } @@ -241,7 +241,7 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - let commandLine = parseCommandLine(args); + const commandLine = parseCommandLine(args); let configFileName: string; // Configuration file name (if any) let cachedConfigFileText: string; // Cached configuration file text, used for reparsing (if any) let configFileWatcher: FileWatcher; // Configuration file watcher @@ -302,7 +302,7 @@ namespace ts { } } else if (commandLine.fileNames.length === 0 && isJSONSupported()) { - let searchPath = normalizePath(sys.getCurrentDirectory()); + const searchPath = normalizePath(sys.getCurrentDirectory()); configFileName = findConfigFile(searchPath); } @@ -322,7 +322,7 @@ namespace ts { configFileWatcher = sys.watchFile(configFileName, configFileChanged); } if (sys.watchDirectory && configFileName) { - let directory = ts.getDirectoryPath(configFileName); + const directory = ts.getDirectoryPath(configFileName); directoryWatcher = sys.watchDirectory( // When the configFileName is just "tsconfig.json", the watched directory should be // the current direcotry; if there is a given "project" parameter, then the configFileName @@ -340,16 +340,16 @@ namespace ts { cachedConfigFileText = sys.readFile(configFileName); } catch (e) { - let error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + const error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); reportWatchDiagnostic(error); sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } } - let result = parseConfigFileTextToJson(configFileName, cachedConfigFileText); - let configObject = result.config; - let configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName)); + const result = parseConfigFileTextToJson(configFileName, cachedConfigFileText); + const configObject = result.config; + const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName)); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined); sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -363,7 +363,7 @@ namespace ts { if (!cachedProgram) { if (configFileName) { - let configParseResult = parseConfigFile(); + const configParseResult = parseConfigFile(); rootFileNames = configParseResult.fileNames; compilerOptions = extend(commandLine.options, configParseResult.options); } @@ -386,7 +386,7 @@ namespace ts { // reset the cache of existing files cachedExistingFiles = {}; - let compileResult = compile(rootFileNames, compilerOptions, compilerHost); + const compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!compilerOptions.watch) { return sys.exit(compileResult.exitStatus); @@ -406,14 +406,14 @@ namespace ts { function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) { // Return existing SourceFile object if one is available if (cachedProgram) { - let sourceFile = cachedProgram.getSourceFile(fileName); + const sourceFile = cachedProgram.getSourceFile(fileName); // A modified source file has no watcher and should not be reused if (sourceFile && sourceFile.fileWatcher) { return sourceFile; } } // Use default host function - let sourceFile = hostGetSourceFile(fileName, languageVersion, onError); + const sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && compilerOptions.watch) { // Attach a file watcher sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed)); @@ -424,7 +424,7 @@ namespace ts { // Change cached program to the given program function setCachedProgram(program: Program) { if (cachedProgram) { - let newSourceFiles = program ? program.getSourceFiles() : undefined; + const newSourceFiles = program ? program.getSourceFiles() : undefined; forEach(cachedProgram.getSourceFiles(), sourceFile => { if (!(newSourceFiles && contains(newSourceFiles, sourceFile))) { if (sourceFile.fileWatcher) { @@ -442,7 +442,7 @@ namespace ts { sourceFile.fileWatcher.close(); sourceFile.fileWatcher = undefined; if (removed) { - let index = rootFileNames.indexOf(sourceFile.fileName); + const index = rootFileNames.indexOf(sourceFile.fileName); if (index >= 0) { rootFileNames.splice(index, 1); } @@ -473,9 +473,9 @@ namespace ts { } function directoryChangeHandler() { - let parsedCommandLine = parseConfigFile(); - let newFileNames = ts.map(parsedCommandLine.fileNames, compilerHost.getCanonicalFileName); - let canonicalRootFileNames = ts.map(rootFileNames, compilerHost.getCanonicalFileName); + const parsedCommandLine = parseConfigFile(); + const newFileNames = ts.map(parsedCommandLine.fileNames, compilerHost.getCanonicalFileName); + const canonicalRootFileNames = ts.map(rootFileNames, compilerHost.getCanonicalFileName); // We check if the project file list has changed. If so, we just throw away the old program and start fresh. if (!arrayIsEqualTo(newFileNames && newFileNames.sort(), canonicalRootFileNames && canonicalRootFileNames.sort())) { @@ -509,8 +509,8 @@ namespace ts { checkTime = 0; emitTime = 0; - let program = createProgram(fileNames, compilerOptions, compilerHost); - let exitStatus = compileProgram(); + const program = createProgram(fileNames, compilerOptions, compilerHost); + const exitStatus = compileProgram(); if (compilerOptions.listFiles) { forEach(program.getSourceFiles(), file => { @@ -519,7 +519,7 @@ namespace ts { } if (compilerOptions.diagnostics) { - let memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; + const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", program.getNodeCount()); @@ -572,7 +572,7 @@ namespace ts { } // Otherwise, emit and report any errors we ran into. - let emitOutput = program.emit(); + const emitOutput = program.emit(); reportDiagnostics(emitOutput.diagnostics, compilerHost); // If the emitter didn't emit anything, then pass that value along. @@ -598,8 +598,8 @@ namespace ts { let output = ""; // We want to align our "syntax" and "examples" commands to a certain margin. - let syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; - let examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; + const syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; + const examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; let marginLength = Math.max(syntaxLength, examplesLength); // Build up the syntactic skeleton. @@ -610,7 +610,7 @@ namespace ts { output += sys.newLine + sys.newLine; // Build up the list of examples. - let padding = makePadding(marginLength); + const padding = makePadding(marginLength); output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine; output += padding + "tsc --out file.js file.ts" + sys.newLine; output += padding + "tsc @args.txt" + sys.newLine; @@ -619,17 +619,17 @@ namespace ts { output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine; // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") - let optsList = filter(optionDeclarations.slice(), v => !v.experimental); + const optsList = filter(optionDeclarations.slice(), v => !v.experimental); optsList.sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase())); // We want our descriptions to align at the same column in our output, // so we keep track of the longest option usage string. marginLength = 0; - let usageColumn: string[] = []; // Things like "-d, --declaration" go in here. - let descriptionColumn: string[] = []; + const usageColumn: string[] = []; // Things like "-d, --declaration" go in here. + const descriptionColumn: string[] = []; for (let i = 0; i < optsList.length; i++) { - let option = optsList[i]; + const option = optsList[i]; // If an option lacks a description, // it is not officially supported. @@ -655,15 +655,15 @@ namespace ts { } // Special case that can't fit in the loop. - let usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; + const usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; usageColumn.push(usageText); descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file)); marginLength = Math.max(usageText.length, marginLength); // Print out each row, aligning all the descriptions on the same column. for (let i = 0; i < usageColumn.length; i++) { - let usage = usageColumn[i]; - let description = descriptionColumn[i]; + const usage = usageColumn[i]; + const description = descriptionColumn[i]; output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine; } @@ -683,14 +683,14 @@ namespace ts { } function writeConfigFile(options: CompilerOptions, fileNames: string[]) { - let currentDirectory = sys.getCurrentDirectory(); - let file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); + const currentDirectory = sys.getCurrentDirectory(); + const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); if (sys.fileExists(file)) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* compilerHost */ undefined); } else { - let compilerOptions = extend(options, defaultInitCompilerOptions); - let configurations: any = { + const compilerOptions = extend(options, defaultInitCompilerOptions); + const configurations: any = { compilerOptions: serializeCompilerOptions(compilerOptions), exclude: ["node_modules"] }; @@ -707,12 +707,12 @@ namespace ts { return; function serializeCompilerOptions(options: CompilerOptions): Map { - let result: Map = {}; - let optionsNameMap = getOptionNameMap().optionNameMap; + const result: Map = {}; + const optionsNameMap = getOptionNameMap().optionNameMap; - for (let name in options) { + for (const name in options) { if (hasProperty(options, name)) { - let value = options[name]; + const value = options[name]; switch (name) { case "init": case "watch": @@ -729,8 +729,8 @@ namespace ts { } else { // Enum - let typeMap = >optionDefinition.type; - for (let key in typeMap) { + const typeMap = >optionDefinition.type; + for (const key in typeMap) { if (hasProperty(typeMap, key)) { if (typeMap[key] === value) result[name] = key; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 6764ea20c81..4335df47670 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -16,9 +16,9 @@ namespace ts { } export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { - let declarations = symbol.declarations; + const declarations = symbol.declarations; if (declarations) { - for (let declaration of declarations) { + for (const declaration of declarations) { if (declaration.kind === kind) { return declaration; } @@ -43,12 +43,12 @@ namespace ts { } // Pool writers to avoid needing to allocate them for every symbol we write. - let stringWriters: StringSymbolWriter[] = []; + const stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { if (stringWriters.length === 0) { let str = ""; - let writeText: (text: string) => void = text => str += text; + const writeText: (text: string) => void = text => str += text; return { string: () => str, writeKeyword: writeText, @@ -92,7 +92,7 @@ namespace ts { } for (let i = 0; i < array1.length; ++i) { - let equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; } @@ -128,7 +128,7 @@ namespace ts { // 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. - let thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || + const thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || forEachChild(node, containsParseError); // If so, mark ourselves accordingly. @@ -157,8 +157,8 @@ namespace ts { // This is a useful function for debugging purposes. export function nodePosToString(node: Node): string { - let file = getSourceFileOfNode(node); - let loc = getLineAndCharacterOfPosition(file, node.pos); + const file = getSourceFileOfNode(node); + const loc = getLineAndCharacterOfPosition(file, node.pos); return `${ file.fileName }(${ loc.line + 1 },${ loc.character + 1 })`; } @@ -213,7 +213,7 @@ namespace ts { return ""; } - let text = sourceFile.text; + const text = sourceFile.text; return text.substring(includeTrivia ? node.pos : skipTrivia(text, node.pos), node.end); } @@ -294,14 +294,14 @@ namespace ts { } export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic { - let sourceFile = getSourceFileOfNode(node); - let span = getErrorSpanForNode(sourceFile, node); + const sourceFile = getSourceFileOfNode(node); + const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } export function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic { - let sourceFile = getSourceFileOfNode(node); - let span = getErrorSpanForNode(sourceFile, node); + const sourceFile = getSourceFileOfNode(node); + const span = getErrorSpanForNode(sourceFile, node); return { file: sourceFile, start: span.start, @@ -313,9 +313,9 @@ namespace ts { } export function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan { - let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + const scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); scanner.scan(); - let start = scanner.getTokenPos(); + const start = scanner.getTokenPos(); return createTextSpanFromBounds(start, scanner.getTextPos()); } @@ -351,7 +351,7 @@ namespace ts { return getSpanOfTokenAtPosition(sourceFile, node.pos); } - let pos = nodeIsMissing(errorNode) + const pos = nodeIsMissing(errorNode) ? errorNode.pos : skipTrivia(sourceFile.text, errorNode.pos); @@ -422,7 +422,7 @@ namespace ts { } export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) { - let commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ? + const commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ? concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos), getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : getLeadingCommentRangesOfNode(node, sourceFileOfNode); @@ -579,7 +579,7 @@ namespace ts { return; default: if (isFunctionLike(node)) { - let name = (node).name; + const name = (node).name; if (name && name.kind === SyntaxKind.ComputedPropertyName) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. @@ -1030,7 +1030,7 @@ namespace ts { } export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { - let moduleState = getModuleInstanceState(node); + const moduleState = getModuleInstanceState(node); return moduleState === ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); } @@ -1053,7 +1053,7 @@ namespace ts { return (node).moduleSpecifier; } if (node.kind === SyntaxKind.ImportEqualsDeclaration) { - let reference = (node).moduleReference; + const reference = (node).moduleReference; if (reference.kind === SyntaxKind.ExternalModuleReference) { return (reference).expression; } @@ -1088,7 +1088,7 @@ namespace ts { function getJSDocTag(node: Node, kind: SyntaxKind): JSDocTag { if (node && node.jsDocComment) { - for (let tag of node.jsDocComment.tags) { + for (const tag of node.jsDocComment.tags) { if (tag.kind === kind) { return tag; } @@ -1112,14 +1112,14 @@ namespace ts { if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) { // If it's a parameter, see if the parent has a jsdoc comment with an @param // annotation. - let parameterName = (parameter.name).text; + const parameterName = (parameter.name).text; - let docComment = parameter.parent.jsDocComment; + const docComment = parameter.parent.jsDocComment; if (docComment) { return forEach(docComment.tags, t => { if (t.kind === SyntaxKind.JSDocParameterTag) { - let parameterTag = t; - let name = parameterTag.preParameterName || parameterTag.postParameterName; + const parameterTag = t; + const name = parameterTag.preParameterName || parameterTag.postParameterName; if (name.text === parameterName) { return t; } @@ -1140,7 +1140,7 @@ namespace ts { return true; } - let paramTag = getCorrespondingJSDocParameterTag(node); + const paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { return paramTag.typeExpression.type.kind === SyntaxKind.JSDocVariadicType; } @@ -1270,7 +1270,7 @@ namespace ts { return false; } - let parent = name.parent; + const parent = name.parent; if (parent.kind === SyntaxKind.ImportSpecifier || parent.kind === SyntaxKind.ExportSpecifier) { if ((parent).propertyName) { return true; @@ -1337,23 +1337,23 @@ namespace ts { } export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } export function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getHeritageClause(clauses: NodeArray, kind: SyntaxKind) { if (clauses) { - for (let clause of clauses) { + for (const clause of clauses) { if (clause.token === kind) { return clause; } @@ -1365,7 +1365,7 @@ namespace ts { export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) { if (!host.getCompilerOptions().noResolve) { - let referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName); + const referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName); return host.getSourceFile(referenceFileName); } } @@ -1381,8 +1381,8 @@ namespace ts { } export function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult { - let simpleReferenceRegEx = /^\/\/\/\s*/gim; + const simpleReferenceRegEx = /^\/\/\/\s*/gim; if (simpleReferenceRegEx.exec(comment)) { if (isNoDefaultLibRegEx.exec(comment)) { return { @@ -1390,10 +1390,10 @@ namespace ts { }; } else { - let matchResult = fullTripleSlashReferencePathRegEx.exec(comment); + const matchResult = fullTripleSlashReferencePathRegEx.exec(comment); if (matchResult) { - let start = commentRange.pos; - let end = commentRange.end; + const start = commentRange.pos; + const end = commentRange.end; return { fileReference: { pos: start, @@ -1462,9 +1462,9 @@ namespace ts { return (name).text; } if (name.kind === SyntaxKind.ComputedPropertyName) { - let nameExpression = (name).expression; + const nameExpression = (name).expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - let rightHandSideName = (nameExpression).name.text; + const rightHandSideName = (nameExpression).name.text; return getPropertyNameForKnownSymbolName(rightHandSideName); } } @@ -1501,7 +1501,7 @@ namespace ts { } export function isParameterDeclaration(node: VariableLikeDeclaration) { - let root = getRootDeclaration(node); + const root = getRootDeclaration(node); return root.kind === SyntaxKind.Parameter; } @@ -1518,12 +1518,12 @@ namespace ts { export function cloneEntityName(node: EntityName): EntityName { if (node.kind === SyntaxKind.Identifier) { - let clone = createSynthesizedNode(SyntaxKind.Identifier); + const clone = createSynthesizedNode(SyntaxKind.Identifier); clone.text = (node).text; return clone; } else { - let clone = createSynthesizedNode(SyntaxKind.QualifiedName); + const clone = createSynthesizedNode(SyntaxKind.QualifiedName); clone.left = cloneEntityName((node).left); clone.left.parent = clone; clone.right = cloneEntityName((node).right); @@ -1537,13 +1537,13 @@ namespace ts { } export function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node { - let node = createNode(kind, /* pos */ -1, /* end */ -1); + const node = createNode(kind, /* pos */ -1, /* end */ -1); node.startsOnNewLine = startsOnNewLine; return node; } export function createSynthesizedNodeArray(): NodeArray { - let array = >[]; + const array = >[]; array.pos = -1; array.end = -1; return array; @@ -1551,7 +1551,7 @@ namespace ts { export function createDiagnosticCollection(): DiagnosticCollection { let nonFileDiagnostics: Diagnostic[] = []; - let fileDiagnostics: Map = {}; + const fileDiagnostics: Map = {}; let diagnosticsModified = false; let modificationCount = 0; @@ -1573,7 +1573,7 @@ namespace ts { return; } - for (let diagnostic of fileDiagnostics[newFile.fileName]) { + for (const diagnostic of fileDiagnostics[newFile.fileName]) { diagnostic.file = newFile; } } @@ -1607,14 +1607,14 @@ namespace ts { return fileDiagnostics[fileName] || []; } - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; function pushDiagnostic(d: Diagnostic) { allDiagnostics.push(d); } forEach(nonFileDiagnostics, pushDiagnostic); - for (let key in fileDiagnostics) { + for (const key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { forEach(fileDiagnostics[key], pushDiagnostic); } @@ -1631,7 +1631,7 @@ namespace ts { diagnosticsModified = false; nonFileDiagnostics = sortAndDeduplicateDiagnostics(nonFileDiagnostics); - for (let key in fileDiagnostics) { + for (const key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } @@ -1644,8 +1644,8 @@ namespace ts { // the language service. These characters should be escaped when printing, and if any characters are added, // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. - let escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - let escapedCharsMap: Map = { + const escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + const escapedCharsMap: Map = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -1676,17 +1676,17 @@ namespace ts { } export function isIntrinsicJsxName(name: string) { - let ch = name.substr(0, 1); + const ch = name.substr(0, 1); return ch.toLowerCase() === ch; } function get16BitUnicodeEscapeSequence(charCode: number): string { - let hexCharCode = charCode.toString(16).toUpperCase(); - let paddedHexCode = ("0000" + hexCharCode).slice(-4); + const hexCharCode = charCode.toString(16).toUpperCase(); + const paddedHexCode = ("0000" + hexCharCode).slice(-4); return "\\u" + paddedHexCode; } - let nonAsciiCharacters = /[^\u0000-\u007F]/g; + const nonAsciiCharacters = /[^\u0000-\u007F]/g; export function escapeNonAsciiCharacters(s: string): string { // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. @@ -1710,7 +1710,7 @@ namespace ts { getIndent(): number; } - let indentStrings: string[] = ["", " "]; + const indentStrings: string[] = ["", " "]; export function getIndentString(level: number) { if (indentStrings[level] === undefined) { indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; @@ -1751,7 +1751,7 @@ namespace ts { function writeLiteral(s: string) { if (s && s.length) { write(s); - let lineStartsOfS = computeLineStarts(s); + const lineStartsOfS = computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + lastOrUndefined(lineStartsOfS); @@ -1789,7 +1789,7 @@ namespace ts { } export function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string) { - let compilerOptions = host.getCompilerOptions(); + const compilerOptions = host.getCompilerOptions(); let emitOutputFilePathWithoutExtension: string; if (compilerOptions.outDir) { emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); @@ -1862,8 +1862,8 @@ namespace ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && (member.flags & NodeFlags.Static) === (accessor.flags & NodeFlags.Static)) { - let memberName = getPropertyNameForPropertyNameNode(member.name); - let accessorName = getPropertyNameForPropertyNameNode(accessor.name); + const memberName = getPropertyNameForPropertyNameNode(member.name); + const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { firstAccessor = member; @@ -1946,13 +1946,13 @@ namespace ts { } if (leadingComments) { - let detachedComments: CommentRange[] = []; + const detachedComments: CommentRange[] = []; let lastComment: CommentRange; - for (let comment of leadingComments) { + for (const comment of leadingComments) { if (lastComment) { - let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - let commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + const commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); if (commentLine >= lastCommentLine + 2) { // There was a blank line between the last comment and this comment. This @@ -1970,8 +1970,8 @@ namespace ts { // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end); - let nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); + const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end); + const nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); @@ -1991,11 +1991,11 @@ namespace ts { export function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) { - let firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - let lineCount = getLineStarts(currentSourceFile).length; + const firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); + const lineCount = getLineStarts(currentSourceFile).length; let firstCommentLineIndent: number; for (let pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - let nextLineStart = (currentLine + 1) === lineCount + const nextLineStart = (currentLine + 1) === lineCount ? currentSourceFile.text.length + 1 : getStartPositionOfLine(currentLine + 1, currentSourceFile); @@ -2006,7 +2006,7 @@ namespace ts { } // These are number of spaces writer is going to write at current indent - let currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + const currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); // Number of spaces we want to be writing // eg: Assume writer indent @@ -2022,10 +2022,10 @@ namespace ts { // More right indented comment */ --4 = 8 - 4 + 11 // class c { } // } - let spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); if (spacesToEmit > 0) { let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - let indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces writer.rawWrite(indentSizeSpaceString); @@ -2054,8 +2054,8 @@ namespace ts { } function writeTrimmedCurrentLine(pos: number, nextLineStart: number) { - let end = Math.min(comment.end, nextLineStart - 1); - let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + const end = Math.min(comment.end, nextLineStart - 1); + const currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text writer.write(currentLineText); @@ -2169,7 +2169,7 @@ namespace ts { } export function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean { - let kind = expression.kind; + const kind = expression.kind; if (kind === SyntaxKind.ObjectLiteralExpression) { return (expression).properties.length === 0; } @@ -2196,11 +2196,11 @@ namespace ts { * representing the UTF-8 encoding of the character, and return the expanded char code list. */ function getExpandedCharCodes(input: string): number[] { - let output: number[] = []; - let length = input.length; + const output: number[] = []; + const length = input.length; for (let i = 0; i < length; i++) { - let charCode = input.charCodeAt(i); + const charCode = input.charCodeAt(i); // handel utf8 if (charCode < 0x80) { @@ -2236,9 +2236,9 @@ namespace ts { */ export function convertToBase64(input: string): string { let result = ""; - let charCodes = getExpandedCharCodes(input); + const charCodes = getExpandedCharCodes(input); let i = 0; - let length = charCodes.length; + const length = charCodes.length; let byte1: number, byte2: number, byte3: number, byte4: number; while (i < length) { @@ -2312,14 +2312,14 @@ namespace ts { } export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { - let overlapStart = Math.max(span.start, other.start); - let overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + const overlapStart = Math.max(span.start, other.start); + const overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); return overlapStart < overlapEnd; } export function textSpanOverlap(span1: TextSpan, span2: TextSpan) { - let overlapStart = Math.max(span1.start, span2.start); - let overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + const overlapStart = Math.max(span1.start, span2.start); + const overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (overlapStart < overlapEnd) { return createTextSpanFromBounds(overlapStart, overlapEnd); } @@ -2331,13 +2331,13 @@ namespace ts { } export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { - let end = start + length; + const end = start + length; return start <= textSpanEnd(span) && end >= span.start; } export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) { - let end1 = start1 + length1; - let end2 = start2 + length2; + const end1 = start1 + length1; + const end2 = start2 + length2; return start2 <= end1 && end2 >= start1; } @@ -2346,8 +2346,8 @@ namespace ts { } export function textSpanIntersection(span1: TextSpan, span2: TextSpan) { - let intersectStart = Math.max(span1.start, span2.start); - let intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + const intersectStart = Math.max(span1.start, span2.start); + const intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (intersectStart <= intersectEnd) { return createTextSpanFromBounds(intersectStart, intersectEnd); } @@ -2406,14 +2406,14 @@ namespace ts { // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. - let change0 = changes[0]; + const change0 = changes[0]; let oldStartN = change0.span.start; let oldEndN = textSpanEnd(change0.span); let newEndN = oldStartN + change0.newLength; for (let i = 1; i < changes.length; i++) { - let nextChange = changes[i]; + const 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 @@ -2495,13 +2495,13 @@ namespace ts { // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } - let oldStart1 = oldStartN; - let oldEnd1 = oldEndN; - let newEnd1 = newEndN; + const oldStart1 = oldStartN; + const oldEnd1 = oldEndN; + const newEnd1 = newEndN; - let oldStart2 = nextChange.span.start; - let oldEnd2 = textSpanEnd(nextChange.span); - let newEnd2 = oldStart2 + nextChange.newLength; + const oldStart2 = nextChange.span.start; + const oldEnd2 = textSpanEnd(nextChange.span); + const newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index 108c6f4518a..848f229f109 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -140,7 +140,7 @@ class CompilerBaselineRunner extends RunnerBase { it("Correct sourcemap content for " + fileName, () => { if (options.sourceMap || options.inlineSourceMap) { Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => { - let record = result.getSourceMapRecord(); + const record = result.getSourceMapRecord(); if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) { // Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required. return null; @@ -159,7 +159,7 @@ class CompilerBaselineRunner extends RunnerBase { // check js output Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => { let tsCode = ""; - let tsSources = otherFiles.concat(toBeCompiled); + const tsSources = otherFiles.concat(toBeCompiled); if (tsSources.length > 1) { tsCode += "//// [" + fileName + "] ////\r\n\r\n"; } @@ -184,7 +184,7 @@ class CompilerBaselineRunner extends RunnerBase { } } - let declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { + const declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { harnessCompiler.setCompilerSettings(tcSettings); }, options); @@ -257,15 +257,15 @@ class CompilerBaselineRunner extends RunnerBase { // These types are equivalent, but depend on what order the compiler observed // certain parts of the program. - let allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName)); + const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName)); - let fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true); - let pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false); + const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true); + const pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false); - let fullResults: ts.Map = {}; - let pullResults: ts.Map = {}; + const fullResults: ts.Map = {}; + const pullResults: ts.Map = {}; - for (let sourceFile of allFiles) { + for (const sourceFile of allFiles) { fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName); pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName); } @@ -294,11 +294,11 @@ class CompilerBaselineRunner extends RunnerBase { return; function checkBaseLines(isSymbolBaseLine: boolean) { - let fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine); - let pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine); + const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine); + const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine); - let fullExtension = isSymbolBaseLine ? ".symbols" : ".types"; - let pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull"; + const fullExtension = isSymbolBaseLine ? ".symbols" : ".types"; + const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull"; if (fullBaseLine !== pullBaseLine) { Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine); @@ -310,24 +310,24 @@ class CompilerBaselineRunner extends RunnerBase { } function generateBaseLine(typeWriterResults: ts.Map, isSymbolBaseline: boolean): string { - let typeLines: string[] = []; - let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; + const typeLines: string[] = []; + const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; allFiles.forEach(file => { - let codeLines = file.content.split("\n"); + const codeLines = file.content.split("\n"); typeWriterResults[file.unitName].forEach(result => { if (isSymbolBaseline && !result.symbol) { return; } - let typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; - let formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; + const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; + const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; if (!typeMap[file.unitName]) { typeMap[file.unitName] = {}; } let typeInfo = [formattedLine]; - let existingTypeInfo = typeMap[file.unitName][result.line]; + const existingTypeInfo = typeMap[file.unitName][result.line]; if (existingTypeInfo) { typeInfo = existingTypeInfo.concat(typeInfo); } @@ -336,10 +336,10 @@ class CompilerBaselineRunner extends RunnerBase { typeLines.push("=== " + file.unitName + " ===\r\n"); for (let i = 0; i < codeLines.length; i++) { - let currentCodeLine = codeLines[i]; + const currentCodeLine = codeLines[i]; typeLines.push(currentCodeLine + "\r\n"); if (typeMap[file.unitName]) { - let typeInfo = typeMap[file.unitName][i]; + const typeInfo = typeMap[file.unitName][i]; if (typeInfo) { typeInfo.forEach(ty => { typeLines.push(">" + ty + "\r\n"); @@ -367,13 +367,13 @@ class CompilerBaselineRunner extends RunnerBase { public initializeTests() { describe(this.testSuiteName + " tests", () => { describe("Setup compiler for compiler baselines", () => { - let harnessCompiler = Harness.Compiler.getCompiler(); + const harnessCompiler = Harness.Compiler.getCompiler(); this.parseOptions(); }); // this will set up a series of describe/it blocks to run between the setup and cleanup phases if (this.tests.length === 0) { - let testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); + const testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); testFiles.forEach(fn => { fn = fn.replace(/\\/g, "/"); this.checkTestCodeOutput(fn); @@ -392,7 +392,7 @@ class CompilerBaselineRunner extends RunnerBase { this.decl = false; this.output = false; - let opts = this.options.split(","); + const opts = this.options.split(","); for (let i = 0; i < opts.length; i++) { switch (opts[i]) { case "error": diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 457ece7e132..bf8b9493829 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -102,7 +102,7 @@ namespace FourSlash { export import IndentStyle = ts.IndentStyle; - let entityMap: ts.Map = { + const entityMap: ts.Map = { "&": "&", "\"": """, "'": "'", @@ -118,7 +118,7 @@ namespace FourSlash { // Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions // To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames // Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data - let metadataOptionNames = { + const metadataOptionNames = { baselineFile: "BaselineFile", emitThisFile: "emitThisFile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project fileName: "Filename", @@ -126,10 +126,10 @@ namespace FourSlash { }; // List of allowed metadata names - let fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; + const fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; function convertGlobalOptionsToCompilerOptions(globalOptions: Harness.TestCaseParser.CompilerSettings): ts.CompilerOptions { - let settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; + const settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; Harness.Compiler.setCompilerOptionsFromHarnessSetting(globalOptions, settings); return settings; } @@ -224,7 +224,7 @@ namespace FourSlash { // Add input file which has matched file name with the given reference-file path. // This is necessary when resolveReference flag is specified private addMatchedInputFile(referenceFilePath: string) { - let inputFile = this.inputFiles[referenceFilePath]; + const inputFile = this.inputFiles[referenceFilePath]; if (inputFile && !Harness.isLibraryFile(referenceFilePath)) { this.languageServiceAdapterHost.addScript(referenceFilePath, inputFile); } @@ -248,8 +248,8 @@ namespace FourSlash { constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) { // Create a new Services Adapter this.cancellationToken = new TestCancellationToken(); - let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); - let languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); + const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); + const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); this.languageServiceAdapterHost = languageServiceAdapter.getHost(); this.languageService = languageServiceAdapter.getLanguageService(); @@ -272,14 +272,14 @@ namespace FourSlash { // Add the entry-point file itself into the languageServiceShimHost this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content); - let resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); - let referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; - let importedFiles: ts.FileReference[] = resolvedResult.importedFiles; + const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); + const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; + const importedFiles: ts.FileReference[] = resolvedResult.importedFiles; // Add triple reference files into language-service host ts.forEach(referencedFiles, referenceFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName so we will properly append the same base directory to refFile path - let referenceFilePath = this.basePath + "/" + referenceFile.fileName; + const referenceFilePath = this.basePath + "/" + referenceFile.fileName; this.addMatchedInputFile(referenceFilePath); }); @@ -287,7 +287,7 @@ namespace FourSlash { ts.forEach(importedFiles, importedFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts" // so convert them before making appropriate comparison - let importedFilePath = this.basePath + "/" + importedFile.fileName + ".ts"; + const importedFilePath = this.basePath + "/" + importedFile.fileName + ".ts"; this.addMatchedInputFile(importedFilePath); }); @@ -324,8 +324,8 @@ namespace FourSlash { }; this.testData.files.forEach(file => { - let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1); - let fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); + const fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1); + const fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); this.scenarioActions.push(""); }); @@ -334,18 +334,18 @@ namespace FourSlash { } private getFileContent(fileName: string): string { - let script = this.languageServiceAdapterHost.getScriptInfo(fileName); + const script = this.languageServiceAdapterHost.getScriptInfo(fileName); return script.content; } // Entry points from fourslash.ts public goToMarker(name = "") { - let marker = this.getMarkerByName(name); + const marker = this.getMarkerByName(name); if (this.activeFile.fileName !== marker.fileName) { this.openFile(marker.fileName); } - let content = this.getFileContent(marker.fileName); + const content = this.getFileContent(marker.fileName); if (marker.position === -1 || marker.position > content.length) { throw new Error(`Marker "${name}" has been invalidated by unrecoverable edits to the file.`); } @@ -356,8 +356,8 @@ namespace FourSlash { public goToPosition(pos: number) { this.currentCaretPosition = pos; - let lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); - let lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); + const lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); + const lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); this.scenarioActions.push(``); } @@ -376,10 +376,10 @@ namespace FourSlash { public openFile(index: number): void; public openFile(name: string): void; public openFile(indexOrName: any) { - let fileToOpen: FourSlashFile = this.findFile(indexOrName); + const fileToOpen: FourSlashFile = this.findFile(indexOrName); fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName); this.activeFile = fileToOpen; - let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1); + const fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1); this.scenarioActions.push(``); // Let the host know that this file is now open @@ -387,13 +387,13 @@ namespace FourSlash { } public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) { - let startMarker = this.getMarkerByName(startMarkerName); - let endMarker = this.getMarkerByName(endMarkerName); - let predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { + const startMarker = this.getMarkerByName(startMarkerName); + const endMarker = this.getMarkerByName(endMarkerName); + const predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; }; - let exists = this.anyErrorInRange(predicate, startMarker, endMarker); + const exists = this.anyErrorInRange(predicate, startMarker, endMarker); this.taoInvalidReason = "verifyErrorExistsBetweenMarkers NYI"; @@ -413,10 +413,10 @@ namespace FourSlash { } private getDiagnostics(fileName: string): ts.Diagnostic[] { - let syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); - let semanticErrors = this.languageService.getSemanticDiagnostics(fileName); + const syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); + const semanticErrors = this.languageService.getSemanticDiagnostics(fileName); - let diagnostics: ts.Diagnostic[] = []; + const diagnostics: ts.Diagnostic[] = []; diagnostics.push.apply(diagnostics, syntacticErrors); diagnostics.push.apply(diagnostics, semanticErrors); @@ -424,9 +424,9 @@ namespace FourSlash { } private getAllDiagnostics(): ts.Diagnostic[] { - let diagnostics: ts.Diagnostic[] = []; + const diagnostics: ts.Diagnostic[] = []; - let fileNames = this.languageServiceAdapterHost.getFilenames(); + const fileNames = this.languageServiceAdapterHost.getFilenames(); for (let i = 0, n = fileNames.length; i < n; i++) { diagnostics.push.apply(this.getDiagnostics(fileNames[i])); } @@ -435,7 +435,7 @@ namespace FourSlash { } public verifyErrorExistsAfterMarker(markerName: string, negative: boolean, after: boolean) { - let marker: Marker = this.getMarkerByName(markerName); + const marker: Marker = this.getMarkerByName(markerName); let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean; if (after) { @@ -451,8 +451,8 @@ namespace FourSlash { this.taoInvalidReason = "verifyErrorExistsAfterMarker NYI"; - let exists = this.anyErrorInRange(predicate, marker); - let diagnostics = this.getAllDiagnostics(); + const exists = this.anyErrorInRange(predicate, marker); + const diagnostics = this.getAllDiagnostics(); if (exists !== negative) { this.printErrorLog(negative, diagnostics); @@ -462,10 +462,10 @@ namespace FourSlash { private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean, startMarker: Marker, endMarker?: Marker) { - let errors = this.getDiagnostics(startMarker.fileName); + const errors = this.getDiagnostics(startMarker.fileName); let exists = false; - let startPos = startMarker.position; + const startPos = startMarker.position; let endPos: number = undefined; if (endMarker !== undefined) { endPos = endMarker.position; @@ -496,40 +496,40 @@ namespace FourSlash { } public verifyNumberOfErrorsInCurrentFile(expected: number) { - let errors = this.getDiagnostics(this.activeFile.fileName); - let actual = errors.length; + const errors = this.getDiagnostics(this.activeFile.fileName); + const actual = errors.length; this.scenarioActions.push(``); if (actual !== expected) { this.printErrorLog(false, errors); - let errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; + const errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; Harness.IO.log(errorMsg); this.raiseError(errorMsg); } } public verifyEval(expr: string, value: any) { - let emit = this.languageService.getEmitOutput(this.activeFile.fileName); + const emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = "verifyEval impossible"; - let evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); + const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); if (evaluation !== value) { this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`); } } public verifyGetEmitOutputForCurrentFile(expected: string): void { - let emit = this.languageService.getEmitOutput(this.activeFile.fileName); + const emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = "verifyGetEmitOutputForCurrentFile impossible"; - let actual = emit.outputFiles[0].text; + const actual = emit.outputFiles[0].text; if (actual !== expected) { this.raiseError(`Expected emit output to be "${expected}", but got "${actual}"`); } @@ -543,7 +543,7 @@ namespace FourSlash { this.taoInvalidReason = "verifyMemberListContains only supports the \"symbol\" parameter"; } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members) { this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind); } @@ -567,10 +567,10 @@ namespace FourSlash { this.scenarioActions.push(``); } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members) { - let match = members.entries.length === expectedCount; + const match = members.entries.length === expectedCount; if ((!match && !negative) || (match && negative)) { this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount); @@ -585,7 +585,7 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members && members.entries.filter(e => e.name === symbol).length !== 0) { this.raiseError(`Member list did contain ${symbol}`); } @@ -594,8 +594,8 @@ namespace FourSlash { public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) { this.taoInvalidReason = "verifyCompletionListItemsCountIsGreaterThan NYI"; - let completions = this.getCompletionListAtCaret(); - let itemsCount = completions.entries.length; + const completions = this.getCompletionListAtCaret(); + const itemsCount = completions.entries.length; if (negative) { if (itemsCount > count) { @@ -617,7 +617,7 @@ namespace FourSlash { this.scenarioActions.push(""); } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if ((!members || members.entries.length === 0) && negative) { this.raiseError("Member list is empty at Caret"); } @@ -637,7 +637,7 @@ namespace FourSlash { public verifyCompletionListIsEmpty(negative: boolean) { this.scenarioActions.push(""); - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if ((!completions || completions.entries.length === 0) && negative) { this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); } @@ -654,7 +654,7 @@ namespace FourSlash { public verifyCompletionListAllowsNewIdentifier(negative: boolean) { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if ((completions && !completions.isNewIdentifierLocation) && !negative) { this.raiseError("Expected builder completion entry"); @@ -665,7 +665,7 @@ namespace FourSlash { } public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if (completions) { this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind); } @@ -685,11 +685,11 @@ namespace FourSlash { * @param expectedKind the kind of symbol (see ScriptElementKind) */ public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) { - let that = this; + const that = this; function filterByTextOrDocumentation(entry: ts.CompletionEntry) { - let details = that.getCompletionEntryDetails(entry.name); - let documentation = ts.displayPartsToString(details.documentation); - let text = ts.displayPartsToString(details.displayParts); + const details = that.getCompletionEntryDetails(entry.name); + const documentation = ts.displayPartsToString(details.documentation); + const text = ts.displayPartsToString(details.displayParts); if (expectedText && expectedDocumentation) { return (documentation === expectedDocumentation && text === expectedText) ? true : false; } @@ -707,7 +707,7 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if (completions) { let filterCompletions = completions.entries.filter(e => e.name === symbol); filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions; @@ -717,7 +717,7 @@ namespace FourSlash { // then these symbols must meet the criterion for Not supposed to be in the list. So we // raise an error let error = "Completion list did contain \'" + symbol + "\'."; - let details = this.getCompletionEntryDetails(filterCompletions[0].name); + const details = this.getCompletionEntryDetails(filterCompletions[0].name); if (expectedText) { error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + "."; } @@ -735,7 +735,7 @@ namespace FourSlash { public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) { this.taoInvalidReason = "verifyCompletionEntryDetails NYI"; - let details = this.getCompletionEntryDetails(entryName); + const details = this.getCompletionEntryDetails(entryName); assert.equal(ts.displayPartsToString(details.displayParts), expectedText, assertionMessage("completion entry details text")); @@ -751,14 +751,14 @@ namespace FourSlash { public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = "verifyReferencesAtPositionListContains NYI"; - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); if (!references || references.length === 0) { this.raiseError("verifyReferencesAtPositionListContains failed - found 0 references, expected at least one."); } for (let i = 0; i < references.length; i++) { - let reference = references[i]; + const reference = references[i]; 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 does not match, actual: ${reference.isWriteAccess}, expected: ${isWriteAccess}.`); @@ -767,18 +767,18 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(references)})`); } public verifyReferencesCountIs(count: number, localFilesOnly = true) { this.taoInvalidReason = "verifyReferences NYI"; - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); let referencesCount = 0; if (localFilesOnly) { - let localFiles = this.testData.files.map(file => file.fileName); + const localFiles = this.testData.files.map(file => file.fileName); // Count only the references in local files. Filter the ones in lib and other files. ts.forEach(references, entry => { if (localFiles.some((fileName) => fileName === entry.fileName)) { @@ -791,7 +791,7 @@ namespace FourSlash { } if (referencesCount !== count) { - let condition = localFilesOnly ? "excluding libs" : "including libs"; + const condition = localFilesOnly ? "excluding libs" : "including libs"; this.raiseError("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount); } } @@ -817,18 +817,18 @@ namespace FourSlash { } public getSyntacticDiagnostics(expected: string) { - let diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } public getSemanticDiagnostics(expected: string) { - let diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + const diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } private testDiagnostics(expected: string, diagnostics: ts.Diagnostic[]) { - let realized = ts.realizeDiagnostics(diagnostics, "\r\n"); - let actual = JSON.stringify(realized, null, " "); + const realized = ts.realizeDiagnostics(diagnostics, "\r\n"); + const actual = JSON.stringify(realized, null, " "); assert.equal(actual, expected); } @@ -840,9 +840,9 @@ namespace FourSlash { } }); - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; - let actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; + const actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; if (negative) { if (expectedText !== undefined) { @@ -888,7 +888,7 @@ namespace FourSlash { return result; } - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind")); assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers")); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); @@ -897,7 +897,7 @@ namespace FourSlash { } public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { let references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); @@ -919,8 +919,8 @@ namespace FourSlash { references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start); for (let i = 0, n = ranges.length; i < n; i++) { - let reference = references[i]; - let range = ranges[i]; + const reference = references[i]; + const range = ranges[i]; if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) { @@ -937,7 +937,7 @@ namespace FourSlash { public verifyQuickInfoExists(negative: boolean) { this.taoInvalidReason = "verifyQuickInfoExists NYI"; - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (negative) { if (actualQuickInfo) { this.raiseError("verifyQuickInfoExists failed. Expected quick info NOT to exist"); @@ -953,7 +953,7 @@ namespace FourSlash { public verifyCurrentSignatureHelpIs(expected: string) { this.taoInvalidReason = "verifyCurrentSignatureHelpIs NYI"; - let help = this.getActiveSignatureHelpItem(); + const help = this.getActiveSignatureHelpItem(); assert.equal( ts.displayPartsToString(help.prefixDisplayParts) + help.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(help.separatorDisplayParts)) + @@ -963,7 +963,7 @@ namespace FourSlash { public verifyCurrentParameterIsletiable(isVariable: boolean) { this.taoInvalidReason = "verifyCurrentParameterIsletiable NYI"; - let signature = this.getActiveSignatureHelpItem(); + const signature = this.getActiveSignatureHelpItem(); assert.isNotNull(signature); assert.equal(isVariable, signature.isVariadic); } @@ -971,24 +971,24 @@ namespace FourSlash { public verifyCurrentParameterHelpName(name: string) { this.taoInvalidReason = "verifyCurrentParameterHelpName NYI"; - let activeParameter = this.getActiveParameter(); - let activeParameterName = activeParameter.name; + const activeParameter = this.getActiveParameter(); + const activeParameterName = activeParameter.name; assert.equal(activeParameterName, name); } public verifyCurrentParameterSpanIs(parameter: string) { this.taoInvalidReason = "verifyCurrentParameterSpanIs NYI"; - let activeSignature = this.getActiveSignatureHelpItem(); - let activeParameter = this.getActiveParameter(); + const activeSignature = this.getActiveSignatureHelpItem(); + const activeParameter = this.getActiveParameter(); assert.equal(ts.displayPartsToString(activeParameter.displayParts), parameter); } public verifyCurrentParameterHelpDocComment(docComment: string) { this.taoInvalidReason = "verifyCurrentParameterHelpDocComment NYI"; - let activeParameter = this.getActiveParameter(); - let activeParameterDocComment = activeParameter.documentation; + const activeParameter = this.getActiveParameter(); + const activeParameterDocComment = activeParameter.documentation; assert.equal(ts.displayPartsToString(activeParameterDocComment), docComment, assertionMessage("current parameter Help DocComment")); } @@ -1007,7 +1007,7 @@ namespace FourSlash { public verifyCurrentSignatureHelpDocComment(docComment: string) { this.taoInvalidReason = "verifyCurrentSignatureHelpDocComment NYI"; - let actualDocComment = this.getActiveSignatureHelpItem().documentation; + const actualDocComment = this.getActiveSignatureHelpItem().documentation; assert.equal(ts.displayPartsToString(actualDocComment), docComment, assertionMessage("current signature help doc comment")); } @@ -1015,22 +1015,22 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let actual = help && help.items ? help.items.length : 0; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = help && help.items ? help.items.length : 0; assert.equal(actual, expected); } public verifySignatureHelpArgumentCount(expected: number) { this.taoInvalidReason = "verifySignatureHelpArgumentCount NYI"; - let signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let actual = signatureHelpItems.argumentCount; + const signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = signatureHelpItems.argumentCount; assert.equal(actual, expected); } public verifySignatureHelpPresent(shouldBePresent = true) { this.taoInvalidReason = "verifySignatureHelpPresent NYI"; - let actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); if (shouldBePresent) { if (!actual) { this.raiseError("Expected signature help to be present, but it wasn't"); @@ -1050,7 +1050,7 @@ namespace FourSlash { } public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { this.raiseError("Rename did not succeed"); } @@ -1064,7 +1064,7 @@ namespace FourSlash { this.raiseError("Expected a single range to be selected in the test file."); } - let expectedRange = this.getRanges()[0]; + const expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.start || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.start + "," + expectedRange.end + "). Got [" + @@ -1073,7 +1073,7 @@ namespace FourSlash { } public verifyRenameInfoFailed(message?: string) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { this.raiseError("Rename was expected to fail"); } @@ -1082,15 +1082,15 @@ namespace FourSlash { } private getActiveSignatureHelpItem() { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let index = help.selectedItemIndex; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const index = help.selectedItemIndex; return help.items[index]; } private getActiveParameter(): ts.SignatureHelpParameter { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let item = help.items[help.selectedItemIndex]; - let currentParam = help.argumentIndex; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const item = help.items[help.selectedItemIndex]; + const currentParam = help.argumentIndex; return item.parameters[currentParam]; } @@ -1099,8 +1099,8 @@ namespace FourSlash { private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) { let resultString = "SpanInfo: " + JSON.stringify(spanInfo); if (spanInfo) { - let spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); - let spanLineMap = ts.computeLineStarts(spanString); + const spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); + const spanLineMap = ts.computeLineStarts(spanString); for (let i = 0; i < spanLineMap.length; i++) { if (!i) { resultString += "\n"; @@ -1114,17 +1114,17 @@ namespace FourSlash { } private baselineCurrentFileLocations(getSpanAtPos: (pos: number) => ts.TextSpan): string { - let fileLineMap = ts.computeLineStarts(this.activeFile.content); + const fileLineMap = ts.computeLineStarts(this.activeFile.content); let nextLine = 0; let resultString = ""; let currentLine: string; let previousSpanInfo: string; let startColumn: number; let length: number; - let prefixString = " >"; + const prefixString = " >"; let pos = 0; - let addSpanInfoString = () => { + const addSpanInfoString = () => { if (previousSpanInfo) { resultString += currentLine; let thisLineMarker = repeatString(startColumn, " ") + repeatString(length, "~"); @@ -1147,7 +1147,7 @@ namespace FourSlash { startColumn = 0; length = 0; } - let spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); + const spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); if (previousSpanInfo && previousSpanInfo !== spanInfo) { addSpanInfoString(); previousSpanInfo = spanInfo; @@ -1191,11 +1191,11 @@ namespace FourSlash { public baselineGetEmitOutput() { this.taoInvalidReason = "baselineGetEmitOutput impossible"; // Find file to be emitted - let emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on + const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on - let allFourSlashFiles = this.testData.files; + const allFourSlashFiles = this.testData.files; for (let idx = 0; idx < allFourSlashFiles.length; ++idx) { - let file = allFourSlashFiles[idx]; + const file = allFourSlashFiles[idx]; if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") { // Find a file with the flag emitThisFile turned on emitFiles.push(file); @@ -1214,20 +1214,20 @@ namespace FourSlash { let resultString = ""; // Loop through all the emittedFiles and emit them one by one emitFiles.forEach(emitFile => { - let emitOutput = this.languageService.getEmitOutput(emitFile.fileName); + const emitOutput = this.languageService.getEmitOutput(emitFile.fileName); // Print emitOutputStatus in readable format resultString += "EmitSkipped: " + emitOutput.emitSkipped + Harness.IO.newLine(); if (emitOutput.emitSkipped) { resultString += "Diagnostics:" + Harness.IO.newLine(); - let diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); + const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); for (let i = 0, n = diagnostics.length; i < n; i++) { resultString += " " + diagnostics[0].messageText + Harness.IO.newLine(); } } emitOutput.outputFiles.forEach((outputFile, idx, array) => { - let fileName = "FileName : " + outputFile.name + Harness.IO.newLine(); + const fileName = "FileName : " + outputFile.name + Harness.IO.newLine(); resultString = resultString + fileName + outputFile.text; }); resultString += Harness.IO.newLine(); @@ -1247,19 +1247,19 @@ namespace FourSlash { } public printCurrentParameterHelp() { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(help)); } public printCurrentQuickInfo() { - let quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(quickInfo)); } public printErrorList() { - let syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); - let semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); - let errorList = syntacticErrors.concat(semanticErrors); + const syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + const semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + const errorList = syntacticErrors.concat(semanticErrors); Harness.IO.log(`Error list (${errorList.length} errors)`); if (errorList.length) { @@ -1274,8 +1274,8 @@ namespace FourSlash { public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) { for (let i = 0; i < this.testData.files.length; i++) { - let file = this.testData.files[i]; - let active = (this.activeFile === file); + const file = this.testData.files[i]; + const active = (this.activeFile === file); Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`); let content = this.getFileContent(file.fileName); if (active) { @@ -1289,22 +1289,22 @@ namespace FourSlash { } public printCurrentSignatureHelp() { - let sigHelp = this.getActiveSignatureHelpItem(); + const sigHelp = this.getActiveSignatureHelpItem(); Harness.IO.log(JSON.stringify(sigHelp)); } public printMemberListMembers() { - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); Harness.IO.log(JSON.stringify(members)); } public printCompletionListMembers() { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); Harness.IO.log(JSON.stringify(completions)); } public printReferences() { - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); ts.forEach(references, entry => { Harness.IO.log(JSON.stringify(entry)); }); @@ -1318,9 +1318,9 @@ namespace FourSlash { this.scenarioActions.push(``); let offset = this.currentCaretPosition; - let ch = ""; + const ch = ""; - let checkCadence = (count >> 2) + 1; + const checkCadence = (count >> 2) + 1; for (let i = 0; i < count; i++) { // Make the edit @@ -1333,7 +1333,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); // this.checkPostEditInletiants(); @@ -1360,8 +1360,8 @@ namespace FourSlash { this.scenarioActions.push(``); let offset = this.currentCaretPosition; - let ch = ""; - let checkCadence = (count >> 2) + 1; + const ch = ""; + const checkCadence = (count >> 2) + 1; for (let i = 0; i < count; i++) { offset--; @@ -1375,7 +1375,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); } @@ -1406,12 +1406,12 @@ namespace FourSlash { // as much as possible private typeHighFidelity(text: string) { let offset = this.currentCaretPosition; - let prevChar = " "; - let checkCadence = (text.length >> 2) + 1; + const prevChar = " "; + const checkCadence = (text.length >> 2) + 1; for (let i = 0; i < text.length; i++) { // Make the edit - let ch = text.charAt(i); + const ch = text.charAt(i); this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch); this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset); @@ -1435,7 +1435,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); // this.checkPostEditInletiants(); @@ -1454,7 +1454,7 @@ namespace FourSlash { public paste(text: string) { this.scenarioActions.push(``); - let start = this.currentCaretPosition; + const start = this.currentCaretPosition; let offset = this.currentCaretPosition; this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, text); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, text); @@ -1463,7 +1463,7 @@ namespace FourSlash { // Handle formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); this.checkPostEditInletiants(); @@ -1484,17 +1484,17 @@ namespace FourSlash { return; } - let incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); + const incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined); - let incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; + const incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; // Check syntactic structure - let content = this.getFileContent(this.activeFile.fileName); + const content = this.getFileContent(this.activeFile.fileName); - let referenceSourceFile = ts.createLanguageServiceSourceFile( + const referenceSourceFile = ts.createLanguageServiceSourceFile( this.activeFile.fileName, createScriptSnapShot(content), ts.ScriptTarget.Latest, /*version:*/ "0", /*setNodeParents:*/ false); - let referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; + const referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics); Utils.assertStructuralEquals(incrementalSourceFile, referenceSourceFile); @@ -1504,7 +1504,7 @@ namespace FourSlash { // The caret can potentially end up between the \r and \n, which is confusing. If // that happens, move it back one character if (this.currentCaretPosition > 0) { - let ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); + const ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); if (ch === "\r") { this.currentCaretPosition--; } @@ -1517,18 +1517,18 @@ namespace FourSlash { let runningOffset = 0; 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 - let oldContent = this.getFileContent(this.activeFile.fileName); + const oldContent = this.getFileContent(this.activeFile.fileName); for (let j = 0; j < edits.length; j++) { this.languageServiceAdapterHost.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); - let change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; + const 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); } if (isFormattingEdit) { - let newContent = this.getFileContent(fileName); + const newContent = this.getFileContent(fileName); if (newContent.replace(/\s/g, "") !== oldContent.replace(/\s/g, "")) { this.raiseError("Formatting operation destroyed non-whitespace content"); @@ -1542,7 +1542,7 @@ namespace FourSlash { } public setFormatOptions(formatCodeOptions: ts.FormatCodeOptions): ts.FormatCodeOptions { - let oldFormatCodeOptions = this.formatCodeOptions; + const oldFormatCodeOptions = this.formatCodeOptions; this.formatCodeOptions = formatCodeOptions; return oldFormatCodeOptions; } @@ -1550,7 +1550,7 @@ namespace FourSlash { public formatDocument() { this.scenarioActions.push(""); - let edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } @@ -1558,14 +1558,14 @@ namespace FourSlash { public formatSelection(start: number, end: number) { this.taoInvalidReason = "formatSelection NYI"; - let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } private updateMarkersForEdit(fileName: string, minChar: number, limChar: number, text: string) { for (let i = 0; i < this.testData.markers.length; i++) { - let marker = this.testData.markers[i]; + const marker = this.testData.markers[i]; if (marker.fileName === fileName) { if (marker.position > minChar) { if (marker.position < limChar) { @@ -1586,7 +1586,7 @@ namespace FourSlash { } public goToEOF() { - let len = this.getFileContent(this.activeFile.fileName).length; + const len = this.getFileContent(this.activeFile.fileName).length; this.goToPosition(len); } @@ -1598,7 +1598,7 @@ namespace FourSlash { this.taoInvalidReason = "GoToDefinition not supported for non-zero definition indices"; } - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError("goToDefinition failed - expected to at least one definition location but got 0"); } @@ -1607,7 +1607,7 @@ namespace FourSlash { this.raiseError(`goToDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`); } - let definition = definitions[definitionIndex]; + const definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1620,7 +1620,7 @@ namespace FourSlash { this.taoInvalidReason = "GoToTypeDefinition not supported for non-zero definition indices"; } - let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0"); } @@ -1629,7 +1629,7 @@ namespace FourSlash { this.raiseError(`goToTypeDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`); } - let definition = definitions[definitionIndex]; + const definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1637,9 +1637,9 @@ namespace FourSlash { public verifyDefinitionLocationExists(negative: boolean) { this.taoInvalidReason = "verifyDefinitionLocationExists NYI"; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let foundDefinitions = definitions && definitions.length; + const foundDefinitions = definitions && definitions.length; if (foundDefinitions && negative) { this.raiseError(`goToDefinition - expected to 0 definition locations but got ${definitions.length}`); @@ -1650,19 +1650,19 @@ namespace FourSlash { } public verifyDefinitionsCount(negative: boolean, expectedCount: number) { - let assertFn = negative ? assert.notEqual : assert.equal; + const assertFn = negative ? assert.notEqual : assert.equal; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualCount = definitions && definitions.length || 0; + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count")); } public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) { - let assertFn = negative ? assert.notEqual : assert.equal; + const assertFn = negative ? assert.notEqual : assert.equal; - let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualCount = definitions && definitions.length || 0; + const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count")); } @@ -1670,9 +1670,9 @@ namespace FourSlash { public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) { this.taoInvalidReason = "verifyDefinititionsInfo NYI"; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; - let actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; + const actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; if (negative) { assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name")); assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name")); @@ -1696,7 +1696,7 @@ namespace FourSlash { public verifyCaretAtMarker(markerName = "") { this.taoInvalidReason = "verifyCaretAtMarker NYI"; - let pos = this.getMarkerByName(markerName); + const pos = this.getMarkerByName(markerName); if (pos.fileName !== this.activeFile.fileName) { throw new Error(`verifyCaretAtMarker failed - expected to be in file "${pos.fileName}", but was in file "${this.activeFile.fileName}"`); } @@ -1707,7 +1707,7 @@ namespace FourSlash { private getIndentation(fileName: string, position: number, indentStyle: ts.IndentStyle): number { - let formatOptions = ts.clone(this.formatCodeOptions); + const formatOptions = ts.clone(this.formatCodeOptions); formatOptions.IndentStyle = indentStyle; return this.languageService.getIndentationAtPosition(fileName, position, formatOptions); @@ -1716,8 +1716,8 @@ namespace FourSlash { public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { this.taoInvalidReason = "verifyIndentationAtCurrentPosition NYI"; - let actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle); - let lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); + const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle); + const lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtCurrentPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); } @@ -1726,8 +1726,8 @@ namespace FourSlash { public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { this.taoInvalidReason = "verifyIndentationAtPosition NYI"; - let actual = this.getIndentation(fileName, position, indentStyle); - let lineCol = this.getLineColStringAtPosition(position); + const actual = this.getIndentation(fileName, position, indentStyle); + const lineCol = this.getLineColStringAtPosition(position); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); } @@ -1736,7 +1736,7 @@ namespace FourSlash { public verifyCurrentLineContent(text: string) { this.taoInvalidReason = "verifyCurrentLineContent NYI"; - let actual = this.getCurrentLineContent(); + const actual = this.getCurrentLineContent(); if (actual !== text) { throw new Error("verifyCurrentLineContent\n" + "\tExpected: \"" + text + "\"\n" + @@ -1747,8 +1747,8 @@ namespace FourSlash { public verifyCurrentFileContent(text: string) { this.taoInvalidReason = "verifyCurrentFileContent NYI"; - let actual = this.getFileContent(this.activeFile.fileName); - let replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); + const actual = this.getFileContent(this.activeFile.fileName); + const replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); if (replaceNewlines(actual) !== replaceNewlines(text)) { throw new Error("verifyCurrentFileContent\n" + "\tExpected: \"" + text + "\"\n" + @@ -1759,7 +1759,7 @@ namespace FourSlash { public verifyTextAtCaretIs(text: string) { this.taoInvalidReason = "verifyCurrentFileContent NYI"; - let actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); + const actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); if (actual !== text) { throw new Error("verifyTextAtCaretIs\n" + "\tExpected: \"" + text + "\"\n" + @@ -1770,14 +1770,14 @@ namespace FourSlash { public verifyCurrentNameOrDottedNameSpanText(text: string) { this.taoInvalidReason = "verifyCurrentNameOrDottedNameSpanText NYI"; - let span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); + const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); if (!span) { this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + "\tExpected: \"" + text + "\"\n" + "\t Actual: undefined"); } - let actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); + const actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); if (actual !== text) { this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + "\tExpected: \"" + text + "\"\n" + @@ -1815,10 +1815,10 @@ namespace FourSlash { } for (let i = 0; i < expected.length; i++) { - let expectedClassification = expected[i]; - let actualClassification = actual[i]; + const expectedClassification = expected[i]; + const actualClassification = actual[i]; - let expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; + const expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; if (expectedType !== actualClassification.classificationType) { this.raiseError("verifyClassifications failed - expected classifications type to be " + expectedType + ", but was " + @@ -1826,11 +1826,11 @@ namespace FourSlash { jsonMismatchString()); } - let expectedSpan = expectedClassification.textSpan; - let actualSpan = actualClassification.textSpan; + const expectedSpan = expectedClassification.textSpan; + const actualSpan = actualClassification.textSpan; if (expectedSpan) { - let expectedLength = expectedSpan.end - expectedSpan.start; + const expectedLength = expectedSpan.end - expectedSpan.start; if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) { this.raiseError("verifyClassifications failed - expected span of text to be " + @@ -1840,7 +1840,7 @@ namespace FourSlash { } } - let actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); + const 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 " + @@ -1858,7 +1858,7 @@ namespace FourSlash { public verifyProjectInfo(expected: string[]) { if (this.testType === FourSlashTestType.Server) { - let actual = (this.languageService).getProjectInfo( + const actual = (this.languageService).getProjectInfo( this.activeFile.fileName, /* needFileNameList */ true ); @@ -1872,14 +1872,14 @@ namespace FourSlash { } public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) { - let actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, + const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); } public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) { - let actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, + const actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); @@ -1888,15 +1888,15 @@ namespace FourSlash { public verifyOutliningSpans(spans: TextSpan[]) { this.taoInvalidReason = "verifyOutliningSpans NYI"; - let actual = this.languageService.getOutliningSpans(this.activeFile.fileName); + const actual = this.languageService.getOutliningSpans(this.activeFile.fileName); if (actual.length !== spans.length) { this.raiseError(`verifyOutliningSpans failed - expected total spans to be ${spans.length}, but was ${actual.length}`); } for (let i = 0; i < spans.length; i++) { - let expectedSpan = spans[i]; - let actualSpan = actual[i]; + const expectedSpan = spans[i]; + const actualSpan = actual[i]; 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)})`); } @@ -1904,7 +1904,7 @@ namespace FourSlash { } public verifyTodoComments(descriptors: string[], spans: TextSpan[]) { - let actual = this.languageService.getTodoComments(this.activeFile.fileName, + const actual = this.languageService.getTodoComments(this.activeFile.fileName, descriptors.map(d => { return { text: d, priority: 0 }; })); if (actual.length !== spans.length) { @@ -1912,9 +1912,9 @@ namespace FourSlash { } for (let i = 0; i < spans.length; i++) { - let expectedSpan = spans[i]; - let actualComment = actual[i]; - let actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); + const expectedSpan = spans[i]; + const actualComment = actual[i]; + const actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); 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)})`); @@ -1924,7 +1924,7 @@ namespace FourSlash { public verifyDocCommentTemplate(expected?: ts.TextInsertion) { const name = "verifyDocCommentTemplate"; - let actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (expected === undefined) { if (actual) { @@ -1958,7 +1958,7 @@ namespace FourSlash { public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) { this.taoInvalidReason = "verifyMatchingBracePosition NYI"; - let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 2) { this.raiseError(`verifyMatchingBracePosition failed - expected result to contain 2 spans, but it had ${actual.length}`); @@ -1983,7 +1983,7 @@ namespace FourSlash { public verifyNoMatchingBracePosition(bracePosition: number) { this.taoInvalidReason = "verifyNoMatchingBracePosition NYI"; - let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 0) { this.raiseError("verifyNoMatchingBracePosition failed - expected: 0 spans, actual: " + actual.length); @@ -1997,7 +1997,7 @@ namespace FourSlash { public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string) { this.taoInvalidReason = "verifyNavigationItemsCount NYI"; - let items = this.languageService.getNavigateToItems(searchValue); + const items = this.languageService.getNavigateToItems(searchValue); let actual = 0; let item: ts.NavigateToItem = null; @@ -2027,14 +2027,14 @@ namespace FourSlash { parentName?: string) { this.taoInvalidReason = "verifyNavigationItemsListContains NYI"; - let items = this.languageService.getNavigateToItems(searchValue); + const items = this.languageService.getNavigateToItems(searchValue); if (!items || items.length === 0) { this.raiseError("verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one."); } for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item && item.name === name && item.kind === kind && (matchKind === undefined || item.matchKind === matchKind) && (fileName === undefined || item.fileName === fileName) && @@ -2045,7 +2045,7 @@ namespace FourSlash { // if there was an explicit match kind specified, then it should be validated. if (matchKind !== undefined) { - let missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; + const missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; this.raiseError(`verifyNavigationItemsListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items)})`); } } @@ -2053,8 +2053,8 @@ namespace FourSlash { public verifyGetScriptLexicalStructureListCount(expected: number) { this.taoInvalidReason = "verifyNavigationItemsListContains impossible"; - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - let actual = this.getNavigationBarItemsCount(items); + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const actual = this.getNavigationBarItemsCount(items); if (expected !== actual) { this.raiseError(`verifyGetScriptLexicalStructureListCount failed - found: ${actual} navigation items, expected: ${expected}.`); @@ -2076,7 +2076,7 @@ namespace FourSlash { public verifyGetScriptLexicalStructureListContains(name: string, kind: string) { this.taoInvalidReason = "verifyGetScriptLexicalStructureListContains impossible"; - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); if (!items || items.length === 0) { this.raiseError("verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one."); @@ -2086,14 +2086,14 @@ namespace FourSlash { return; } - let missingItem = { name: name, kind: kind }; + const missingItem = { name: name, kind: kind }; this.raiseError(`verifyGetScriptLexicalStructureListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items, null, " ")})`); } private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) { if (items) { for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item && item.text === name && item.kind === kind) { return true; } @@ -2108,25 +2108,25 @@ namespace FourSlash { } public printNavigationItems(searchValue: string) { - let items = this.languageService.getNavigateToItems(searchValue); - let length = items && items.length; + const items = this.languageService.getNavigateToItems(searchValue); + const length = items && items.length; Harness.IO.log(`NavigationItems list (${length} items)`); for (let i = 0; i < length; i++) { - let item = items[i]; + const item = items[i]; Harness.IO.log(`name: ${item.name}, kind: ${item.kind}, parentName: ${item.containerName}, fileName: ${item.fileName}`); } } public printScriptLexicalStructureItems() { - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - let length = items && items.length; + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const length = items && items.length; Harness.IO.log(`NavigationItems list (${length} items)`); for (let i = 0; i < length; i++) { - let item = items[i]; + const item = items[i]; Harness.IO.log(`name: ${item.text}, kind: ${item.kind}`); } } @@ -2138,13 +2138,13 @@ namespace FourSlash { public verifyOccurrencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = "verifyOccurrencesAtPositionListContains NYI"; - let occurrences = this.getOccurrencesAtCurrentPosition(); + const occurrences = this.getOccurrencesAtCurrentPosition(); if (!occurrences || occurrences.length === 0) { this.raiseError("verifyOccurrencesAtPositionListContains failed - found 0 references, expected at least one."); } - for (let occurrence of occurrences) { + for (const occurrence of occurrences) { if (occurrence && occurrence.fileName === fileName && occurrence.textSpan.start === start && ts.textSpanEnd(occurrence.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && occurrence.isWriteAccess !== isWriteAccess) { this.raiseError(`verifyOccurrencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${occurrence.isWriteAccess}, expected: ${isWriteAccess}.`); @@ -2153,39 +2153,39 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError(`verifyOccurrencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(occurrences)})`); } public verifyOccurrencesAtPositionListCount(expectedCount: number) { this.taoInvalidReason = "verifyOccurrencesAtPositionListCount NYI"; - let occurrences = this.getOccurrencesAtCurrentPosition(); - let actualCount = occurrences ? occurrences.length : 0; + const occurrences = this.getOccurrencesAtCurrentPosition(); + const actualCount = occurrences ? occurrences.length : 0; if (expectedCount !== actualCount) { this.raiseError(`verifyOccurrencesAtPositionListCount failed - actual: ${actualCount}, expected:${expectedCount}`); } } private getDocumentHighlightsAtCurrentPosition(fileNamesToSearch: string[]) { - let filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name)); + const filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name)); return this.languageService.getDocumentHighlights(this.activeFile.fileName, this.currentCaretPosition, filesToSearch); } public verifyDocumentHighlightsAtPositionListContains(fileName: string, start: number, end: number, fileNamesToSearch: string[], kind?: string) { this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListContains NYI"; - let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); + const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); if (!documentHighlights || documentHighlights.length === 0) { this.raiseError("verifyDocumentHighlightsAtPositionListContains failed - found 0 highlights, expected at least one."); } - for (let documentHighlight of documentHighlights) { + for (const documentHighlight of documentHighlights) { if (documentHighlight.fileName === fileName) { - let { highlightSpans } = documentHighlight; + const { highlightSpans } = documentHighlight; - for (let highlight of highlightSpans) { + for (const highlight of highlightSpans) { if (highlight && highlight.textSpan.start === start && ts.textSpanEnd(highlight.textSpan) === end) { if (typeof kind !== "undefined" && highlight.kind !== kind) { this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - item "kind" value does not match, actual: ${highlight.kind}, expected: ${kind}.`); @@ -2196,15 +2196,15 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, kind: kind }; + const missingItem = { fileName: fileName, start: start, end: end, kind: kind }; this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(documentHighlights)})`); } public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) { this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListCount NYI"; - let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); - let actualCount = documentHighlights + const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); + const actualCount = documentHighlights ? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0) : 0; @@ -2215,13 +2215,13 @@ namespace FourSlash { // Get the text of the entire line the caret is currently at private getCurrentLineContent() { - let text = this.getFileContent(this.activeFile.fileName); + const text = this.getFileContent(this.activeFile.fileName); - let pos = this.currentCaretPosition; + const pos = this.currentCaretPosition; let startPos = pos, endPos = pos; while (startPos > 0) { - let ch = text.charCodeAt(startPos - 1); + const ch = text.charCodeAt(startPos - 1); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; } @@ -2230,7 +2230,7 @@ namespace FourSlash { } while (endPos < text.length) { - let ch = text.charCodeAt(endPos); + const ch = text.charCodeAt(endPos); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; @@ -2251,10 +2251,10 @@ namespace FourSlash { } for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item.name === name) { if (documentation != undefined || text !== undefined) { - let details = this.getCompletionEntryDetails(item.name); + const details = this.getCompletionEntryDetails(item.name); if (documentation !== undefined) { assert.equal(ts.displayPartsToString(details.documentation), documentation, assertionMessage("completion item documentation")); @@ -2272,7 +2272,7 @@ namespace FourSlash { } } - let itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); + const itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); this.raiseError(`Expected "${JSON.stringify({ name, text, documentation, kind })}" to be in list [${itemsString}]`); } @@ -2280,7 +2280,7 @@ namespace FourSlash { private findFile(indexOrName: any) { let result: FourSlashFile = null; if (typeof indexOrName === "number") { - let index = indexOrName; + const index = indexOrName; if (index >= this.testData.files.length) { throw new Error(`File index (${index}) in openFile was out of range. There are only ${this.testData.files.length} files in this test.`); } @@ -2294,10 +2294,10 @@ namespace FourSlash { // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; - let availableNames: string[] = []; + const availableNames: string[] = []; let foundIt = false; for (let i = 0; i < this.testData.files.length; i++) { - let fn = this.testData.files[i].fileName; + const fn = this.testData.files[i].fileName; if (fn) { if (fn === name) { result = this.testData.files[i]; @@ -2320,15 +2320,15 @@ namespace FourSlash { } private getLineColStringAtPosition(position: number) { - let pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); + const pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); return `line ${(pos.line + 1)}, col ${pos.character}`; } public getMarkerByName(markerName: string) { - let markerPos = this.testData.markerPositions[markerName]; + const markerPos = this.testData.markerPositions[markerName]; if (markerPos === undefined) { - let markerNames: string[] = []; - for (let m in this.testData.markerPositions) markerNames.push(m); + const markerNames: string[] = []; + for (const m in this.testData.markerPositions) markerNames.push(m); throw new Error(`Unknown marker "${markerName}" Available markers: ${markerNames.map(m => "\"" + m + "\"").join(", ")}`); } else { @@ -2358,12 +2358,12 @@ namespace FourSlash { } // TOOD: should these just use the Harness's stdout/stderr? - let fsOutput = new Harness.Compiler.WriterAggregator(); - let fsErrors = new Harness.Compiler.WriterAggregator(); + const fsOutput = new Harness.Compiler.WriterAggregator(); + const fsErrors = new Harness.Compiler.WriterAggregator(); export let xmlData: TestXmlData[] = []; export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) { - let content = Harness.IO.readFile(fileName); - let xml = runFourSlashTestContent(basePath, testType, content, fileName); + const content = Harness.IO.readFile(fileName); + const xml = runFourSlashTestContent(basePath, testType, content, fileName); xmlData.push(xml); } @@ -2371,12 +2371,12 @@ namespace FourSlash { // here we cache the JS output and reuse it for every test. let fourslashJsOutput: string; { - let host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFileName, content: undefined }], + const host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFileName, content: undefined }], (fn, contents) => fourslashJsOutput = contents, ts.ScriptTarget.Latest, Harness.IO.useCaseSensitiveFileNames()); - let program = ts.createProgram([Harness.Compiler.fourslashFileName], { noResolve: true, target: ts.ScriptTarget.ES3 }, host); + const program = ts.createProgram([Harness.Compiler.fourslashFileName], { noResolve: true, target: ts.ScriptTarget.ES3 }, host); program.emit(host.getSourceFile(Harness.Compiler.fourslashFileName, ts.ScriptTarget.ES3)); } @@ -2384,12 +2384,12 @@ namespace FourSlash { export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): TestXmlData { // Parse out the files and their metadata - let testData = parseTestData(basePath, content, fileName); + const testData = parseTestData(basePath, content, fileName); currentTestState = new TestState(basePath, testType, testData); let result = ""; - let host = Harness.Compiler.createCompilerHost( + const host = Harness.Compiler.createCompilerHost( [ { unitName: Harness.Compiler.fourslashFileName, content: undefined }, { unitName: fileName, content: content } @@ -2398,11 +2398,11 @@ namespace FourSlash { ts.ScriptTarget.Latest, Harness.IO.useCaseSensitiveFileNames()); - let program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host); + const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host); - let sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3); + const sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3); - let diagnostics = ts.getPreEmitDiagnostics(program, sourceFile); + const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile); if (diagnostics.length > 0) { throw new Error(`Error compiling ${fileName}: ` + diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n")); @@ -2422,13 +2422,13 @@ namespace FourSlash { throw err; } - let xmlData = currentTestState.getTestXmlData(); + const xmlData = currentTestState.getTestXmlData(); xmlData.originalName = fileName; return xmlData; } function chompLeadingSpace(content: string) { - let lines = content.split("\n"); + const lines = content.split("\n"); for (let i = 0; i < lines.length; i++) { if ((lines[i].length !== 0) && (lines[i].charAt(0) !== " ")) { return content; @@ -2440,22 +2440,22 @@ namespace FourSlash { function parseTestData(basePath: string, contents: string, fileName: string): FourSlashData { // Regex for parsing options in the format "@Alpha: Value of any sort" - let optionRegex = /^\s*@(\w+): (.*)\s*/; + const optionRegex = /^\s*@(\w+): (.*)\s*/; // List of all the subfiles we've parsed out - let files: FourSlashFile[] = []; + const files: FourSlashFile[] = []; // Global options - let globalOptions: { [s: string]: string; } = {}; + const globalOptions: { [s: string]: string; } = {}; // Marker positions // Split up the input file by line // Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so // we have to string-based splitting instead and try to figure out the delimiting chars - let lines = contents.split("\n"); + const lines = contents.split("\n"); - let markerPositions: MarkerMap = {}; - let markers: Marker[] = []; - let ranges: Range[] = []; + const markerPositions: MarkerMap = {}; + const markers: Marker[] = []; + const ranges: Range[] = []; // Stuff related to the subfile we're parsing let currentFileContent: string = null; @@ -2464,7 +2464,7 @@ namespace FourSlash { for (let i = 0; i < lines.length; i++) { let line = lines[i]; - let lineLength = line.length; + const lineLength = line.length; if (lineLength > 0 && line.charAt(lineLength - 1) === "\r") { line = line.substr(0, lineLength - 1); @@ -2486,9 +2486,9 @@ namespace FourSlash { } else if (line.substr(0, 2) === "//") { // Comment line, check for global/file @options and record them - let match = optionRegex.exec(line.substr(2)); + const match = optionRegex.exec(line.substr(2)); if (match) { - let fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); + const fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); if (fileMetadataNamesIndex === -1) { // Check if the match is already existed in the global options if (globalOptions[match[1]] !== undefined) { @@ -2500,7 +2500,7 @@ namespace FourSlash { if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) { // Found an @FileName directive, if this is not the first then create a new subfile if (currentFileContent) { - let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2530,7 +2530,7 @@ namespace FourSlash { else { // Empty line or code line, terminate current subfile if there is one if (currentFileContent) { - let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2573,7 +2573,7 @@ namespace FourSlash { } function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): string { - for (let option in optionObject) { + for (const option in optionObject) { if (option !== metadataOptionNames.fileName) { return option; } @@ -2588,7 +2588,7 @@ namespace FourSlash { } function reportError(fileName: string, line: number, col: number, message: string) { - let errorMessage = fileName + "(" + line + "," + col + "): " + message; + const errorMessage = fileName + "(" + line + "," + col + "): " + message; throw new Error(errorMessage); } @@ -2607,7 +2607,7 @@ namespace FourSlash { return null; } - let marker: Marker = { + const marker: Marker = { fileName: fileName, position: location.position, data: markerValue @@ -2624,14 +2624,14 @@ namespace FourSlash { } function recordMarker(fileName: string, location: ILocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker { - let marker: Marker = { + const marker: Marker = { fileName: fileName, position: location.position }; // Verify markers for uniqueness if (markerMap[name] !== undefined) { - let message = "Marker '" + name + "' is duplicated in the source file contents."; + const message = "Marker '" + name + "' is duplicated in the source file contents."; reportError(marker.fileName, location.sourceLine, location.sourceColumn, message); return null; } @@ -2646,7 +2646,7 @@ namespace FourSlash { content = chompLeadingSpace(content); // Any slash-star comment with a character not in this string is not a marker. - let validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_"; + const validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_"; /// The file content (minus metacharacters) so far let output = ""; @@ -2655,7 +2655,7 @@ namespace FourSlash { let openMarker: ILocationInformation = null; /// A stack of the open range markers that are still unclosed - let openRanges: IRangeLocationInformation[] = []; + const openRanges: IRangeLocationInformation[] = []; /// A list of ranges we've collected so far */ let localRanges: Range[] = []; @@ -2673,7 +2673,7 @@ namespace FourSlash { let line = 1; let column = 1; - let flush = (lastSafeCharIndex: number) => { + const flush = (lastSafeCharIndex: number) => { if (lastSafeCharIndex === undefined) { output = output + content.substr(lastNormalCharPosition); } @@ -2685,7 +2685,7 @@ namespace FourSlash { if (content.length > 0) { let previousChar = content.charAt(0); for (let i = 1; i < content.length; i++) { - let currentChar = content.charAt(i); + const currentChar = content.charAt(i); switch (state) { case State.none: if (previousChar === "[" && currentChar === "|") { @@ -2703,12 +2703,12 @@ namespace FourSlash { } else if (previousChar === "|" && currentChar === "]") { // found a range end - let rangeStart = openRanges.pop(); + const rangeStart = openRanges.pop(); if (!rangeStart) { reportError(fileName, line, column, "Found range end with no matching start."); } - let range: Range = { + const range: Range = { fileName: fileName, start: rangeStart.position, end: (i - 1) - difference, @@ -2748,8 +2748,8 @@ namespace FourSlash { // Object markers are only ever terminated by |} and have no content restrictions if (previousChar === "|" && currentChar === "}") { // Record the marker - let objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - let marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); + const objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + const marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2769,8 +2769,8 @@ namespace FourSlash { if (previousChar === "*" && currentChar === "/") { // Record the marker // start + 2 to ignore the */, -1 on the end to ignore the * (/ is next) - let markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - let marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); + const markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + const marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2821,7 +2821,7 @@ namespace FourSlash { flush(undefined); if (openRanges.length > 0) { - let openRange = openRanges[0]; + const openRange = openRanges[0]; reportError(fileName, openRange.sourceLine, openRange.sourceColumn, "Unterminated range."); } diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts index 867c0d5a4d6..7228f06c20f 100644 --- a/src/harness/fourslashRunner.ts +++ b/src/harness/fourslashRunner.ts @@ -45,10 +45,10 @@ class FourSlashRunner extends RunnerBase { this.tests.forEach((fn: string) => { describe(fn, () => { fn = ts.normalizeSlashes(fn); - let justName = fn.replace(/^.*[\\\/]/, ""); + const justName = fn.replace(/^.*[\\\/]/, ""); // Convert to relative path - let testIndex = fn.indexOf("tests/"); + const testIndex = fn.indexOf("tests/"); if (testIndex >= 0) fn = fn.substr(testIndex); if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) { @@ -60,21 +60,21 @@ class FourSlashRunner extends RunnerBase { }); describe("Generate Tao XML", () => { - let invalidReasons: any = {}; + const invalidReasons: any = {}; FourSlash.xmlData.forEach(xml => { if (xml.invalidReason !== null) { invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1; } }); - let invalidReport: { reason: string; count: number }[] = []; - for (let reason in invalidReasons) { + const invalidReport: { reason: string; count: number }[] = []; + for (const reason in invalidReasons) { if (invalidReasons.hasOwnProperty(reason)) { invalidReport.push({ reason: reason, count: invalidReasons[reason] }); } } invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1); - let lines: string[] = []; + const lines: string[] = []; lines.push("